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, rt_util
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]
45 raise errors.Usage("Extra arguments given")
47 creatoropts = configmgr.create
50 if creatoropts['runtime'] == "bootstrap":
51 configmgr._ksconf = ksconf
52 rt_util.bootstrap_mic()
54 if creatoropts['arch'] and creatoropts['arch'].startswith('arm'):
55 msger.warning('liveusb cannot support arm images, Quit')
59 if len(creatoropts['record_pkgs']) > 0:
60 recording_pkgs = creatoropts['record_pkgs']
62 if creatoropts['release'] is not None:
63 if 'name' not in recording_pkgs:
64 recording_pkgs.append('name')
65 if 'vcs' not in recording_pkgs:
66 recording_pkgs.append('vcs')
68 configmgr._ksconf = ksconf
70 # try to find the pkgmgr
72 backends = pluginmgr.get_plugins('backend')
73 if 'auto' == creatoropts['pkgmgr']:
74 for key in configmgr.prefer_backends:
76 pkgmgr = backends[key]
79 for key in backends.keys():
80 if key == creatoropts['pkgmgr']:
81 pkgmgr = backends[key]
85 raise errors.CreatorError("Can't find backend: %s, "
86 "available choices: %s" %
87 (creatoropts['pkgmgr'],
88 ','.join(backends.keys())))
90 creator = liveusb.LiveUSBImageCreator(creatoropts, pkgmgr)
92 if len(recording_pkgs) > 0:
93 creator._recording_pkgs = recording_pkgs
95 self.check_image_exists(creator.destdir,
97 [creator.name + ".usbimg"],
98 creatoropts['release'])
100 creator.check_depend_tools()
101 creator.mount(None, creatoropts["cachedir"])
103 creator.configure(creatoropts["repomd"])
104 creator.copy_kernel()
106 creator.package(creatoropts["destdir"])
107 creator.create_manifest()
108 if creatoropts['release'] is not None:
109 creator.release_output(ksconf, creatoropts['destdir'], creatoropts['release'])
110 creator.print_outimage_info()
112 except errors.CreatorError:
117 msger.info("Finished.")
121 def do_chroot(cls, target, cmd=[]):
122 os_image = cls.do_unpack(target)
123 os_image_dir = os.path.dirname(os_image)
125 # unpack image to target dir
126 imgsize = misc.get_file_size(os_image) * 1024L * 1024L
127 imgtype = misc.get_image_type(os_image)
128 if imgtype == "btrfsimg":
130 myDiskMount = fs_related.BtrfsDiskMount
131 elif imgtype in ("ext3fsimg", "ext4fsimg"):
133 myDiskMount = fs_related.ExtDiskMount
135 raise errors.CreatorError("Unsupported filesystem type: %s" % fstype)
137 extmnt = misc.mkdtemp()
138 extloop = myDiskMount(fs_related.SparseLoopbackDisk(os_image, imgsize),
147 except errors.MountError:
149 shutil.rmtree(extmnt, ignore_errors = True)
154 cmdline = ' '.join(cmd)
156 cmdline = "/bin/bash"
157 envcmd = fs_related.find_binary_inchroot("env", extmnt)
159 cmdline = "%s HOME=/root %s" % (envcmd, cmdline)
160 chroot.chroot(extmnt, None, cmdline)
162 raise errors.CreatorError("Failed to chroot to %s." %target)
164 chroot.cleanup_after_chroot("img", extloop, os_image_dir, extmnt)
167 def do_pack(cls, base_on):
170 def __mkinitrd(instance):
171 kernelver = instance._get_kernel_versions().values()[0][0]
172 args = [ "/usr/libexec/mkliveinitrd", "/boot/initrd-%s.img" % kernelver, "%s" % kernelver ]
174 subprocess.call(args, preexec_fn = instance._chroot)
176 except OSError, (err, msg):
177 raise errors.CreatorError("Failed to execute /usr/libexec/mkliveinitrd: %s" % msg)
179 def __run_post_cleanups(instance):
180 kernelver = instance._get_kernel_versions().values()[0][0]
181 args = ["rm", "-f", "/boot/initrd-%s.img" % kernelver]
184 subprocess.call(args, preexec_fn = instance._chroot)
185 except OSError, (err, msg):
186 raise errors.CreatorError("Failed to run post cleanups: %s" % msg)
188 convertoropts = configmgr.convert
189 convertoropts['name'] = os.path.splitext(os.path.basename(base_on))[0]
190 convertor = liveusb.LiveUSBImageCreator(convertoropts)
191 imgtype = misc.get_image_type(base_on)
192 if imgtype == "btrfsimg":
194 elif imgtype in ("ext3fsimg", "ext4fsimg"):
197 raise errors.CreatorError("Unsupported filesystem type: %s" % fstyp)
198 convertor._set_fstype(fstype)
200 convertor.mount(base_on)
201 __mkinitrd(convertor)
202 convertor._create_bootconfig()
203 __run_post_cleanups(convertor)
204 convertor.launch_shell(convertoropts['shell'])
207 convertor.print_outimage_info()
209 shutil.rmtree(os.path.dirname(base_on), ignore_errors = True)
212 def do_unpack(cls, srcimg):
214 imgsize = misc.get_file_size(img) * 1024L * 1024L
215 imgmnt = misc.mkdtemp()
216 disk = fs_related.SparseLoopbackDisk(img, imgsize)
217 imgloop = PartitionedMount(imgmnt, skipformat = True)
218 imgloop.add_disk('/dev/sdb', disk)
219 imgloop.add_partition(imgsize/1024/1024, "/dev/sdb", "/", "vfat", boot=False)
222 except errors.MountError:
226 # legacy LiveOS filesystem layout support, remove for F9 or F10
227 if os.path.exists(imgmnt + "/squashfs.img"):
228 squashimg = imgmnt + "/squashfs.img"
230 squashimg = imgmnt + "/LiveOS/squashfs.img"
232 tmpoutdir = misc.mkdtemp()
233 # unsquashfs requires outdir mustn't exist
234 shutil.rmtree(tmpoutdir, ignore_errors = True)
235 misc.uncompress_squashfs(squashimg, tmpoutdir)
238 # legacy LiveOS filesystem layout support, remove for F9 or F10
239 if os.path.exists(tmpoutdir + "/os.img"):
240 os_image = tmpoutdir + "/os.img"
242 os_image = tmpoutdir + "/LiveOS/ext3fs.img"
244 if not os.path.exists(os_image):
245 raise errors.CreatorError("'%s' is not a valid live CD ISO : neither "
246 "LiveOS/ext3fs.img nor os.img exist" %img)
247 imgname = os.path.basename(srcimg)
248 imgname = os.path.splitext(imgname)[0] + ".img"
249 rtimage = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), imgname)
250 shutil.copyfile(os_image, rtimage)
254 shutil.rmtree(tmpoutdir, ignore_errors = True)
255 shutil.rmtree(imgmnt, ignore_errors = True)