Merge "zyppbackend: remove select packages in group"
[tools/mic.git] / plugins / imager / loop_plugin.py
1 #!/usr/bin/python -tt
2 #
3 # Copyright 2011 Intel, Inc.
4 #
5 # This copyrighted material is made available to anyone wishing to use, modify,
6 # copy, or redistribute it subject to the terms and conditions of the GNU
7 # General Public License v.2.  This program is distributed in the hope that it
8 # will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
9 # implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 # See the GNU General Public License for more details.
11 #
12 # You should have received a copy of the GNU General Public License along with
13 # this program; if not, write to the Free Software Foundation, Inc., 51
14 # Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  Any Red Hat
15 # trademarks that are incorporated in the source code or documentation are not
16 # subject to the GNU General Public License and may only be used or replicated
17 # with the express permission of Red Hat, Inc.
18 #
19
20 import os
21 import shutil
22 import tempfile
23
24 from mic import configmgr, pluginmgr, chroot, msger
25 from mic.utils import misc, fs_related, errors, cmdln
26 import mic.imager.loop as loop
27
28 from mic.pluginbase import ImagerPlugin
29 class LoopPlugin(ImagerPlugin):
30     name = 'loop'
31
32     @classmethod
33     @cmdln.option('-E', '--extra-loop', dest='extra_loop',
34                   help='Extra loop image to be mounted, multiple <mountpoint>:name_of_loop_file pairs expected, and '
35                        'joined by using "," like the following sample:'
36                        '  --extr-loop=/opt:opt.img,/boot:boot.img'
37                        )
38     def do_create(self, subcmd, opts, *args):
39         """${cmd_name}: create loop image
40
41         ${cmd_usage}
42         ${cmd_option_list}
43         """
44
45         if not args:
46             raise errors.Usage("More arguments needed")
47
48         if len(args) != 1:
49             raise errors.Usage("Extra arguments given")
50
51         try:
52             if opts.extra_loop:
53                 extra_loop = dict([[i.strip() for i in one.split(':')] for one in opts.extra_loop.split(',')])
54             else:
55                 extra_loop = {}
56         except ValueError:
57             raise errors.Usage("invalid --extra-loop option specified")
58
59         cfgmgr = configmgr.getConfigMgr()
60         creatoropts = cfgmgr.create
61         cfgmgr._ksconf = args[0]
62
63         # try to find the pkgmgr
64         pkgmgr = None
65         for (key, pcls) in pluginmgr.PluginMgr().get_plugins('backend').iteritems():
66             if key == creatoropts['pkgmgr']:
67                 pkgmgr = pcls
68                 break
69
70         if not pkgmgr:
71             raise errors.CreatorError("Can't find package manager: %s" % creatoropts['pkgmgr'])
72
73         creator = loop.LoopImageCreator(creatoropts, pkgmgr, extra_loop)
74         try:
75             creator.check_depend_tools()
76             creator.mount(None, creatoropts["cachedir"])
77             creator.install()
78             creator.configure(creatoropts["repomd"])
79             creator.unmount()
80             creator.package(creatoropts["outdir"])
81             creator.print_outimage_info()
82
83         except errors.CreatorError:
84             raise
85         finally:
86             creator.cleanup()
87
88         msger.info("Finished.")
89         return 0
90
91     @classmethod
92     def do_chroot(cls, target):#chroot.py parse opts&args
93         img = target
94         imgsize = misc.get_file_size(img)
95         extmnt = misc.mkdtemp()
96         extloop = fs_related.ExtDiskMount(fs_related.SparseLoopbackDisk(img, imgsize),
97                                                          extmnt,
98                                                          "ext3",
99                                                          4096,
100                                                          "ext3 label")
101         try:
102             extloop.mount()
103
104         except errors.MountError:
105             extloop.cleanup()
106             shutil.rmtree(extmnt, ignore_errors = True)
107             raise
108
109         try:
110             chroot.chroot(extmnt, None,  "/bin/env HOME=/root /bin/bash")
111         except:
112             raise errors.CreatorError("Failed to chroot to %s." %img)
113         finally:
114             chroot.cleanup_after_chroot("img", extloop, None, extmnt)
115
116     @classmethod
117     def do_unpack(cls, srcimg):
118         image = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), "target.img")
119         msger.info("Copying file system ...")
120         shutil.copyfile(srcimg, image)
121         return image