call copy_attachment() after configure() and move attachment files
[tools/mic.git] / plugins / imager / qcow_plugin.py
1 #
2 # Copyright (c) 2014 Intel, Inc.
3 #
4 # This program is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU General Public License as published by the Free
6 # Software Foundation; version 2 of the License
7 #
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11 # for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc., 59
15 # Temple Place - Suite 330, Boston, MA 02111-1307, USA.
16
17 import os
18 import subprocess
19 import shutil
20
21 from mic import msger, rt_util
22 from mic.conf import configmgr
23 from mic.plugin import pluginmgr
24 from mic.pluginbase import ImagerPlugin
25 from mic.imager.loop import LoopImageCreator
26 from mic.utils import errors, fs_related, runner
27
28 class QcowImageCreator(LoopImageCreator):
29     img_format = 'qcow'
30
31     def __init__(self, creatoropts=None, pkgmgr=None):
32         LoopImageCreator.__init__(self, creatoropts, pkgmgr) 
33         self.cmd_qemuimg = 'qemu-img'
34
35     def _stage_final_image(self):
36         try:
37             self.cmd_qemuimg = fs_related.find_binary_path('qemu-img')
38         except errors.CreatorError:
39             return LoopImageCreator._stage_final_image(self)
40
41         self._resparse()
42
43         imgfile = None
44         for item in self._instloops:
45             if item['mountpoint'] == '/':
46                 if item['fstype'] == "ext4":
47                     runner.show('/sbin/tune2fs -O ^huge_file,extents,uninit_bg %s'
48                                 % imgfile)
49                 self.image_files.setdefault('partitions', {}).update(
50                          {item['mountpoint']: item['label']})
51                 imgfile = os.path.join(self._imgdir, item['name'])
52
53         if imgfile:
54             qemuimage = imgfile + ".x86"
55             runner.show("%s convert -O qcow2 %s %s"
56                         % (self.cmd_qemuimg, imgfile, qemuimage))
57             os.unlink(imgfile)
58             os.rename(qemuimage, imgfile)
59
60         for item in os.listdir(self._imgdir):
61             shutil.move(os.path.join(self._imgdir, item),
62                         os.path.join(self._outdir, item))
63
64 class QcowPlugin(ImagerPlugin):
65     name = 'qcow'
66
67     @classmethod
68     def do_create(cls, args):
69         """${cmd_name}: create qcow image
70
71         Usage:
72             ${name} ${cmd_name} <ksfile> [OPTS]
73
74         ${cmd_option_list}
75         """
76         if args is None:
77             raise errors.Usage("Invalid arguments")
78
79         creatoropts = configmgr.create
80         ksconf = args.ksfile
81
82         if creatoropts['runtime'] == "bootstrap":
83             configmgr._ksconf = ksconf
84             rt_util.bootstrap_mic()
85
86         recording_pkgs = []
87         if len(creatoropts['record_pkgs']) > 0:
88             recording_pkgs = creatoropts['record_pkgs']
89
90         if creatoropts['release'] is not None:
91             if 'name' not in recording_pkgs:
92                 recording_pkgs.append('name')
93             if 'vcs' not in recording_pkgs:
94                 recording_pkgs.append('vcs')
95
96         configmgr._ksconf = ksconf
97
98         # try to find the pkgmgr
99         pkgmgr = None
100         backends = pluginmgr.get_plugins('backend')
101         if 'auto' == creatoropts['pkgmgr']:
102             for key in configmgr.prefer_backends:
103                 if key in backends:
104                     pkgmgr = backends[key]
105                     break
106         else:
107             for key in backends.keys():
108                 if key == creatoropts['pkgmgr']:
109                     pkgmgr = backends[key]
110                     break
111
112         if not pkgmgr:
113             raise errors.CreatorError("Can't find backend: %s, "
114                                        "available choices: %s" %
115                                       (creatoropts['pkgmgr'],
116                                        ','.join(backends.keys())))
117
118         creator = QcowImageCreator(creatoropts,
119                                    pkgmgr)
120
121         if len(recording_pkgs) > 0:
122             creator._recording_pkgs = recording_pkgs
123
124         image_names = [creator.name + ".img"]
125         image_names.extend(creator.get_image_names())
126         cls.check_image_exists(creator.destdir,
127                                 creator.pack_to,
128                                 image_names,
129                                 creatoropts['release'])
130
131         try:
132             creator.check_depend_tools()
133             creator.mount(None, creatoropts["cachedir"])
134             creator.install()
135             creator.configure(creatoropts["repomd"])
136             creator.copy_kernel()
137             creator.copy_attachment()
138             creator.create_cpio_image()
139             creator.unmount()
140             creator.copy_cpio_image()
141             creator.package(creatoropts["destdir"])
142             creator.create_manifest()
143
144             if creatoropts['release'] is not None:
145                 creator.release_output(ksconf,
146                                        creatoropts['destdir'],
147                                        creatoropts['release'])
148             creator.print_outimage_info()
149
150         except errors.CreatorError:
151             raise
152         finally:
153             creator.cleanup()
154
155         #Run script of --run_script after image created
156         if creatoropts['run_script']:
157             cmd = creatoropts['run_script']
158             try:
159                 runner.show(cmd)
160             except OSError,err:
161                 msger.warning(str(err))
162
163
164         msger.info("Finished.")
165         return 0
166
167     @classmethod
168     def do_chroot(cls, target, cmd=[]):
169         pass
170
171     @classmethod
172     def do_unpack(cls, srcimg):
173         pass