auto selecting backend with 'pkgmgr=auto'
[tools/mic.git] / plugins / imager / loop_plugin.py
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
18 import os
19 import shutil
20 import tempfile
21
22 from mic import chroot, msger
23 from mic.utils import misc, fs_related, errors, cmdln
24 from mic.conf import configmgr
25 from mic.plugin import pluginmgr
26 from mic.imager.loop import LoopImageCreator, load_mountpoints
27
28 from mic.pluginbase import ImagerPlugin
29 class LoopPlugin(ImagerPlugin):
30     name = 'loop'
31
32     @classmethod
33     @cmdln.option("--compress-disk-image", dest="compress_image",
34                   type='choice', choices=("gz", "bz2"), default=None,
35                   help="Same with --compress-image")
36                   # alias to compress-image for compatibility
37     @cmdln.option("--compress-image", dest="compress_image",
38                   type='choice', choices=("gz", "bz2"), default=None,
39                   help="Compress all loop images with 'gz' or 'bz2'")
40     @cmdln.option("--shrink", action='store_true', default=False,
41                   help="Whether to shrink loop images to minimal size")
42     def do_create(self, subcmd, opts, *args):
43         """${cmd_name}: create loop image
44
45         Usage:
46             ${name} ${cmd_name} <ksfile> [OPTS]
47
48         ${cmd_option_list}
49         """
50
51         creatoropts = configmgr.create
52         ksconf = args[0]
53
54         recording_pkgs = []
55         if len(creatoropts['record_pkgs']) > 0:
56             recording_pkgs = creatoropts['record_pkgs']
57
58         if creatoropts['release'] is not None:
59             if 'name' not in recording_pkgs:
60                 recording_pkgs.append('name')
61
62         ksconf = misc.normalize_ksfile(ksconf,
63                                        creatoropts['release'],
64                                        creatoropts['arch'])
65         configmgr._ksconf = ksconf
66
67         # Called After setting the configmgr._ksconf
68         # as the creatoropts['name'] is reset there.
69         if creatoropts['release'] is not None:
70             creatoropts['outdir'] = "%s/%s/images/%s/" % (creatoropts['outdir'],
71                                                           creatoropts['release'],
72                                                           creatoropts['name'])
73
74         # try to find the pkgmgr
75         pkgmgr = None
76         for (key, pcls) in pluginmgr.get_plugins('backend').iteritems():
77             if 'auto' == creatoropts['pkgmgr']:
78                 pkgmgr = pcls
79                 break
80             elif key == creatoropts['pkgmgr']:
81                 pkgmgr = pcls
82                 break
83
84         if not pkgmgr:
85             pkgmgrs = pluginmgr.get_plugins('backend').keys()
86             raise errors.CreatorError("Can't find package manager: %s "
87                                       "(availables: %s)" \
88                                       % (creatoropts['pkgmgr'],
89                                          ', '.join(pkgmgrs)))
90
91         creator = LoopImageCreator(creatoropts,
92                                    pkgmgr,
93                                    opts.compress_image,
94                                    opts.shrink)
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 + ".img"],
102                                 creatoropts['release'])
103
104         try:
105             creator.check_depend_tools()
106             creator.mount(None, creatoropts["cachedir"])
107             creator.install()
108             creator.configure(creatoropts["repomd"])
109             creator.copy_kernel()
110             creator.unmount()
111             creator.package(creatoropts["outdir"])
112
113             if creatoropts['release'] is not None:
114                 creator.release_output(ksconf,
115                                        creatoropts['outdir'],
116                                        creatoropts['release'])
117             creator.print_outimage_info()
118
119         except errors.CreatorError:
120             raise
121         finally:
122             creator.cleanup()
123
124         msger.info("Finished.")
125         return 0
126
127     @classmethod
128     def _do_chroot_tar(cls, target):
129         mountfp_xml = os.path.splitext(target)[0] + '.xml'
130         if not os.path.exists(mountfp_xml):
131             raise errors.CreatorError("No mount point file found for this tar "
132                                       "image, please check %s" % mountfp_xml)
133
134         import tarfile
135         tar = tarfile.open(target, 'r')
136         tmpdir = misc.mkdtemp()
137         tar.extractall(path=tmpdir)
138         tar.close()
139
140         mntdir = misc.mkdtemp()
141
142         loops = []
143         for (mp, label, name, size, fstype) in load_mountpoints(mountfp_xml):
144             if fstype in ("ext2", "ext3", "ext4"):
145                 myDiskMount = fs_related.ExtDiskMount
146             elif fstype == "btrfs":
147                 myDiskMount = fs_related.BtrfsDiskMount
148             elif fstype in ("vfat", "msdos"):
149                 myDiskMount = fs_related.VfatDiskMount
150             else:
151                 msger.error("Cannot support fstype: %s" % fstype)
152
153             name = os.path.join(tmpdir, name)
154             size = size * 1024L * 1024L
155             loop = myDiskMount(fs_related.SparseLoopbackDisk(name, size),
156                                os.path.join(mntdir, mp.lstrip('/')),
157                                fstype, size, label)
158
159             try:
160                 msger.verbose("Mount %s to %s" % (mp, mntdir + mp))
161                 fs_related.makedirs(os.path.join(mntdir, mp.lstrip('/')))
162                 loop.mount()
163
164             except:
165                 loop.cleanup()
166                 for lp in reversed(loops):
167                     chroot.cleanup_after_chroot("img", lp, None, mntdir)
168
169                 shutil.rmtree(tmpdir, ignore_errors=True)
170                 raise
171
172             loops.append(loop)
173
174         try:
175             chroot.chroot(mntdir, None, "/usr/bin/env HOME=/root /bin/bash")
176         except:
177             raise errors.CreatorError("Failed to chroot to %s." % target)
178         finally:
179             for loop in reversed(loops):
180                 chroot.cleanup_after_chroot("img", loop, None, mntdir)
181
182             shutil.rmtree(tmpdir, ignore_errors=True)
183
184     @classmethod
185     def do_chroot(cls, target):
186         if target.endswith('.tar'):
187             import tarfile
188             if tarfile.is_tarfile(target):
189                 LoopPlugin._do_chroot_tar(target)
190                 return
191             else:
192                 raise errors.CreatorError("damaged tarball for loop images")
193
194         img = target
195         imgsize = misc.get_file_size(img) * 1024L * 1024L
196         imgtype = misc.get_image_type(img)
197         if imgtype == "btrfsimg":
198             fstype = "btrfs"
199             myDiskMount = fs_related.BtrfsDiskMount
200         elif imgtype in ("ext3fsimg", "ext4fsimg"):
201             fstype = imgtype[:4]
202             myDiskMount = fs_related.ExtDiskMount
203         else:
204             raise errors.CreatorError("Unsupported filesystem type: %s" \
205                                       % imgtype)
206
207         extmnt = misc.mkdtemp()
208         extloop = myDiskMount(fs_related.SparseLoopbackDisk(img, imgsize),
209                                                          extmnt,
210                                                          fstype,
211                                                          4096,
212                                                          "%s label" % fstype)
213         try:
214             extloop.mount()
215
216         except errors.MountError:
217             extloop.cleanup()
218             shutil.rmtree(extmnt, ignore_errors=True)
219             raise
220
221         try:
222             envcmd = fs_related.find_binary_inchroot("env", extmnt)
223             if envcmd:
224                 cmdline = "%s HOME=/root /bin/bash" % envcmd
225             else:
226                 cmdline = "/bin/bash"
227             chroot.chroot(extmnt, None, cmdline)
228         except:
229             raise errors.CreatorError("Failed to chroot to %s." % img)
230         finally:
231             chroot.cleanup_after_chroot("img", extloop, None, extmnt)
232
233     @classmethod
234     def do_unpack(cls, srcimg):
235         image = os.path.join(tempfile.mkdtemp(dir="/var/tmp", prefix="tmp"),
236                              "target.img")
237         msger.info("Copying file system ...")
238         shutil.copyfile(srcimg, image)
239         return image