Give prompt info if target image file exist.
[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 configmgr, pluginmgr, chroot, msger
23 from mic.utils import misc, fs_related, errors, cmdln
24 import mic.imager.loop as loop
25
26 from mic.pluginbase import ImagerPlugin
27 class LoopPlugin(ImagerPlugin):
28     name = 'loop'
29
30     @classmethod
31     @cmdln.option("--taring-to", dest="taring_to", type='string', default=None, help="Specify the filename for packaging all loop images into a single tarball")
32     def do_create(self, subcmd, opts, *args):
33         """${cmd_name}: create loop image
34
35         ${cmd_usage}
36         ${cmd_option_list}
37         """
38
39         if not args:
40             raise errors.Usage("More arguments needed")
41
42         if len(args) != 1:
43             raise errors.Usage("Extra arguments given")
44
45         cfgmgr = configmgr.getConfigMgr()
46         creatoropts = cfgmgr.create
47         ksconf = args[0]
48
49         if not os.path.exists(ksconf):
50             raise errors.CreatorError("Can't find the file: %s" % ksconf)
51
52         recording_pkgs = []
53         if len(creatoropts['record_pkgs']) > 0:
54             recording_pkgs = creatoropts['record_pkgs']
55         if creatoropts['release'] is not None:
56             if 'name' not in recording_pkgs:
57                 recording_pkgs.append('name')
58             ksconf = misc.save_ksconf_file(ksconf, creatoropts['release'])
59             name = os.path.splitext(os.path.basename(ksconf))[0]
60             creatoropts['outdir'] = "%s/%s/images/%s/" % (creatoropts['outdir'], creatoropts['release'], name)
61         cfgmgr._ksconf = ksconf
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             pkgmgrs = pluginmgr.PluginMgr().get_plugins('backend').keys()
72             raise errors.CreatorError("Can't find package manager: %s (availables: %s)" % (creatoropts['pkgmgr'], ', '.join(pkgmgrs)))
73
74         creator = loop.LoopImageCreator(creatoropts, pkgmgr, opts.taring_to)
75
76         if len(recording_pkgs) > 0:
77             creator._recording_pkgs = recording_pkgs
78
79         destdir = os.path.abspath(os.path.expanduser(creatoropts["outdir"]))
80         imagefile = "%s.img" % os.path.join(destdir, creator.name)
81
82         if not os.path.exists(destdir):
83             os.makedirs(destdir)
84         elif os.path.exists(imagefile):
85             if msger.ask('The target image: %s already exists, need to delete it?' % imagefile):
86                 os.unlink(imagefile)
87
88         try:
89             creator.check_depend_tools()
90             creator.mount(None, creatoropts["cachedir"])
91             creator.install()
92             creator.configure(creatoropts["repomd"])
93             creator.unmount()
94             creator.package(creatoropts["outdir"])
95
96             if creatoropts['release'] is not None:
97                 creator.release_output(ksconf, creatoropts['outdir'], creatoropts['release'])
98             creator.print_outimage_info()
99
100         except errors.CreatorError:
101             raise
102         finally:
103             creator.cleanup()
104
105         msger.info("Finished.")
106         return 0
107
108     @classmethod
109     def do_chroot(cls, target):#chroot.py parse opts&args
110         img = target
111         imgsize = misc.get_file_size(img)
112         extmnt = misc.mkdtemp()
113         extloop = fs_related.ExtDiskMount(fs_related.SparseLoopbackDisk(img, imgsize),
114                                                          extmnt,
115                                                          "ext3",
116                                                          4096,
117                                                          "ext3 label")
118         try:
119             extloop.mount()
120
121         except errors.MountError:
122             extloop.cleanup()
123             shutil.rmtree(extmnt, ignore_errors = True)
124             raise
125
126         try:
127             chroot.chroot(extmnt, None,  "/bin/env HOME=/root /bin/bash")
128         except:
129             raise errors.CreatorError("Failed to chroot to %s." %img)
130         finally:
131             chroot.cleanup_after_chroot("img", extloop, None, extmnt)
132
133     @classmethod
134     def do_unpack(cls, srcimg):
135         image = os.path.join(tempfile.mkdtemp(dir = "/var/tmp", prefix = "tmp"), "target.img")
136         msger.info("Copying file system ...")
137         shutil.copyfile(srcimg, image)
138         return image