add vcs value for --record-pkgs to record vcs info
[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 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, native')
96         # --taring-to is alias to --pack-to
97         optparser.add_option('', '--taring-to', type='string',
98                              dest='pack_to', default=None,
99                              help=SUPPRESS_HELP)
100         optparser.add_option('', '--pack-to', type='string',
101                              dest='pack_to', default=None,
102                              help='Pack the images together into the specified'
103                                   ' achive, extension supported: .zip, .tar, '
104                                   '.tar.gz, .tar.bz2, etc. by default, .tar '
105                                   'will be used')
106         optparser.add_option('', '--copy-kernel', action='store_true',
107                              dest='copy_kernel',
108                              help='Copy kernel files from image /boot directory'
109                                   ' to the image output directory.')
110         optparser.add_option('', '--repourl', action='append',
111                              dest='repourl', default=[],
112                              help=SUPPRESS_HELP)
113         return optparser
114
115     def preoptparse(self, argv):
116         optparser = self.get_optparser()
117
118         largs = []
119         rargs = []
120         while argv:
121             arg = argv.pop(0)
122
123             if arg in ('-h', '--help'):
124                 rargs.append(arg)
125
126             elif optparser.has_option(arg):
127                 largs.append(arg)
128
129                 if optparser.get_option(arg).takes_value():
130                     try:
131                         largs.append(argv.pop(0))
132                     except IndexError:
133                         raise errors.Usage("option %s requires arguments" % arg)
134
135             else:
136                 if arg.startswith("--"):
137                     if "=" in arg:
138                         opt = arg.split("=")[0]
139                     else:
140                         opt = None
141                 elif arg.startswith("-") and len(arg) > 2:
142                     opt = arg[0:2]
143                 else:
144                     opt = None
145
146                 if opt and optparser.has_option(opt):
147                     largs.append(arg)
148                 else:
149                     rargs.append(arg)
150
151         return largs + rargs
152
153     def postoptparse(self):
154         abspath = lambda pth: os.path.abspath(os.path.expanduser(pth))
155
156         if self.options.verbose:
157             msger.set_loglevel('verbose')
158         if self.options.debug:
159             msger.set_loglevel('debug')
160
161         if self.options.logfile:
162             logfile_abs_path = abspath(self.options.logfile)
163             if os.path.isdir(logfile_abs_path):
164                 raise errors.Usage("logfile's path %s should be file"
165                                    % self.options.logfile)
166             if not os.path.exists(os.path.dirname(logfile_abs_path)):
167                 os.makedirs(os.path.dirname(logfile_abs_path))
168             msger.set_interactive(False)
169             msger.set_logfile(logfile_abs_path)
170             configmgr.create['logfile'] = self.options.logfile
171
172         if self.options.config:
173             configmgr.reset()
174             configmgr._siteconf = self.options.config
175
176         if self.options.outdir is not None:
177             configmgr.create['outdir'] = abspath(self.options.outdir)
178         if self.options.cachedir is not None:
179             configmgr.create['cachedir'] = abspath(self.options.cachedir)
180         os.environ['ZYPP_LOCKFILE_ROOT'] = configmgr.create['cachedir']
181
182         for cdir in ('outdir', 'cachedir'):
183             if os.path.exists(configmgr.create[cdir]) \
184               and not os.path.isdir(configmgr.create[cdir]):
185                 msger.error('Invalid directory specified: %s' \
186                             % configmgr.create[cdir])
187
188         if self.options.local_pkgs_path is not None:
189             if not os.path.exists(self.options.local_pkgs_path):
190                 msger.error('Local pkgs directory: \'%s\' not exist' \
191                               % self.options.local_pkgs_path)
192             configmgr.create['local_pkgs_path'] = self.options.local_pkgs_path
193
194         if self.options.release:
195             configmgr.create['release'] = self.options.release
196
197         if self.options.record_pkgs:
198             configmgr.create['record_pkgs'] = []
199             for infotype in self.options.record_pkgs.split(','):
200                 if infotype not in ('name', 'content', 'license', 'vcs'):
201                     raise errors.Usage('Invalid pkg recording: %s, valid ones:'
202                                        ' "name", "content", "license", "vcs"' \
203                                        % infotype)
204
205                 configmgr.create['record_pkgs'].append(infotype)
206
207         if self.options.arch is not None:
208             supported_arch = sorted(rpmmisc.archPolicies.keys(), reverse=True)
209             if self.options.arch in supported_arch:
210                 configmgr.create['arch'] = self.options.arch
211             else:
212                 raise errors.Usage('Invalid architecture: "%s".\n'
213                                    '  Supported architectures are: \n'
214                                    '  %s' % (self.options.arch,
215                                                ', '.join(supported_arch)))
216
217         if self.options.pkgmgr is not None:
218             configmgr.create['pkgmgr'] = self.options.pkgmgr
219
220         if self.options.runtime:
221             configmgr.set_runtime(self.options.runtime)
222
223         if self.options.pack_to is not None:
224             configmgr.create['pack_to'] = self.options.pack_to
225
226         if self.options.copy_kernel:
227             configmgr.create['copy_kernel'] = self.options.copy_kernel
228
229         if self.options.repourl:
230             for item in self.options.repourl:
231                 try:
232                     key, val = item.split('=')
233                 except:
234                     continue
235                 configmgr.create['repourl'][key] = val
236
237     def main(self, argv=None):
238         if argv is None:
239             argv = sys.argv
240         else:
241             argv = argv[:] # don't modify caller's list
242
243         self.optparser = self.get_optparser()
244         if self.optparser:
245             try:
246                 argv = self.preoptparse(argv)
247                 self.options, args = self.optparser.parse_args(argv)
248
249             except cmdln.CmdlnUserError, ex:
250                 msg = "%s: %s\nTry '%s help' for info.\n"\
251                       % (self.name, ex, self.name)
252                 msger.error(msg)
253
254             except cmdln.StopOptionProcessing, ex:
255                 return 0
256         else:
257             # optparser=None means no process for opts
258             self.options, args = None, argv[1:]
259
260         if not args:
261             return self.emptyline()
262
263         self.postoptparse()
264
265         return self.cmd(args)
266
267     def precmd(self, argv): # check help before cmd
268
269         if '-h' in argv or '?' in argv or '--help' in argv or 'help' in argv:
270             return argv
271
272         if len(argv) == 1:
273             return ['help', argv[0]]
274
275         if os.geteuid() != 0:
276             raise msger.error("Root permission is required, abort")
277
278         return argv
279
280     def do_auto(self, subcmd, opts, *args):
281         """${cmd_name}: auto detect image type from magic header
282
283         Usage:
284             ${name} ${cmd_name} <ksfile>
285
286         ${cmd_option_list}
287         """
288         def parse_magic_line(re_str, pstr, ptype='mic'):
289             ptn = re.compile(re_str)
290             m = ptn.match(pstr)
291             if not m or not m.groups():
292                 return None
293
294             inline_argv = m.group(1).strip()
295             if ptype == 'mic':
296                 m2 = re.search('(?P<format>\w+)', inline_argv)
297             elif ptype == 'mic2':
298                 m2 = re.search('(-f|--format(=)?)\s*(?P<format>\w+)',
299                                inline_argv)
300             else:
301                 return None
302
303             if m2:
304                 cmdname = m2.group('format')
305                 inline_argv = inline_argv.replace(m2.group(0), '')
306                 return (cmdname, inline_argv)
307
308             return None
309
310         if len(args) != 1:
311             raise errors.Usage("Extra arguments given")
312
313         if not os.path.exists(args[0]):
314             raise errors.CreatorError("Can't find the file: %s" % args[0])
315
316         with open(args[0], 'r') as rf:
317             first_line = rf.readline()
318
319         mic_re = '^#\s*-\*-mic-options-\*-\s+(.*)\s+-\*-mic-options-\*-'
320         mic2_re = '^#\s*-\*-mic2-options-\*-\s+(.*)\s+-\*-mic2-options-\*-'
321
322         result = parse_magic_line(mic_re, first_line, 'mic') \
323                  or parse_magic_line(mic2_re, first_line, 'mic2')
324         if not result:
325             raise errors.KsError("Invalid magic line in file: %s" % args[0])
326
327         if result[0] not in self._subcmds:
328             raise errors.KsError("Unsupport format '%s' in %s"
329                                  % (result[0], args[0]))
330
331         argv = ' '.join(result + args).split()
332         self.main(argv)
333