show available pkgmgrs if invalid one encountered
[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, runner
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             raise errors.Usage("Extra arguments given")
48
49         cfgmgr = configmgr.getConfigMgr()
50         creatoropts = cfgmgr.create
51         ksconf = args[0]
52
53         recording_pkgs = None
54         if creatoropts['release'] is not None:
55             recording_pkgs = "name"
56             ksconf = misc.save_ksconf_file(ksconf, creatoropts['release'])
57             name = os.path.splitext(os.path.basename(ksconf))[0]
58             creatoropts['outdir'] = "%s/%s-%s/" % (creatoropts['outdir'], name, creatoropts['release'])
59         cfgmgr._ksconf = ksconf
60
61         # try to find the pkgmgr
62         pkgmgr = None
63         for (key, pcls) in pluginmgr.PluginMgr().get_plugins('backend').iteritems():
64             if key == creatoropts['pkgmgr']:
65                 pkgmgr = pcls
66                 break
67
68         if not pkgmgr:
69             pkgmgrs = pluginmgr.PluginMgr().get_plugins('backend').keys()
70             raise errors.CreatorError("Can't find package manager: %s (availables: %s)" % (creatoropts['pkgmgr'], ', '.join(pkgmgrs)))
71
72         creator = raw.RawImageCreator(creatoropts, pkgmgr)
73
74         if recording_pkgs is not None:
75             creator._recording_pkgs = recording_pkgs
76
77         try:
78             creator.check_depend_tools()
79             creator.mount(None, creatoropts["cachedir"])
80             creator.install()
81             creator.configure(creatoropts["repomd"])
82             creator.unmount()
83             creator.package(creatoropts["outdir"])
84             if creatoropts['release'] is not None:
85                 creator.release_output(ksconf, creatoropts['outdir'], creatoropts['name'], creatoropts['release'])
86             creator.print_outimage_info()
87
88         except errors.CreatorError:
89             raise
90         finally:
91             creator.cleanup()
92
93         msger.info("Finished.")
94         return 0
95
96     @classmethod
97     def do_chroot(cls, target):
98         img = target
99         imgsize = misc.get_file_size(img) * 1024L * 1024L
100         partedcmd = fs_related.find_binary_path("parted")
101         disk = fs_related.SparseLoopbackDisk(img, imgsize)
102         imgmnt = misc.mkdtemp()
103         imgloop = PartitionedMount({'/dev/sdb':disk}, imgmnt, skipformat = True)
104         img_fstype = "ext3"
105
106         # Check the partitions from raw disk.
107         root_mounted = False
108         partition_mounts = 0
109         for line in runner.outs([partedcmd,"-s",img,"unit","B","print"]).splitlines():
110             line = line.strip()
111
112             # Lines that start with number are the partitions,
113             # because parted can be translated we can't refer to any text lines.
114             if not line or not line[0].isdigit():
115                 continue
116
117             # Some vars have extra , as list seperator.
118             line = line.replace(",","")
119
120             # Example of parted output lines that are handled:
121             # Number  Start        End          Size         Type     File system     Flags
122             #  1      512B         3400000511B  3400000000B  primary
123             #  2      3400531968B  3656384511B  255852544B   primary  linux-swap(v1)
124             #  3      3656384512B  3720347647B  63963136B    primary  fat16           boot, lba
125
126             partition_info = re.split("\s+",line)
127
128             size = partition_info[3].split("B")[0]
129
130             if len(partition_info) < 6 or partition_info[5] in ["boot"]:
131                 # No filesystem can be found from partition line. Assuming
132                 # btrfs, because that is the only MeeGo fs that parted does
133                 # not recognize properly.
134                 # TODO: Can we make better assumption?
135                 fstype = "btrfs"
136             elif partition_info[5] in ["ext2","ext3","ext4","btrfs"]:
137                 fstype = partition_info[5]
138             elif partition_info[5] in ["fat16","fat32"]:
139                 fstype = "vfat"
140             elif "swap" in partition_info[5]:
141                 fstype = "swap"
142             else:
143                 raise errors.CreatorError("Could not recognize partition fs type '%s'." % partition_info[5])
144
145             if not root_mounted and fstype in ["ext2","ext3","ext4","btrfs"]:
146                 # TODO: Check that this is actually the valid root partition from /etc/fstab
147                 mountpoint = "/"
148                 root_mounted = True
149             elif fstype == "swap":
150                 mountpoint = "swap"
151             else:
152                 # TODO: Assing better mount points for the rest of the partitions.
153                 partition_mounts += 1
154                 mountpoint = "/media/partition_%d" % partition_mounts
155
156             if "boot" in partition_info:
157                 boot = True
158             else:
159                 boot = False
160
161             msger.verbose("Size: %s Bytes, fstype: %s, mountpoint: %s, boot: %s" % (size, fstype, mountpoint, boot))
162             # TODO: add_partition should take bytes as size parameter.
163             imgloop.add_partition((int)(size)/1024/1024, "/dev/sdb", mountpoint, fstype = fstype, boot = boot)
164
165         try:
166             imgloop.mount()
167
168         except errors.MountError:
169             imgloop.cleanup()
170             raise
171
172         try:
173             chroot.chroot(imgmnt, None,  "/bin/env HOME=/root /bin/bash")
174         except:
175             raise errors.CreatorError("Failed to chroot to %s." %img)
176         finally:
177             chroot.cleanup_after_chroot("img", imgloop, None, imgmnt)
178
179     @classmethod
180     def do_unpack(cls, srcimg):
181         srcimgsize = (misc.get_file_size(srcimg)) * 1024L * 1024L
182         srcmnt = misc.mkdtemp("srcmnt")
183         disk = fs_related.SparseLoopbackDisk(srcimg, srcimgsize)
184         srcloop = PartitionedMount({'/dev/sdb':disk}, srcmnt, skipformat = True)
185
186         srcloop.add_partition(srcimgsize/1024/1024, "/dev/sdb", "/", "ext3", boot=False)
187         try:
188             srcloop.mount()
189
190         except errors.MountError:
191             srcloop.cleanup()
192             raise
193
194         image = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), "target.img")
195         args = ['dd', "if=%s" % srcloop.partitions[0]['device'], "of=%s" % image]
196
197         msger.info("`dd` image ...")
198         rc = runner.show(args)
199         srcloop.cleanup()
200         shutil.rmtree(os.path.dirname(srcmnt), ignore_errors = True)
201
202         if rc != 0:
203             raise errors.CreatorError("Failed to dd")
204         else:
205             return image