680217ec92be0a3bf3fb03136d5e6d2b3a22b516
[tools/mic.git] / plugins / imager / livecd_plugin.py
1 #!/usr/bin/python -tt
2 #
3 # Copyright (c) 2011 Intel, Inc.
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the Free
7 # Software Foundation; version 2 of the License
8 #
9 # This program is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 # for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with this program; if not, write to the Free Software Foundation, Inc., 59
16 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18 import os
19 import shutil
20 import tempfile
21
22 from mic import chroot, msger
23 from mic.utils import misc, fs_related, errors
24 from mic.conf import configmgr
25 import mic.imager.livecd as livecd
26 from mic.plugin import pluginmgr
27
28 from mic.pluginbase import ImagerPlugin
29 class LiveCDPlugin(ImagerPlugin):
30     name = 'livecd'
31
32     @classmethod
33     def do_create(self, subcmd, opts, *args):
34         """${cmd_name}: create livecd image
35
36         Usage:
37             ${name} ${cmd_name} <ksfile> [OPTS]
38
39         ${cmd_option_list}
40         """
41
42         creatoropts = configmgr.create
43         ksconf = args[0]
44
45         if creatoropts['arch'] and creatoropts['arch'].startswith('arm'):
46             msger.warning('livecd cannot support arm images, Quit')
47             return
48
49         recording_pkgs = []
50         if len(creatoropts['record_pkgs']) > 0:
51             recording_pkgs = creatoropts['record_pkgs']
52
53         if creatoropts['release'] is not None:
54             if 'name' not in recording_pkgs:
55                 recording_pkgs.append('name')
56
57         ksconf = misc.normalize_ksfile(ksconf,
58                                        creatoropts['release'],
59                                        creatoropts['arch'])
60
61         configmgr._ksconf = ksconf
62
63         # Called After setting the configmgr._ksconf as the creatoropts['name'] is reset there.
64         if creatoropts['release'] is not None:
65             creatoropts['outdir'] = "%s/%s/images/%s/" % (creatoropts['outdir'], creatoropts['release'], creatoropts['name'])
66
67         # try to find the pkgmgr
68         pkgmgr = None
69         for (key, pcls) in pluginmgr.get_plugins('backend').iteritems():
70             if key == creatoropts['pkgmgr']:
71                 pkgmgr = pcls
72                 break
73
74         if not pkgmgr:
75             pkgmgrs = pluginmgr.get_plugins('backend').keys()
76             raise errors.CreatorError("Can't find package manager: %s (availables: %s)" % (creatoropts['pkgmgr'], ', '.join(pkgmgrs)))
77
78         creator = livecd.LiveCDImageCreator(creatoropts, pkgmgr)
79
80         if len(recording_pkgs) > 0:
81             creator._recording_pkgs = recording_pkgs
82
83         self.check_image_exists(creator.destdir,
84                                 creator.pack_to,
85                                 [creator.name + ".iso"],
86                                 creatoropts['release'])
87
88         try:
89             creator.check_depend_tools()
90             creator.mount(None, creatoropts["cachedir"])
91             creator.install()
92             creator.configure(creatoropts["repomd"])
93             creator.copy_kernel()
94             creator.unmount()
95             creator.package(creatoropts["outdir"])
96             if creatoropts['release'] is not None:
97                 creator.release_output(ksconf, creatoropts['outdir'], creatoropts['release'])
98             creator.print_outimage_info()
99
100         except errors.CreatorError:
101             raise
102         finally:
103             creator.cleanup()
104
105         msger.info("Finished.")
106         return 0
107
108     @classmethod
109     def do_chroot(cls, target):
110         os_image = cls.do_unpack(target)
111         os_image_dir = os.path.dirname(os_image)
112
113         # unpack image to target dir
114         imgsize = misc.get_file_size(os_image) * 1024L * 1024L
115         imgtype = misc.get_image_type(os_image)
116         if imgtype == "btrfsimg":
117             fstype = "btrfs"
118             myDiskMount = fs_related.BtrfsDiskMount
119         elif imgtype in ("ext3fsimg", "ext4fsimg"):
120             fstype = imgtype[:4]
121             myDiskMount = fs_related.ExtDiskMount
122         else:
123             raise errors.CreatorError("Unsupported filesystem type: %s" % fstype)
124
125         extmnt = misc.mkdtemp()
126         extloop = myDiskMount(fs_related.SparseLoopbackDisk(os_image, imgsize),
127                               extmnt,
128                               fstype,
129                               4096,
130                               "%s label" % fstype)
131         try:
132             extloop.mount()
133
134         except errors.MountError:
135             extloop.cleanup()
136             shutil.rmtree(extmnt, ignore_errors = True)
137             shutil.rmtree(os_image_dir, ignore_errors = True)
138             raise
139
140         try:
141             envcmd = fs_related.find_binary_inchroot("env", extmnt)
142             if envcmd:
143                 cmdline = "%s HOME=/root /bin/bash" % envcmd
144             else:
145                 cmdline = "/bin/bash"
146             chroot.chroot(extmnt, None, cmdline)
147         except:
148             raise errors.CreatorError("Failed to chroot to %s." %target)
149         finally:
150             chroot.cleanup_after_chroot("img", extloop, os_image_dir, extmnt)
151
152     @classmethod
153     def do_pack(cls, base_on):
154         import subprocess
155
156         def __mkinitrd(instance):
157             kernelver = instance._get_kernel_versions().values()[0][0]
158             args = [ "/usr/libexec/mkliveinitrd", "/boot/initrd-%s.img" % kernelver, "%s" % kernelver ]
159             try:
160                 subprocess.call(args, preexec_fn = instance._chroot)
161             except OSError, (err, msg):
162                raise errors.CreatorError("Failed to execute /usr/libexec/mkliveinitrd: %s" % msg)
163
164         def __run_post_cleanups(instance):
165             kernelver = instance._get_kernel_versions().values()[0][0]
166             args = ["rm", "-f", "/boot/initrd-%s.img" % kernelver]
167
168             try:
169                 subprocess.call(args, preexec_fn = instance._chroot)
170             except OSError, (err, msg):
171                raise errors.CreatorError("Failed to run post cleanups: %s" % msg)
172
173         convertoropts = configmgr.convert
174         convertoropts['name'] = os.path.splitext(os.path.basename(base_on))[0]
175         convertor = livecd.LiveCDImageCreator(convertoropts)
176         imgtype = misc.get_image_type(base_on)
177         if imgtype == "btrfsimg":
178             fstype = "btrfs"
179         elif imgtype in ("ext3fsimg", "ext4fsimg"):
180             fstype = imgtype[:4]
181         else:
182             raise errors.CreatorError("Unsupported filesystem type: %s" % fstype)
183         convertor._set_fstype(fstype)
184         try:
185             convertor.mount(base_on)
186             __mkinitrd(convertor)
187             convertor._create_bootconfig()
188             __run_post_cleanups(convertor)
189             convertor.launch_shell(convertoropts['shell'])
190             convertor.unmount()
191             convertor.package()
192             convertor.print_outimage_info()
193         finally:
194             shutil.rmtree(os.path.dirname(base_on), ignore_errors = True)
195
196     @classmethod
197     def do_unpack(cls, srcimg):
198         img = srcimg
199         imgmnt = misc.mkdtemp()
200         imgloop = fs_related.DiskMount(fs_related.LoopbackDisk(img, 0), imgmnt)
201         try:
202             imgloop.mount()
203         except errors.MountError:
204             imgloop.cleanup()
205             raise
206
207         # legacy LiveOS filesystem layout support, remove for F9 or F10
208         if os.path.exists(imgmnt + "/squashfs.img"):
209             squashimg = imgmnt + "/squashfs.img"
210         else:
211             squashimg = imgmnt + "/LiveOS/squashfs.img"
212
213         tmpoutdir = misc.mkdtemp()
214         # unsquashfs requires outdir mustn't exist
215         shutil.rmtree(tmpoutdir, ignore_errors = True)
216         misc.uncompress_squashfs(squashimg, tmpoutdir)
217
218         try:
219             # legacy LiveOS filesystem layout support, remove for F9 or F10
220             if os.path.exists(tmpoutdir + "/os.img"):
221                 os_image = tmpoutdir + "/os.img"
222             else:
223                 os_image = tmpoutdir + "/LiveOS/ext3fs.img"
224
225             if not os.path.exists(os_image):
226                 raise errors.CreatorError("'%s' is not a valid live CD ISO : neither "
227                                           "LiveOS/ext3fs.img nor os.img exist" %img)
228
229             imgname = os.path.basename(srcimg)
230             imgname = os.path.splitext(imgname)[0] + ".img"
231             rtimage = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), imgname)
232             shutil.copyfile(os_image, rtimage)
233
234         finally:
235             imgloop.cleanup()
236             shutil.rmtree(tmpoutdir, ignore_errors = True)
237             shutil.rmtree(imgmnt, ignore_errors = True)
238
239         return rtimage