summaryrefslogtreecommitdiffstats
path: root/scripts/lib/mic/plugins/imager/liveusb_plugin.py
diff options
context:
space:
mode:
Diffstat (limited to 'scripts/lib/mic/plugins/imager/liveusb_plugin.py')
-rw-r--r--scripts/lib/mic/plugins/imager/liveusb_plugin.py260
1 files changed, 260 insertions, 0 deletions
diff --git a/scripts/lib/mic/plugins/imager/liveusb_plugin.py b/scripts/lib/mic/plugins/imager/liveusb_plugin.py
new file mode 100644
index 0000000000..7aa8927df9
--- /dev/null
+++ b/scripts/lib/mic/plugins/imager/liveusb_plugin.py
@@ -0,0 +1,260 @@
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
18import os
19import shutil
20import tempfile
21
22from mic import chroot, msger, rt_util
23from mic.utils import misc, fs_related, errors
24from mic.utils.partitionedfs import PartitionedMount
25from mic.conf import configmgr
26from mic.plugin import pluginmgr
27
28import mic.imager.liveusb as liveusb
29
30from mic.pluginbase import ImagerPlugin
31class LiveUSBPlugin(ImagerPlugin):
32 name = 'liveusb'
33
34 @classmethod
35 def do_create(self, subcmd, opts, *args):
36 """${cmd_name}: create liveusb image
37
38 Usage:
39 ${name} ${cmd_name} <ksfile> [OPTS]
40
41 ${cmd_option_list}
42 """
43
44 if len(args) != 1:
45 raise errors.Usage("Extra arguments given")
46
47 creatoropts = configmgr.create
48 ksconf = args[0]
49
50 if creatoropts['runtime'] == "bootstrap":
51 configmgr._ksconf = ksconf
52 rt_util.bootstrap_mic()
53
54 if creatoropts['arch'] and creatoropts['arch'].startswith('arm'):
55 msger.warning('liveusb cannot support arm images, Quit')
56 return
57
58 recording_pkgs = []
59 if len(creatoropts['record_pkgs']) > 0:
60 recording_pkgs = creatoropts['record_pkgs']
61
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')
67
68 configmgr._ksconf = ksconf
69
70 # Called After setting the configmgr._ksconf as the creatoropts['name'] is reset there.
71 if creatoropts['release'] is not None:
72 creatoropts['outdir'] = "%s/%s/images/%s/" % (creatoropts['outdir'], creatoropts['release'], creatoropts['name'])
73
74 # try to find the pkgmgr
75 pkgmgr = None
76 backends = pluginmgr.get_plugins('backend')
77 if 'auto' == creatoropts['pkgmgr']:
78 for key in configmgr.prefer_backends:
79 if key in backends:
80 pkgmgr = backends[key]
81 break
82 else:
83 for key in backends.keys():
84 if key == creatoropts['pkgmgr']:
85 pkgmgr = backends[key]
86 break
87
88 if not pkgmgr:
89 raise errors.CreatorError("Can't find backend: %s, "
90 "available choices: %s" %
91 (creatoropts['pkgmgr'],
92 ','.join(backends.keys())))
93
94 creator = liveusb.LiveUSBImageCreator(creatoropts, pkgmgr)
95
96 if len(recording_pkgs) > 0:
97 creator._recording_pkgs = recording_pkgs
98
99 self.check_image_exists(creator.destdir,
100 creator.pack_to,
101 [creator.name + ".usbimg"],
102 creatoropts['release'])
103 try:
104 creator.check_depend_tools()
105 creator.mount(None, creatoropts["cachedir"])
106 creator.install()
107 creator.configure(creatoropts["repomd"])
108 creator.copy_kernel()
109 creator.unmount()
110 creator.package(creatoropts["outdir"])
111 if creatoropts['release'] is not None:
112 creator.release_output(ksconf, creatoropts['outdir'], creatoropts['release'])
113 creator.print_outimage_info()
114
115 except errors.CreatorError:
116 raise
117 finally:
118 creator.cleanup()
119
120 msger.info("Finished.")
121 return 0
122
123 @classmethod
124 def do_chroot(cls, target, cmd=[]):
125 os_image = cls.do_unpack(target)
126 os_image_dir = os.path.dirname(os_image)
127
128 # unpack image to target dir
129 imgsize = misc.get_file_size(os_image) * 1024L * 1024L
130 imgtype = misc.get_image_type(os_image)
131 if imgtype == "btrfsimg":
132 fstype = "btrfs"
133 myDiskMount = fs_related.BtrfsDiskMount
134 elif imgtype in ("ext3fsimg", "ext4fsimg"):
135 fstype = imgtype[:4]
136 myDiskMount = fs_related.ExtDiskMount
137 else:
138 raise errors.CreatorError("Unsupported filesystem type: %s" % fstype)
139
140 extmnt = misc.mkdtemp()
141 extloop = myDiskMount(fs_related.SparseLoopbackDisk(os_image, imgsize),
142 extmnt,
143 fstype,
144 4096,
145 "%s label" % fstype)
146
147 try:
148 extloop.mount()
149
150 except errors.MountError:
151 extloop.cleanup()
152 shutil.rmtree(extmnt, ignore_errors = True)
153 raise
154
155 try:
156 if len(cmd) != 0:
157 cmdline = ' '.join(cmd)
158 else:
159 cmdline = "/bin/bash"
160 envcmd = fs_related.find_binary_inchroot("env", extmnt)
161 if envcmd:
162 cmdline = "%s HOME=/root %s" % (envcmd, cmdline)
163 chroot.chroot(extmnt, None, cmdline)
164 except:
165 raise errors.CreatorError("Failed to chroot to %s." %target)
166 finally:
167 chroot.cleanup_after_chroot("img", extloop, os_image_dir, extmnt)
168
169 @classmethod
170 def do_pack(cls, base_on):
171 import subprocess
172
173 def __mkinitrd(instance):
174 kernelver = instance._get_kernel_versions().values()[0][0]
175 args = [ "/usr/libexec/mkliveinitrd", "/boot/initrd-%s.img" % kernelver, "%s" % kernelver ]
176 try:
177 subprocess.call(args, preexec_fn = instance._chroot)
178
179 except OSError, (err, msg):
180 raise errors.CreatorError("Failed to execute /usr/libexec/mkliveinitrd: %s" % msg)
181
182 def __run_post_cleanups(instance):
183 kernelver = instance._get_kernel_versions().values()[0][0]
184 args = ["rm", "-f", "/boot/initrd-%s.img" % kernelver]
185
186 try:
187 subprocess.call(args, preexec_fn = instance._chroot)
188 except OSError, (err, msg):
189 raise errors.CreatorError("Failed to run post cleanups: %s" % msg)
190
191 convertoropts = configmgr.convert
192 convertoropts['name'] = os.path.splitext(os.path.basename(base_on))[0]
193 convertor = liveusb.LiveUSBImageCreator(convertoropts)
194 imgtype = misc.get_image_type(base_on)
195 if imgtype == "btrfsimg":
196 fstype = "btrfs"
197 elif imgtype in ("ext3fsimg", "ext4fsimg"):
198 fstype = imgtype[:4]
199 else:
200 raise errors.CreatorError("Unsupported filesystem type: %s" % fstyp)
201 convertor._set_fstype(fstype)
202 try:
203 convertor.mount(base_on)
204 __mkinitrd(convertor)
205 convertor._create_bootconfig()
206 __run_post_cleanups(convertor)
207 convertor.launch_shell(convertoropts['shell'])
208 convertor.unmount()
209 convertor.package()
210 convertor.print_outimage_info()
211 finally:
212 shutil.rmtree(os.path.dirname(base_on), ignore_errors = True)
213
214 @classmethod
215 def do_unpack(cls, srcimg):
216 img = srcimg
217 imgsize = misc.get_file_size(img) * 1024L * 1024L
218 imgmnt = misc.mkdtemp()
219 disk = fs_related.SparseLoopbackDisk(img, imgsize)
220 imgloop = PartitionedMount(imgmnt, skipformat = True)
221 imgloop.add_disk('/dev/sdb', disk)
222 imgloop.add_partition(imgsize/1024/1024, "/dev/sdb", "/", "vfat", boot=False)
223 try:
224 imgloop.mount()
225 except errors.MountError:
226 imgloop.cleanup()
227 raise
228
229 # legacy LiveOS filesystem layout support, remove for F9 or F10
230 if os.path.exists(imgmnt + "/squashfs.img"):
231 squashimg = imgmnt + "/squashfs.img"
232 else:
233 squashimg = imgmnt + "/LiveOS/squashfs.img"
234
235 tmpoutdir = misc.mkdtemp()
236 # unsquashfs requires outdir mustn't exist
237 shutil.rmtree(tmpoutdir, ignore_errors = True)
238 misc.uncompress_squashfs(squashimg, tmpoutdir)
239
240 try:
241 # legacy LiveOS filesystem layout support, remove for F9 or F10
242 if os.path.exists(tmpoutdir + "/os.img"):
243 os_image = tmpoutdir + "/os.img"
244 else:
245 os_image = tmpoutdir + "/LiveOS/ext3fs.img"
246
247 if not os.path.exists(os_image):
248 raise errors.CreatorError("'%s' is not a valid live CD ISO : neither "
249 "LiveOS/ext3fs.img nor os.img exist" %img)
250 imgname = os.path.basename(srcimg)
251 imgname = os.path.splitext(imgname)[0] + ".img"
252 rtimage = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), imgname)
253 shutil.copyfile(os_image, rtimage)
254
255 finally:
256 imgloop.cleanup()
257 shutil.rmtree(tmpoutdir, ignore_errors = True)
258 shutil.rmtree(imgmnt, ignore_errors = True)
259
260 return rtimage