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