rewrite msger module based on logging
[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, re
19 import pwd
20 from optparse import SUPPRESS_HELP
21
22 from mic import msger, rt_util
23 from mic.utils import cmdln, errors, rpmmisc
24 from mic.conf import configmgr
25 from mic.plugin import pluginmgr
26
27
28 class Creator(cmdln.Cmdln):
29     """${name}: create an image
30
31     Usage:
32         ${name} SUBCOMMAND <ksfile> [OPTS]
33
34     ${command_list}
35     ${option_list}
36     """
37
38     name = 'mic create(cr)'
39
40     def __init__(self, *args, **kwargs):
41         cmdln.Cmdln.__init__(self, *args, **kwargs)
42         self._subcmds = []
43
44         # get cmds from pluginmgr
45         # mix-in do_subcmd interface
46         for subcmd, klass in pluginmgr.get_plugins('imager').iteritems():
47             if not hasattr(klass, 'do_create'):
48                 msger.warning("Unsurpport subcmd: %s" % subcmd)
49                 continue
50
51             func = getattr(klass, 'do_create')
52             setattr(self.__class__, "do_"+subcmd, func)
53             self._subcmds.append(subcmd)
54
55     def get_optparser(self):
56         optparser = cmdln.CmdlnOptionParser(self)
57         optparser.add_option('-d', '--debug', action='store_true',
58                              dest='debug',
59                              help=SUPPRESS_HELP)
60         optparser.add_option('-v', '--verbose', action='store_true',
61                              dest='verbose',
62                              help=SUPPRESS_HELP)
63         optparser.add_option('', '--logfile', type='string', dest='logfile',
64                              default=None,
65                              help='Path of logfile')
66         optparser.add_option('-c', '--config', type='string', dest='config',
67                              default=None,
68                              help='Specify config file for mic')
69         optparser.add_option('-k', '--cachedir', type='string', action='store',
70                              dest='cachedir', default=None,
71                              help='Cache directory to store the downloaded')
72         optparser.add_option('-o', '--outdir', type='string', action='store',
73                              dest='outdir', default=None,
74                              help='Output directory')
75         optparser.add_option('-A', '--arch', type='string', dest='arch',
76                              default=None,
77                              help='Specify repo architecture')
78         optparser.add_option('', '--release', type='string', dest='release',
79                              default=None, metavar='RID',
80                              help='Generate a release of RID with all necessary'
81                                   ' files, when @BUILD_ID@ is contained in '
82                                   'kickstart file, it will be replaced by RID')
83         optparser.add_option("", "--record-pkgs", type="string",
84                              dest="record_pkgs", default=None,
85                              help='Record the info of installed packages, '
86                                   'multiple values can be specified which '
87                                   'joined by ",", valid values: "name", '
88                                   '"content", "license", "vcs"')
89         optparser.add_option('', '--pkgmgr', type='string', dest='pkgmgr',
90                              default=None,
91                              help='Specify backend package manager')
92         optparser.add_option('', '--local-pkgs-path', type='string',
93                              dest='local_pkgs_path', default=None,
94                              help='Path for local pkgs(rpms) to be installed')
95         optparser.add_option('', '--runtime', type='string',
96                              dest='runtime', default=None,
97                              help='Specify  runtime mode, avaiable: bootstrap, native')
98         # --taring-to is alias to --pack-to
99         optparser.add_option('', '--taring-to', type='string',
100                              dest='pack_to', default=None,
101                              help=SUPPRESS_HELP)
102         optparser.add_option('', '--pack-to', type='string',
103                              dest='pack_to', default=None,
104                              help='Pack the images together into the specified'
105                                   ' achive, extension supported: .zip, .tar, '
106                                   '.tar.gz, .tar.bz2, etc. by default, .tar '
107                                   'will be used')
108         optparser.add_option('', '--copy-kernel', action='store_true',
109                              dest='copy_kernel',
110                              help='Copy kernel files from image /boot directory'
111                                   ' to the image output directory.')
112         optparser.add_option('', '--install-pkgs', type='string', action='store',
113                              dest='install_pkgs', default=None,
114                              help='Specify what type of packages to be installed,'
115                                   ' valid: source, debuginfo, debugsource')
116         optparser.add_option('', '--check-pkgs', type='string', action='store',
117                              dest='check_pkgs', default=[],
118                              help='Check if given packages would be installed, '
119                                   'packages should be separated by comma')
120         optparser.add_option('', '--tmpfs', action='store_true', dest='enabletmpfs',
121                              help='Setup tmpdir as tmpfs to accelerate, experimental'
122                                   ' feature, use it if you have more than 4G memory')
123         optparser.add_option('', '--repourl', action='append',
124                              dest='repourl', default=[],
125                              help=SUPPRESS_HELP)
126         return optparser
127
128     def preoptparse(self, argv):
129         optparser = self.get_optparser()
130
131         largs = []
132         rargs = []
133         while argv:
134             arg = argv.pop(0)
135
136             if arg in ('-h', '--help'):
137                 rargs.append(arg)
138
139             elif optparser.has_option(arg):
140                 largs.append(arg)
141
142                 if optparser.get_option(arg).takes_value():
143                     try:
144                         largs.append(argv.pop(0))
145                     except IndexError:
146                         raise errors.Usage("option %s requires arguments" % arg)
147
148             else:
149                 if arg.startswith("--"):
150                     if "=" in arg:
151                         opt = arg.split("=")[0]
152                     else:
153                         opt = None
154                 elif arg.startswith("-") and len(arg) > 2:
155                     opt = arg[0:2]
156                 else:
157                     opt = None
158
159                 if opt and optparser.has_option(opt):
160                     largs.append(arg)
161                 else:
162                     rargs.append(arg)
163
164         return largs + rargs
165
166     def postoptparse(self):
167         abspath = lambda pth: os.path.abspath(os.path.expanduser(pth))
168
169         if self.options.verbose:
170             msger.set_loglevel('VERBOSE')
171         if self.options.debug:
172             msger.set_loglevel('DEBUG')
173
174         if self.options.logfile:
175             logfile_abs_path = abspath(self.options.logfile)
176             if os.path.isdir(logfile_abs_path):
177                 raise errors.Usage("logfile's path %s should be file"
178                                    % self.options.logfile)
179             if not os.path.exists(os.path.dirname(logfile_abs_path)):
180                 os.makedirs(os.path.dirname(logfile_abs_path))
181             msger.set_interactive(False)
182             msger.set_logfile(logfile_abs_path)
183             configmgr.create['logfile'] = self.options.logfile
184
185         if self.options.config:
186             configmgr.reset()
187             configmgr._siteconf = self.options.config
188
189         if self.options.outdir is not None:
190             configmgr.create['outdir'] = abspath(self.options.outdir)
191         if self.options.cachedir is not None:
192             configmgr.create['cachedir'] = abspath(self.options.cachedir)
193         os.environ['ZYPP_LOCKFILE_ROOT'] = configmgr.create['cachedir']
194
195         for cdir in ('outdir', 'cachedir'):
196             if os.path.exists(configmgr.create[cdir]) \
197               and not os.path.isdir(configmgr.create[cdir]):
198                 msger.error('Invalid directory specified: %s' \
199                             % configmgr.create[cdir])
200
201         if self.options.local_pkgs_path is not None:
202             if not os.path.exists(self.options.local_pkgs_path):
203                 msger.error('Local pkgs directory: \'%s\' not exist' \
204                               % self.options.local_pkgs_path)
205             configmgr.create['local_pkgs_path'] = self.options.local_pkgs_path
206
207         if self.options.release:
208             configmgr.create['release'] = self.options.release.rstrip('/')
209
210         if self.options.record_pkgs:
211             configmgr.create['record_pkgs'] = []
212             for infotype in self.options.record_pkgs.split(','):
213                 if infotype not in ('name', 'content', 'license', 'vcs'):
214                     raise errors.Usage('Invalid pkg recording: %s, valid ones:'
215                                        ' "name", "content", "license", "vcs"' \
216                                        % infotype)
217
218                 configmgr.create['record_pkgs'].append(infotype)
219
220         if self.options.arch is not None:
221             supported_arch = sorted(rpmmisc.archPolicies.keys(), reverse=True)
222             if self.options.arch in supported_arch:
223                 configmgr.create['arch'] = self.options.arch
224             else:
225                 raise errors.Usage('Invalid architecture: "%s".\n'
226                                    '  Supported architectures are: \n'
227                                    '  %s' % (self.options.arch,
228                                                ', '.join(supported_arch)))
229
230         if self.options.pkgmgr is not None:
231             configmgr.create['pkgmgr'] = self.options.pkgmgr
232
233         if self.options.runtime:
234             configmgr.set_runtime(self.options.runtime)
235
236         if self.options.pack_to is not None:
237             configmgr.create['pack_to'] = self.options.pack_to
238
239         if self.options.copy_kernel:
240             configmgr.create['copy_kernel'] = self.options.copy_kernel
241
242         if self.options.install_pkgs:
243             configmgr.create['install_pkgs'] = []
244             for pkgtype in self.options.install_pkgs.split(','):
245                 if pkgtype not in ('source', 'debuginfo', 'debugsource'):
246                     raise errors.Usage('Invalid parameter specified: "%s", '
247                                        'valid values: source, debuginfo, '
248                                        'debusource' % pkgtype)
249
250                 configmgr.create['install_pkgs'].append(pkgtype)
251
252         if self.options.check_pkgs:
253             for pkg in self.options.check_pkgs.split(','):
254                 configmgr.create['check_pkgs'].append(pkg)
255
256         if self.options.enabletmpfs:
257             configmgr.create['enabletmpfs'] = self.options.enabletmpfs
258
259         if self.options.repourl:
260             for item in self.options.repourl:
261                 try:
262                     key, val = item.split('=')
263                 except:
264                     continue
265                 configmgr.create['repourl'][key] = val
266
267     def main(self, argv=None):
268         if argv is None:
269             argv = sys.argv
270         else:
271             argv = argv[:] # don't modify caller's list
272
273         self.optparser = self.get_optparser()
274         if self.optparser:
275             try:
276                 argv = self.preoptparse(argv)
277                 self.options, args = self.optparser.parse_args(argv)
278
279             except cmdln.CmdlnUserError, ex:
280                 msg = "%s: %s\nTry '%s help' for info.\n"\
281                       % (self.name, ex, self.name)
282                 msger.error(msg)
283
284             except cmdln.StopOptionProcessing, ex:
285                 return 0
286         else:
287             # optparser=None means no process for opts
288             self.options, args = None, argv[1:]
289
290         if not args:
291             return self.emptyline()
292
293         self.postoptparse()
294
295         return self.cmd(args)
296
297     def precmd(self, argv): # check help before cmd
298
299         if '-h' in argv or '?' in argv or '--help' in argv or 'help' in argv:
300             return argv
301
302         if len(argv) == 1:
303             return ['help', argv[0]]
304
305         if os.geteuid() != 0:
306             msger.error("Root permission is required, abort")
307
308         try:
309             w = pwd.getpwuid(os.geteuid())
310         except KeyError:
311             msger.warning("Might fail in compressing stage for undetermined user")
312
313         return argv
314
315     def do_auto(self, subcmd, opts, *args):
316         """${cmd_name}: auto detect image type from magic header
317
318         Usage:
319             ${name} ${cmd_name} <ksfile>
320
321         ${cmd_option_list}
322         """
323         def parse_magic_line(re_str, pstr, ptype='mic'):
324             ptn = re.compile(re_str)
325             m = ptn.match(pstr)
326             if not m or not m.groups():
327                 return None
328
329             inline_argv = m.group(1).strip()
330             if ptype == 'mic':
331                 m2 = re.search('(?P<format>\w+)', inline_argv)
332             elif ptype == 'mic2':
333                 m2 = re.search('(-f|--format(=)?)\s*(?P<format>\w+)',
334                                inline_argv)
335             else:
336                 return None
337
338             if m2:
339                 cmdname = m2.group('format')
340                 inline_argv = inline_argv.replace(m2.group(0), '')
341                 return (cmdname, inline_argv)
342
343             return None
344
345         if len(args) != 1:
346             raise errors.Usage("Extra arguments given")
347
348         if not os.path.exists(args[0]):
349             raise errors.CreatorError("Can't find the file: %s" % args[0])
350
351         with open(args[0], 'r') as rf:
352             first_line = rf.readline()
353
354         mic_re = '^#\s*-\*-mic-options-\*-\s+(.*)\s+-\*-mic-options-\*-'
355         mic2_re = '^#\s*-\*-mic2-options-\*-\s+(.*)\s+-\*-mic2-options-\*-'
356
357         result = parse_magic_line(mic_re, first_line, 'mic') \
358                  or parse_magic_line(mic2_re, first_line, 'mic2')
359         if not result:
360             raise errors.KsError("Invalid magic line in file: %s" % args[0])
361
362         if result[0] not in self._subcmds:
363             raise errors.KsError("Unsupport format '%s' in %s"
364                                  % (result[0], args[0]))
365
366         argv = ' '.join(result + args).split()
367         self.main(argv)
368