put logfile setting up prior to other error output
[platform/upstream/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
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         optparser.add_option('-R', '--repo', action='append',
127                              dest='repo', default=[],
128                              help=SUPPRESS_HELP)
129         optparser.add_option('', '--ignore-ksrepo', action='store_true',
130                              dest='ignore_ksrepo', default=False,
131                              help=SUPPRESS_HELP)
132         return optparser
133
134     def preoptparse(self, argv):
135         optparser = self.get_optparser()
136
137         largs = []
138         rargs = []
139         while argv:
140             arg = argv.pop(0)
141
142             if arg in ('-h', '--help'):
143                 rargs.append(arg)
144
145             elif optparser.has_option(arg):
146                 largs.append(arg)
147
148                 if optparser.get_option(arg).takes_value():
149                     try:
150                         largs.append(argv.pop(0))
151                     except IndexError:
152                         raise errors.Usage("option %s requires arguments" % arg)
153
154             else:
155                 if arg.startswith("--"):
156                     if "=" in arg:
157                         opt = arg.split("=")[0]
158                     else:
159                         opt = None
160                 elif arg.startswith("-") and len(arg) > 2:
161                     opt = arg[0:2]
162                 else:
163                     opt = None
164
165                 if opt and optparser.has_option(opt):
166                     largs.append(arg)
167                 else:
168                     rargs.append(arg)
169
170         return largs + rargs
171
172     def postoptparse(self):
173         abspath = lambda pth: os.path.abspath(os.path.expanduser(pth))
174
175         if self.options.verbose:
176             msger.set_loglevel('VERBOSE')
177         if self.options.debug:
178             msger.set_loglevel('DEBUG')
179
180         if self.options.logfile:
181             logfile_abs_path = abspath(self.options.logfile)
182             if os.path.isdir(logfile_abs_path):
183                 raise errors.Usage("logfile's path %s should be file"
184                                    % self.options.logfile)
185             configmgr.create['logfile'] = logfile_abs_path
186             configmgr.set_logfile()
187
188         if self.options.config:
189             configmgr.reset()
190             configmgr._siteconf = self.options.config
191
192         if self.options.outdir is not None:
193             configmgr.create['outdir'] = abspath(self.options.outdir)
194         if self.options.cachedir is not None:
195             configmgr.create['cachedir'] = abspath(self.options.cachedir)
196         os.environ['ZYPP_LOCKFILE_ROOT'] = configmgr.create['cachedir']
197
198         for cdir in ('outdir', 'cachedir'):
199             if os.path.exists(configmgr.create[cdir]) \
200               and not os.path.isdir(configmgr.create[cdir]):
201                 raise errors.Usage('Invalid directory specified: %s' \
202                                    % configmgr.create[cdir])
203             if not os.path.exists(configmgr.create[cdir]):
204                 os.makedirs(configmgr.create[cdir])
205                 if os.getenv('SUDO_UID', '') and os.getenv('SUDO_GID', ''):
206                     os.chown(configmgr.create[cdir],
207                              int(os.getenv('SUDO_UID')),
208                              int(os.getenv('SUDO_GID')))
209
210         if self.options.local_pkgs_path is not None:
211             if not os.path.exists(self.options.local_pkgs_path):
212                 raise errors.Usage('Local pkgs directory: \'%s\' not exist' \
213                               % self.options.local_pkgs_path)
214             configmgr.create['local_pkgs_path'] = self.options.local_pkgs_path
215
216         if self.options.release:
217             configmgr.create['release'] = self.options.release.rstrip('/')
218
219         if self.options.record_pkgs:
220             configmgr.create['record_pkgs'] = []
221             for infotype in self.options.record_pkgs.split(','):
222                 if infotype not in ('name', 'content', 'license', 'vcs'):
223                     raise errors.Usage('Invalid pkg recording: %s, valid ones:'
224                                        ' "name", "content", "license", "vcs"' \
225                                        % infotype)
226
227                 configmgr.create['record_pkgs'].append(infotype)
228
229         if self.options.arch is not None:
230             supported_arch = sorted(rpmmisc.archPolicies.keys(), reverse=True)
231             if self.options.arch in supported_arch:
232                 configmgr.create['arch'] = self.options.arch
233             else:
234                 raise errors.Usage('Invalid architecture: "%s".\n'
235                                    '  Supported architectures are: \n'
236                                    '  %s' % (self.options.arch,
237                                                ', '.join(supported_arch)))
238
239         if self.options.pkgmgr is not None:
240             configmgr.create['pkgmgr'] = self.options.pkgmgr
241
242         if self.options.runtime:
243             configmgr.set_runtime(self.options.runtime)
244
245         if self.options.pack_to is not None:
246             configmgr.create['pack_to'] = self.options.pack_to
247
248         if self.options.copy_kernel:
249             configmgr.create['copy_kernel'] = self.options.copy_kernel
250
251         if self.options.install_pkgs:
252             configmgr.create['install_pkgs'] = []
253             for pkgtype in self.options.install_pkgs.split(','):
254                 if pkgtype not in ('source', 'debuginfo', 'debugsource'):
255                     raise errors.Usage('Invalid parameter specified: "%s", '
256                                        'valid values: source, debuginfo, '
257                                        'debusource' % pkgtype)
258
259                 configmgr.create['install_pkgs'].append(pkgtype)
260
261         if self.options.check_pkgs:
262             for pkg in self.options.check_pkgs.split(','):
263                 configmgr.create['check_pkgs'].append(pkg)
264
265         if self.options.enabletmpfs:
266             configmgr.create['enabletmpfs'] = self.options.enabletmpfs
267
268         if self.options.repourl:
269             for item in self.options.repourl:
270                 try:
271                     key, val = item.split('=')
272                 except:
273                     continue
274                 configmgr.create['repourl'][key] = val
275
276         if self.options.repo:
277             for optvalue in self.options.repo:
278                 repo = {}
279                 for item in optvalue.split(';'):
280                     try:
281                         key, val = item.split('=')
282                     except:
283                         continue
284                     repo[key.strip()] = val.strip()
285                 if 'name' in repo:
286                     configmgr.create['extrarepos'][repo['name']] = repo
287
288         if self.options.ignore_ksrepo:
289             configmgr.create['ignore_ksrepo'] = self.options.ignore_ksrepo
290
291     def main(self, argv=None):
292         if argv is None:
293             argv = sys.argv
294         else:
295             argv = argv[:] # don't modify caller's list
296
297         self.optparser = self.get_optparser()
298         if self.optparser:
299             try:
300                 argv = self.preoptparse(argv)
301                 self.options, args = self.optparser.parse_args(argv)
302
303             except cmdln.CmdlnUserError, ex:
304                 msg = "%s: %s\nTry '%s help' for info.\n"\
305                       % (self.name, ex, self.name)
306                 raise errors.Usage(msg)
307
308             except cmdln.StopOptionProcessing, ex:
309                 return 0
310         else:
311             # optparser=None means no process for opts
312             self.options, args = None, argv[1:]
313
314         if not args:
315             return self.emptyline()
316
317         self.postoptparse()
318
319         return self.cmd(args)
320
321     def precmd(self, argv): # check help before cmd
322
323         if '-h' in argv or '?' in argv or '--help' in argv or 'help' in argv:
324             return argv
325
326         if len(argv) == 1:
327             return ['help', argv[0]]
328
329         if os.geteuid() != 0:
330             msger.error("Root permission is required, abort")
331
332         try:
333             w = pwd.getpwuid(os.geteuid())
334         except KeyError:
335             msger.warning("Might fail in compressing stage for undetermined user")
336
337         return argv
338
339     def do_auto(self, subcmd, opts, *args):
340         """${cmd_name}: auto detect image type from magic header
341
342         Usage:
343             ${name} ${cmd_name} <ksfile>
344
345         ${cmd_option_list}
346         """
347         def parse_magic_line(re_str, pstr, ptype='mic'):
348             ptn = re.compile(re_str)
349             m = ptn.match(pstr)
350             if not m or not m.groups():
351                 return None
352
353             inline_argv = m.group(1).strip()
354             if ptype == 'mic':
355                 m2 = re.search('(?P<format>\w+)', inline_argv)
356             elif ptype == 'mic2':
357                 m2 = re.search('(-f|--format(=)?)\s*(?P<format>\w+)',
358                                inline_argv)
359             else:
360                 return None
361
362             if m2:
363                 cmdname = m2.group('format')
364                 inline_argv = inline_argv.replace(m2.group(0), '')
365                 return (cmdname, inline_argv)
366
367             return None
368
369         if len(args) != 1:
370             raise errors.Usage("Extra arguments given")
371
372         if not os.path.exists(args[0]):
373             raise errors.CreatorError("Can't find the file: %s" % args[0])
374
375         with open(args[0], 'r') as rf:
376             first_line = rf.readline()
377
378         mic_re = '^#\s*-\*-mic-options-\*-\s+(.*)\s+-\*-mic-options-\*-'
379         mic2_re = '^#\s*-\*-mic2-options-\*-\s+(.*)\s+-\*-mic2-options-\*-'
380
381         result = parse_magic_line(mic_re, first_line, 'mic') \
382                  or parse_magic_line(mic2_re, first_line, 'mic2')
383         if not result:
384             raise errors.KsError("Invalid magic line in file: %s" % args[0])
385
386         if result[0] not in self._subcmds:
387             raise errors.KsError("Unsupport format '%s' in %s"
388                                  % (result[0], args[0]))
389
390         argv = ' '.join(result + args).split()
391         self.main(argv)
392