3 # Copyright (c) 2011 Intel, Inc.
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
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
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.
22 from mic import chroot, msger
23 from mic.utils import misc, fs_related, errors
24 from mic.utils.partitionedfs import PartitionedMount
25 from mic.conf import configmgr
26 from mic.plugin import pluginmgr
28 import mic.imager.liveusb as liveusb
30 from mic.pluginbase import ImagerPlugin
31 class LiveUSBPlugin(ImagerPlugin):
35 def do_create(self, subcmd, opts, *args):
36 """${cmd_name}: create liveusb image
39 ${name} ${cmd_name} <ksfile> [OPTS]
44 creatoropts = configmgr.create
47 if creatoropts['arch'] and creatoropts['arch'].startswith('arm'):
48 msger.warning('liveusb cannot support arm images, Quit')
52 if len(creatoropts['record_pkgs']) > 0:
53 recording_pkgs = creatoropts['record_pkgs']
55 if creatoropts['release'] is not None:
56 if 'name' not in recording_pkgs:
57 recording_pkgs.append('name')
59 ksconf = misc.normalize_ksfile(ksconf,
60 creatoropts['release'],
63 configmgr._ksconf = ksconf
65 # Called After setting the configmgr._ksconf as the creatoropts['name'] is reset there.
66 if creatoropts['release'] is not None:
67 creatoropts['outdir'] = "%s/%s/images/%s/" % (creatoropts['outdir'], creatoropts['release'], creatoropts['name'])
69 # try to find the pkgmgr
71 for (key, pcls) in pluginmgr.get_plugins('backend').iteritems():
72 if key == creatoropts['pkgmgr']:
77 pkgmgrs = pluginmgr.get_plugins('backend').keys()
78 raise errors.CreatorError("Can't find package manager: %s (availables: %s)" % (creatoropts['pkgmgr'], ', '.join(pkgmgrs)))
80 creator = liveusb.LiveUSBImageCreator(creatoropts, pkgmgr)
82 if len(recording_pkgs) > 0:
83 creator._recording_pkgs = recording_pkgs
85 self.check_image_exists(creator.destdir,
87 [creator.name + ".usbimg"],
88 creatoropts['release'])
90 creator.check_depend_tools()
91 creator.mount(None, creatoropts["cachedir"])
93 creator.configure(creatoropts["repomd"])
96 creator.package(creatoropts["outdir"])
97 if creatoropts['release'] is not None:
98 creator.release_output(ksconf, creatoropts['outdir'], creatoropts['release'])
99 creator.print_outimage_info()
101 except errors.CreatorError:
106 msger.info("Finished.")
110 def do_chroot(cls, target):
111 os_image = cls.do_unpack(target)
112 os_image_dir = os.path.dirname(os_image)
114 # unpack image to target dir
115 imgsize = misc.get_file_size(os_image) * 1024L * 1024L
116 imgtype = misc.get_image_type(os_image)
117 if imgtype == "btrfsimg":
119 myDiskMount = fs_related.BtrfsDiskMount
120 elif imgtype in ("ext3fsimg", "ext4fsimg"):
122 myDiskMount = fs_related.ExtDiskMount
124 raise errors.CreatorError("Unsupported filesystem type: %s" % fstype)
126 extmnt = misc.mkdtemp()
127 extloop = myDiskMount(fs_related.SparseLoopbackDisk(os_image, imgsize),
136 except errors.MountError:
138 shutil.rmtree(extmnt, ignore_errors = True)
142 envcmd = fs_related.find_binary_inchroot("env", extmnt)
144 cmdline = "%s HOME=/root /bin/bash" % envcmd
146 cmdline = "/bin/bash"
147 chroot.chroot(extmnt, None, cmdline)
149 raise errors.CreatorError("Failed to chroot to %s." %target)
151 chroot.cleanup_after_chroot("img", extloop, os_image_dir, extmnt)
154 def do_pack(cls, base_on):
157 def __mkinitrd(instance):
158 kernelver = instance._get_kernel_versions().values()[0][0]
159 args = [ "/usr/libexec/mkliveinitrd", "/boot/initrd-%s.img" % kernelver, "%s" % kernelver ]
161 subprocess.call(args, preexec_fn = instance._chroot)
163 except OSError, (err, msg):
164 raise errors.CreatorError("Failed to execute /usr/libexec/mkliveinitrd: %s" % msg)
166 def __run_post_cleanups(instance):
167 kernelver = instance._get_kernel_versions().values()[0][0]
168 args = ["rm", "-f", "/boot/initrd-%s.img" % kernelver]
171 subprocess.call(args, preexec_fn = instance._chroot)
172 except OSError, (err, msg):
173 raise errors.CreatorError("Failed to run post cleanups: %s" % msg)
175 convertoropts = configmgr.convert
176 convertoropts['name'] = os.path.splitext(os.path.basename(base_on))[0]
177 convertor = liveusb.LiveUSBImageCreator(convertoropts)
178 imgtype = misc.get_image_type(base_on)
179 if imgtype == "btrfsimg":
181 elif imgtype in ("ext3fsimg", "ext4fsimg"):
184 raise errors.CreatorError("Unsupported filesystem type: %s" % fstyp)
185 convertor._set_fstype(fstype)
187 convertor.mount(base_on)
188 __mkinitrd(convertor)
189 convertor._create_bootconfig()
190 __run_post_cleanups(convertor)
191 convertor.launch_shell(convertoropts['shell'])
194 convertor.print_outimage_info()
196 shutil.rmtree(os.path.dirname(base_on), ignore_errors = True)
199 def do_unpack(cls, srcimg):
201 imgsize = misc.get_file_size(img) * 1024L * 1024L
202 imgmnt = misc.mkdtemp()
203 disk = fs_related.SparseLoopbackDisk(img, imgsize)
204 imgloop = PartitionedMount({'/dev/sdb':disk}, imgmnt, skipformat = True)
205 imgloop.add_partition(imgsize/1024/1024, "/dev/sdb", "/", "vfat", boot=False)
208 except errors.MountError:
212 # legacy LiveOS filesystem layout support, remove for F9 or F10
213 if os.path.exists(imgmnt + "/squashfs.img"):
214 squashimg = imgmnt + "/squashfs.img"
216 squashimg = imgmnt + "/LiveOS/squashfs.img"
218 tmpoutdir = misc.mkdtemp()
219 # unsquashfs requires outdir mustn't exist
220 shutil.rmtree(tmpoutdir, ignore_errors = True)
221 misc.uncompress_squashfs(squashimg, tmpoutdir)
224 # legacy LiveOS filesystem layout support, remove for F9 or F10
225 if os.path.exists(tmpoutdir + "/os.img"):
226 os_image = tmpoutdir + "/os.img"
228 os_image = tmpoutdir + "/LiveOS/ext3fs.img"
230 if not os.path.exists(os_image):
231 raise errors.CreatorError("'%s' is not a valid live CD ISO : neither "
232 "LiveOS/ext3fs.img nor os.img exist" %img)
233 imgname = os.path.basename(srcimg)
234 imgname = os.path.splitext(imgname)[0] + ".img"
235 rtimage = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), imgname)
236 shutil.copyfile(os_image, rtimage)
240 shutil.rmtree(tmpoutdir, ignore_errors = True)
241 shutil.rmtree(imgmnt, ignore_errors = True)