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()
106 creator.package(creatoropts["destdir"])
107 creator.create_manifest()
109 if creatoropts['release'] is not None:
110 creator.release_output(ksconf,
111 creatoropts['destdir'],
112 creatoropts['release'])
113 creator.print_outimage_info()
115 except errors.CreatorError:
120 msger.info("Finished.")
124 def _do_chroot_tar(cls, target, cmd=[]):
125 mountfp_xml = os.path.splitext(target)[0] + '.xml'
126 if not os.path.exists(mountfp_xml):
127 raise errors.CreatorError("No mount point file found for this tar "
128 "image, please check %s" % mountfp_xml)
131 tar = tarfile.open(target, 'r')
132 tmpdir = misc.mkdtemp()
133 tar.extractall(path=tmpdir)
136 mntdir = misc.mkdtemp()
139 for (mp, label, name, size, fstype) in load_mountpoints(mountfp_xml):
140 if fstype in ("ext2", "ext3", "ext4"):
141 myDiskMount = fs_related.ExtDiskMount
142 elif fstype == "btrfs":
143 myDiskMount = fs_related.BtrfsDiskMount
144 elif fstype in ("vfat", "msdos"):
145 myDiskMount = fs_related.VfatDiskMount
147 raise errors.CreatorError("Cannot support fstype: %s" % fstype)
149 name = os.path.join(tmpdir, name)
150 size = size * 1024L * 1024L
151 loop = myDiskMount(fs_related.SparseLoopbackDisk(name, size),
152 os.path.join(mntdir, mp.lstrip('/')),
156 msger.verbose("Mount %s to %s" % (mp, mntdir + mp))
157 fs_related.makedirs(os.path.join(mntdir, mp.lstrip('/')))
162 for lp in reversed(loops):
163 chroot.cleanup_after_chroot("img", lp, None, mntdir)
165 shutil.rmtree(tmpdir, ignore_errors=True)
172 cmdline = "/usr/bin/env HOME=/root " + ' '.join(cmd)
174 cmdline = "/usr/bin/env HOME=/root /bin/bash"
175 chroot.chroot(mntdir, None, cmdline)
177 raise errors.CreatorError("Failed to chroot to %s." % target)
179 for loop in reversed(loops):
180 chroot.cleanup_after_chroot("img", loop, None, mntdir)
182 shutil.rmtree(tmpdir, ignore_errors=True)
185 def do_chroot(cls, target, cmd=[]):
186 if target.endswith('.tar'):
188 if tarfile.is_tarfile(target):
189 LoopPlugin._do_chroot_tar(target, cmd)
192 raise errors.CreatorError("damaged tarball for loop images")
195 imgsize = misc.get_file_size(img) * 1024L * 1024L
196 imgtype = misc.get_image_type(img)
197 if imgtype == "btrfsimg":
199 myDiskMount = fs_related.BtrfsDiskMount
200 elif imgtype in ("ext3fsimg", "ext4fsimg"):
202 myDiskMount = fs_related.ExtDiskMount
204 raise errors.CreatorError("Unsupported filesystem type: %s" \
207 extmnt = misc.mkdtemp()
208 extloop = myDiskMount(fs_related.SparseLoopbackDisk(img, imgsize),
216 except errors.MountError:
218 shutil.rmtree(extmnt, ignore_errors=True)
225 cmdline = "/bin/bash"
226 envcmd = fs_related.find_binary_inchroot("env", extmnt)
228 cmdline = "%s HOME=/root %s" % (envcmd, cmdline)
229 chroot.chroot(extmnt, None, cmdline)
231 raise errors.CreatorError("Failed to chroot to %s." % img)
233 chroot.cleanup_after_chroot("img", extloop, None, extmnt)
236 def do_unpack(cls, srcimg):
237 image = os.path.join(tempfile.mkdtemp(dir="/var/tmp", prefix="tmp"),
239 msger.info("Copying file system ...")
240 shutil.copyfile(srcimg, image)