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.conf import configmgr
25 from mic.plugin import pluginmgr
26 from mic.imager.loop import LoopImageCreator, load_mountpoints
28 from mic.pluginbase import ImagerPlugin
29 class LoopPlugin(ImagerPlugin):
33 def do_create(self, args):
34 """${cmd_name}: create loop image
37 ${name} ${cmd_name} <ksfile> [OPTS]
43 raise errors.Usage("Invalid arguments")
45 creatoropts = configmgr.create
48 if creatoropts['runtime'] == "bootstrap":
49 configmgr._ksconf = ksconf
50 rt_util.bootstrap_mic()
53 if len(creatoropts['record_pkgs']) > 0:
54 recording_pkgs = creatoropts['record_pkgs']
56 if creatoropts['release'] is not None:
57 if 'name' not in recording_pkgs:
58 recording_pkgs.append('name')
59 if 'vcs' not in recording_pkgs:
60 recording_pkgs.append('vcs')
62 configmgr._ksconf = ksconf
64 # try to find the pkgmgr
66 backends = pluginmgr.get_plugins('backend')
67 if 'auto' == creatoropts['pkgmgr']:
68 for key in configmgr.prefer_backends:
70 pkgmgr = backends[key]
73 for key in backends.keys():
74 if key == creatoropts['pkgmgr']:
75 pkgmgr = backends[key]
79 raise errors.CreatorError("Can't find backend: %s, "
80 "available choices: %s" %
81 (creatoropts['pkgmgr'],
82 ','.join(backends.keys())))
84 creator = LoopImageCreator(creatoropts,
89 if len(recording_pkgs) > 0:
90 creator._recording_pkgs = recording_pkgs
92 image_names = [creator.name + ".img"]
93 image_names.extend(creator.get_image_names())
94 self.check_image_exists(creator.destdir,
97 creatoropts['release'])
100 creator.check_depend_tools()
101 creator.mount(None, creatoropts["cachedir"])
103 creator.configure(creatoropts["repomd"])
104 creator.copy_kernel()
105 creator.create_cpio_image()
107 creator.package(creatoropts["destdir"])
108 creator.create_manifest()
110 if creatoropts['release'] is not None:
111 creator.release_output(ksconf,
112 creatoropts['destdir'],
113 creatoropts['release'])
114 creator.print_outimage_info()
116 except errors.CreatorError:
121 msger.info("Finished.")
125 def _do_chroot_tar(cls, target, cmd=[]):
126 mountfp_xml = os.path.splitext(target)[0] + '.xml'
127 if not os.path.exists(mountfp_xml):
128 raise errors.CreatorError("No mount point file found for this tar "
129 "image, please check %s" % mountfp_xml)
132 tar = tarfile.open(target, 'r')
133 tmpdir = misc.mkdtemp()
134 tar.extractall(path=tmpdir)
137 mntdir = misc.mkdtemp()
140 for (mp, label, name, size, fstype) in load_mountpoints(mountfp_xml):
141 if fstype in ("ext2", "ext3", "ext4"):
142 myDiskMount = fs_related.ExtDiskMount
143 elif fstype == "btrfs":
144 myDiskMount = fs_related.BtrfsDiskMount
145 elif fstype in ("vfat", "msdos"):
146 myDiskMount = fs_related.VfatDiskMount
148 raise errors.CreatorError("Cannot support fstype: %s" % fstype)
150 name = os.path.join(tmpdir, name)
151 size = size * 1024L * 1024L
152 loop = myDiskMount(fs_related.SparseLoopbackDisk(name, size),
153 os.path.join(mntdir, mp.lstrip('/')),
157 msger.verbose("Mount %s to %s" % (mp, mntdir + mp))
158 fs_related.makedirs(os.path.join(mntdir, mp.lstrip('/')))
163 for lp in reversed(loops):
164 chroot.cleanup_after_chroot("img", lp, None, mntdir)
166 shutil.rmtree(tmpdir, ignore_errors=True)
173 cmdline = "/usr/bin/env HOME=/root " + ' '.join(cmd)
175 cmdline = "/usr/bin/env HOME=/root /bin/bash"
176 chroot.chroot(mntdir, None, cmdline)
178 raise errors.CreatorError("Failed to chroot to %s." % target)
180 for loop in reversed(loops):
181 chroot.cleanup_after_chroot("img", loop, None, mntdir)
183 shutil.rmtree(tmpdir, ignore_errors=True)
186 def do_chroot(cls, target, cmd=[]):
187 if target.endswith('.tar'):
189 if tarfile.is_tarfile(target):
190 LoopPlugin._do_chroot_tar(target, cmd)
193 raise errors.CreatorError("damaged tarball for loop images")
196 imgsize = misc.get_file_size(img) * 1024L * 1024L
197 imgtype = misc.get_image_type(img)
198 if imgtype == "btrfsimg":
200 myDiskMount = fs_related.BtrfsDiskMount
201 elif imgtype in ("ext3fsimg", "ext4fsimg"):
203 myDiskMount = fs_related.ExtDiskMount
205 raise errors.CreatorError("Unsupported filesystem type: %s" \
208 extmnt = misc.mkdtemp()
209 extloop = myDiskMount(fs_related.SparseLoopbackDisk(img, imgsize),
217 except errors.MountError:
219 shutil.rmtree(extmnt, ignore_errors=True)
226 cmdline = "/bin/bash"
227 envcmd = fs_related.find_binary_inchroot("env", extmnt)
229 cmdline = "%s HOME=/root %s" % (envcmd, cmdline)
230 chroot.chroot(extmnt, None, cmdline)
232 raise errors.CreatorError("Failed to chroot to %s." % img)
234 chroot.cleanup_after_chroot("img", extloop, None, extmnt)
237 def do_unpack(cls, srcimg):
238 image = os.path.join(tempfile.mkdtemp(dir="/var/tmp", prefix="tmp"),
240 msger.info("Copying file system ...")
241 shutil.copyfile(srcimg, image)