Add new option of --run_script
[tools/mic.git] / plugins / imager / fs_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 subprocess
19 from mic import chroot, msger, rt_util
20 from mic.utils import misc, errors, fs_related
21 from mic.imager import fs
22 from mic.conf import configmgr
23 from mic.plugin import pluginmgr
24
25 from mic.pluginbase import ImagerPlugin
26 class FsPlugin(ImagerPlugin):
27     name = 'fs'
28
29     @classmethod
30     def do_create(self, args):
31         """${cmd_name}: create fs image
32
33         Usage:
34             ${name} ${cmd_name} <ksfile> [OPTS]
35
36         ${cmd_option_list}
37         """
38
39         if args is None:
40             raise errors.Usage("Invalid arguments.")
41
42         creatoropts = configmgr.create
43         ksconf = args.ksfile
44
45         if creatoropts['runtime'] == 'bootstrap':
46             configmgr._ksconf = ksconf
47             rt_util.bootstrap_mic()
48
49         recording_pkgs = []
50         if len(creatoropts['record_pkgs']) > 0:
51             recording_pkgs = creatoropts['record_pkgs']
52
53         if creatoropts['release'] is not None:
54             if 'name' not in recording_pkgs:
55                 recording_pkgs.append('name')
56             if 'vcs' not in recording_pkgs:
57                 recording_pkgs.append('vcs')
58
59         configmgr._ksconf = ksconf
60
61         # try to find the pkgmgr
62         pkgmgr = None
63         backends = pluginmgr.get_plugins('backend')
64         if 'auto' == creatoropts['pkgmgr']:
65             for key in configmgr.prefer_backends:
66                 if key in backends:
67                     pkgmgr = backends[key]
68                     break
69         else:
70             for key in backends.keys():
71                 if key == creatoropts['pkgmgr']:
72                     pkgmgr = backends[key]
73                     break
74
75         if not pkgmgr:
76             raise errors.CreatorError("Can't find backend: %s, "
77                                       "available choices: %s" %
78                                       (creatoropts['pkgmgr'],
79                                        ','.join(backends.keys())))
80
81         creator = fs.FsImageCreator(creatoropts, pkgmgr)
82         creator._include_src = args.include_src
83
84         if len(recording_pkgs) > 0:
85             creator._recording_pkgs = recording_pkgs
86
87         self.check_image_exists(creator.destdir,
88                                 creator.pack_to,
89                                 [creator.name],
90                                 creatoropts['release'])
91
92         try:
93             creator.check_depend_tools()
94             creator.mount(None, creatoropts["cachedir"])
95             creator.install()
96             #Download the source packages ###private options
97             if args.include_src:
98                 installed_pkgs =  creator.get_installed_packages()
99                 msger.info('Generating the image with source rpms included ...')
100                 if not misc.SrcpkgsDownload(installed_pkgs, creatoropts["repomd"],
101                         creator._instroot, creatoropts["cachedir"]):
102                     msger.warning("Source packages can't be downloaded")
103
104             creator.configure(creatoropts["repomd"])
105             creator.copy_kernel()
106             creator.unmount()
107             creator.package(creatoropts["destdir"])
108             creator.create_manifest()
109             if creatoropts['release'] is not None:
110                 creator.release_output(ksconf, creatoropts['destdir'],
111                         creatoropts['release'])
112             creator.print_outimage_info()
113         except errors.CreatorError:
114             raise
115         finally:
116             creator.cleanup()
117
118         #Run script of --run_script after image created
119         if creatoropts['run_script']:
120             cmd = creatoropts['run_script']
121             msger.info("Running command in parameter run_script: "+"".join(cmd))
122             try:
123                 p = subprocess.Popen(cmd, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
124                 p.communicate()
125             except OSError,err:
126                 msger.warning(str(err))
127
128
129         msger.info("Finished.")
130         return 0
131
132     @classmethod
133     def do_chroot(self, target, cmd=[]):#chroot.py parse opts&args
134         try:
135             if len(cmd) != 0:
136                 cmdline = ' '.join(cmd)
137             else:
138                 cmdline = "/bin/bash"
139             envcmd = fs_related.find_binary_inchroot("env", target)
140             if envcmd:
141                 cmdline = "%s HOME=/root %s" % (envcmd, cmdline)
142             chroot.chroot(target, None, cmdline)
143         finally:
144             chroot.cleanup_after_chroot("dir", None, None, None)
145             return 1