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