Set ZYPP_LOCKFILE_ROOT env variable for multi-instance support
[tools/mic.git] / mic / creator.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, sys
19 from optparse import SUPPRESS_HELP
20
21 from mic import msger
22 from mic.utils import cmdln, errors, rpmmisc
23 from conf import configmgr
24 from plugin import pluginmgr
25
26 class Creator(cmdln.Cmdln):
27     """${name}: create an image
28
29     Usage:
30         ${name} SUBCOMMAND [OPTS] [ARGS..]
31
32     ${command_list}
33     ${option_list}
34     """
35
36     name = 'mic create(cr)'
37
38     def __init__(self, *args, **kwargs):
39         cmdln.Cmdln.__init__(self, *args, **kwargs)
40
41         # get cmds from pluginmgr
42         # mix-in do_subcmd interface
43         for subcmd, klass in pluginmgr.get_plugins('imager').iteritems():
44             if not hasattr(klass, 'do_create'):
45                 msger.warning("Unsurpport subcmd: %s" % subcmd)
46                 continue
47
48             func = getattr(klass, 'do_create')
49             setattr(self.__class__, "do_"+subcmd, func)
50
51     def get_optparser(self):
52         optparser = cmdln.CmdlnOptionParser(self)
53         optparser.add_option('-d', '--debug', action='store_true', dest='debug', help=SUPPRESS_HELP)
54         optparser.add_option('-v', '--verbose', action='store_true', dest='verbose', help=SUPPRESS_HELP)
55         optparser.add_option('', '--logfile', type='string', dest='logfile', default=None, help='Path of logfile')
56         optparser.add_option('-c', '--config', type='string', dest='config', default=None, help='Specify config file for mic')
57         optparser.add_option('-k', '--cachedir', type='string', action='store', dest='cachedir', default=None, help='Cache directory to store the downloaded')
58         optparser.add_option('-o', '--outdir', type='string', action='store', dest='outdir', default=None, help='Output directory')
59         optparser.add_option('-A', '--arch', type='string', dest='arch', default=None, help='Specify repo architecture')
60         optparser.add_option('', '--release', type='string', dest='release', default=None, metavar='RID', help='Generate a release of RID with all necessary files, when @BUILD_ID@ is contained in kickstart file, it will be replaced by RID')
61         optparser.add_option("", "--record-pkgs", type="string", dest="record_pkgs", default=None,
62                              help='Record the info of installed packages, multiple values can be specified which joined by ",", valid values: "name", "content", "license"')
63         optparser.add_option('', '--pkgmgr', type='string', dest='pkgmgr', default=None, help='Specify backend package manager')
64         optparser.add_option('', '--local-pkgs-path', type='string', dest='local_pkgs_path', default=None, help='Path for local pkgs(rpms) to be installed')
65         optparser.add_option('', '--compress-disk-image', type='string', dest='compress_disk_image', default=None, help='Sets the disk image compression. NOTE: The available values might depend on the used filesystem type.')
66         return optparser
67
68     def preoptparse(self, argv):
69         optparser = self.get_optparser()
70
71         largs = []
72         rargs = []
73         while argv:
74             arg = argv.pop(0)
75
76             if arg in ('-h', '--help'):
77                 rargs.append(arg)
78
79             elif optparser.has_option(arg):
80                 largs.append(arg)
81
82                 if optparser.get_option(arg).takes_value():
83                     try:
84                         largs.append(argv.pop(0))
85                     except IndexError:
86                         raise errors.Usage("%s option requires an argument" % arg)
87
88             else:
89                 if arg.startswith("--"):
90                     if "=" in arg:
91                         opt = arg.split("=")[0]
92                     else:
93                         opt = None
94                 elif arg.startswith("-") and len(arg) > 2:
95                     opt = arg[0:2]
96                 else:
97                     opt = None
98
99                 if opt and optparser.has_option(opt):
100                     largs.append(arg)
101                 else:
102                     rargs.append(arg)
103
104         return largs + rargs
105
106     def postoptparse(self):
107         if self.options.verbose:
108             msger.set_loglevel('verbose')
109         if self.options.debug:
110             msger.set_loglevel('debug')
111
112         if self.options.logfile:
113             msger.set_interactive(False)
114             msger.set_logfile(self.options.logfile)
115             configmgr.create['logfile'] = self.options.logfile
116
117         if self.options.config:
118             configmgr.reset()
119             configmgr._siteconf = self.options.config
120
121         if self.options.outdir is not None:
122             configmgr.create['outdir'] = self.options.outdir
123         if self.options.cachedir is not None:
124             configmgr.create['cachedir'] = self.options.cachedir
125         os.environ['ZYPP_LOCKFILE_ROOT'] = configmgr.create['cachedir']
126         if self.options.local_pkgs_path is not None:
127             configmgr.create['local_pkgs_path'] = self.options.local_pkgs_path
128
129         if self.options.release:
130             configmgr.create['release'] = self.options.release
131
132         if self.options.record_pkgs:
133             configmgr.create['record_pkgs'] = []
134             for infotype in self.options.record_pkgs.split(','):
135                 if infotype not in ('name', 'content', 'license'):
136                     raise errors.Usage('Invalid pkg recording: %s, valid ones: "name", "content", "license"' % infotype)
137
138                 configmgr.create['record_pkgs'].append(infotype)
139
140         if self.options.arch is not None:
141             supported_arch = sorted(rpmmisc.archPolicies.keys(), reverse=True)
142             if self.options.arch in supported_arch:
143                 configmgr.create['arch'] = self.options.arch
144             else:
145                 raise errors.Usage('Invalid architecture: "%s".\n'
146                                    '  Supported architectures are: \n'
147                                    '  %s\n' % (self.options.arch, ', '.join(supported_arch)))
148
149         if self.options.pkgmgr is not None:
150             configmgr.create['pkgmgr'] = self.options.pkgmgr
151
152         if self.options.compress_disk_image is not None:
153             configmgr.create['compress_disk_image'] = self.options.compress_disk_image
154
155     def main(self, argv=None):
156         if argv is None:
157             argv = sys.argv
158         else:
159             argv = argv[:] # don't modify caller's list
160
161         self.optparser = self.get_optparser()
162         if self.optparser:
163             try:
164                 argv = self.preoptparse(argv)
165                 self.options, args = self.optparser.parse_args(argv)
166
167             except cmdln.CmdlnUserError, ex:
168                 msg = "%s: %s\nTry '%s help' for info.\n"\
169                       % (self.name, ex, self.name)
170                 msger.error(msg)
171
172             except cmdln.StopOptionProcessing, ex:
173                 return 0
174         else:
175             # optparser=None means no process for opts
176             self.options, args = None, argv[1:]
177
178         self.postoptparse()
179
180         if not args:
181             return self.emptyline()
182
183         if os.geteuid() != 0:
184             msger.error('Root permission is required to continue, abort')
185
186         return self.cmd(args)
187