remove improper exception handlings
[tools/mic.git] / plugins / imager / raw_plugin.py
1 #!/usr/bin/python -tt
2 #
3 # Copyright 2011 Intel, Inc.
4 #
5 # This copyrighted material is made available to anyone wishing to use, modify,
6 # copy, or redistribute it subject to the terms and conditions of the GNU
7 # General Public License v.2.  This program is distributed in the hope that it
8 # will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
9 # implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 # See the GNU General Public License for more details.
11 #
12 # You should have received a copy of the GNU General Public License along with
13 # this program; if not, write to the Free Software Foundation, Inc., 51
14 # Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  Any Red Hat
15 # trademarks that are incorporated in the source code or documentation are not
16 # subject to the GNU General Public License and may only be used or replicated
17 # with the express permission of Red Hat, Inc.
18 #
19
20 import os
21 import shutil
22 import re
23 import tempfile
24
25 from mic import configmgr, pluginmgr, chroot, msger
26 from mic.utils import misc, fs_related, errors
27 from mic.utils.partitionedfs import PartitionedMount
28
29 import mic.imager.raw as raw
30
31 from mic.pluginbase import ImagerPlugin
32 class RawPlugin(ImagerPlugin):
33     name = 'raw'
34
35     @classmethod
36     def do_create(self, subcmd, opts, *args):
37         """${cmd_name}: create raw image
38
39         ${cmd_usage}
40         ${cmd_option_list}
41         """
42
43         if not args:
44             raise errors.Usage("More arguments needed")
45
46         if len(args) == 1:
47             ksconf = args[0]
48         else:
49             raise errors.Usage("Extra arguments given")
50
51         cfgmgr = configmgr.getConfigMgr()
52         creatoropts = cfgmgr.create
53         cfgmgr.setProperty("ksconf", ksconf)
54
55         # try to find the pkgmgr
56         pkgmgr = None
57         for (key, pcls) in pluginmgr.PluginMgr().get_plugins('backend').iteritems():
58             if key == creatoropts['pkgmgr']:
59                 pkgmgr = pcls
60                 break
61
62         if not pkgmgr:
63             raise errors.CreatorError("Can't find package manager: %s" % creatoropts['pkgmgr'])
64
65         creator = raw.RawImageCreator(creatoropts, pkgmgr)
66         try:
67             creator.check_depend_tools()
68             creator.mount(None, creatoropts["cachedir"])
69             creator.install()
70             creator.configure(creatoropts["repomd"])
71             creator.unmount()
72             creator.package(creatoropts["outdir"])
73             outimage = creator.outimage
74             creator.print_outimage_info()
75             outimage = creator.outimage
76
77         except errors.CreatorError:
78             raise
79         finally:
80             creator.cleanup()
81
82         msger.info("Finished.")
83         return 0
84
85     @classmethod
86     def do_chroot(cls, target):
87         import subprocess
88
89         img = target
90         imgsize = misc.get_file_size(img) * 1024L * 1024L
91         partedcmd = fs_related.find_binary_path("parted")
92         disk = fs_related.SparseLoopbackDisk(img, imgsize)
93         imgmnt = misc.mkdtemp()
94         imgloop = PartitionedMount({'/dev/sdb':disk}, imgmnt, skipformat = True)
95         img_fstype = "ext3"
96
97         # Check the partitions from raw disk.
98         root_mounted = False
99         partition_mounts = 0
100         for line in subprocess.Popen([partedcmd,"-s",img,"unit","B","print"],
101                                      stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\
102                                              .communicate()[0]\
103                                              .strip()\
104                                              .splitlines():
105
106             line = line.strip()
107
108             # Lines that start with number are the partitions,
109             # because parted can be translated we can't refer to any text lines.
110             if not line or not line[0].isdigit():
111                 continue
112
113             # Some vars have extra , as list seperator.
114             line = line.replace(",","")
115
116             # Example of parted output lines that are handled:
117             # Number  Start        End          Size         Type     File system     Flags
118             #  1      512B         3400000511B  3400000000B  primary
119             #  2      3400531968B  3656384511B  255852544B   primary  linux-swap(v1)
120             #  3      3656384512B  3720347647B  63963136B    primary  fat16           boot, lba
121
122             partition_info = re.split("\s+",line)
123
124             size = partition_info[3].split("B")[0]
125
126             if len(partition_info) < 6 or partition_info[5] in ["boot"]:
127                 # No filesystem can be found from partition line. Assuming
128                 # btrfs, because that is the only MeeGo fs that parted does
129                 # not recognize properly.
130                 # TODO: Can we make better assumption?
131                 fstype = "btrfs"
132             elif partition_info[5] in ["ext2","ext3","ext4","btrfs"]:
133                 fstype = partition_info[5]
134             elif partition_info[5] in ["fat16","fat32"]:
135                 fstype = "vfat"
136             elif "swap" in partition_info[5]:
137                 fstype = "swap"
138             else:
139                 raise errors.CreatorError("Could not recognize partition fs type '%s'." % partition_info[5])
140
141             if not root_mounted and fstype in ["ext2","ext3","ext4","btrfs"]:
142                 # TODO: Check that this is actually the valid root partition from /etc/fstab
143                 mountpoint = "/"
144                 root_mounted = True
145             elif fstype == "swap":
146                 mountpoint = "swap"
147             else:
148                 # TODO: Assing better mount points for the rest of the partitions.
149                 partition_mounts += 1
150                 mountpoint = "/media/partition_%d" % partition_mounts
151
152             if "boot" in partition_info:
153                 boot = True
154             else:
155                 boot = False
156
157             msger.verbose("Size: %s Bytes, fstype: %s, mountpoint: %s, boot: %s" % (size, fstype, mountpoint, boot))
158             # TODO: add_partition should take bytes as size parameter.
159             imgloop.add_partition((int)(size)/1024/1024, "/dev/sdb", mountpoint, fstype = fstype, boot = boot)
160
161         try:
162             imgloop.mount()
163
164         except errors.MountError:
165             imgloop.cleanup()
166             raise
167
168         try:
169             chroot.chroot(imgmnt, None,  "/bin/env HOME=/root /bin/bash")
170         except:
171             raise errors.CreatorError("Failed to chroot to %s." %img)
172         finally:
173             chroot.cleanup_after_chroot("img", imgloop, None, imgmnt)
174
175     @classmethod
176     def do_unpack(cls, srcimg):
177         srcimgsize = (misc.get_file_size(srcimg)) * 1024L * 1024L
178         srcmnt = misc.mkdtemp("srcmnt")
179         disk = fs_related.SparseLoopbackDisk(srcimg, srcimgsize)
180         srcloop = PartitionedMount({'/dev/sdb':disk}, srcmnt, skipformat = True)
181
182         srcloop.add_partition(srcimgsize/1024/1024, "/dev/sdb", "/", "ext3", boot=False)
183         try:
184             srcloop.mount()
185
186         except errors.MountError:
187             srcloop.cleanup()
188             raise
189
190         image = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), "target.img")
191         args = ['dd', "if=%s" % srcloop.partitions[0]['device'], "of=%s" % image]
192
193         msger.info("`dd` image ...")
194         rc = msger.run(args)
195         srcloop.cleanup()
196         shutil.rmtree(srcmnt, ignore_errors = True)
197
198         if rc != 0:
199             raise errors.CreatorError("Failed to dd")
200         else:
201             return image