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