3 # Copyright (c) 2011 Intel, Inc.
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
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
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.
20 from optparse import SUPPRESS_HELP
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
28 class Creator(cmdln.Cmdln):
29 """${name}: create an image
32 ${name} SUBCOMMAND <ksfile> [OPTS]
38 name = 'mic create(cr)'
40 def __init__(self, *args, **kwargs):
41 cmdln.Cmdln.__init__(self, *args, **kwargs)
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)
51 func = getattr(klass, 'do_create')
52 setattr(self.__class__, "do_"+subcmd, func)
53 self._subcmds.append(subcmd)
55 def get_optparser(self):
56 optparser = cmdln.CmdlnOptionParser(self)
57 optparser.add_option('-d', '--debug', action='store_true',
60 optparser.add_option('-v', '--verbose', action='store_true',
63 optparser.add_option('', '--logfile', type='string', dest='logfile',
65 help='Path of logfile')
66 optparser.add_option('-c', '--config', type='string', dest='config',
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',
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',
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,
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 '
108 optparser.add_option('', '--copy-kernel', action='store_true',
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=[],
128 def preoptparse(self, argv):
129 optparser = self.get_optparser()
136 if arg in ('-h', '--help'):
139 elif optparser.has_option(arg):
142 if optparser.get_option(arg).takes_value():
144 largs.append(argv.pop(0))
146 raise errors.Usage("option %s requires arguments" % arg)
149 if arg.startswith("--"):
151 opt = arg.split("=")[0]
154 elif arg.startswith("-") and len(arg) > 2:
159 if opt and optparser.has_option(opt):
166 def postoptparse(self):
167 abspath = lambda pth: os.path.abspath(os.path.expanduser(pth))
169 if self.options.verbose:
170 msger.set_loglevel('VERBOSE')
171 if self.options.debug:
172 msger.set_loglevel('DEBUG')
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
185 if self.options.config:
187 configmgr._siteconf = self.options.config
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']
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])
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
207 if self.options.release:
208 configmgr.create['release'] = self.options.release.rstrip('/')
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"' \
218 configmgr.create['record_pkgs'].append(infotype)
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
225 raise errors.Usage('Invalid architecture: "%s".\n'
226 ' Supported architectures are: \n'
227 ' %s' % (self.options.arch,
228 ', '.join(supported_arch)))
230 if self.options.pkgmgr is not None:
231 configmgr.create['pkgmgr'] = self.options.pkgmgr
233 if self.options.runtime:
234 configmgr.set_runtime(self.options.runtime)
236 if self.options.pack_to is not None:
237 configmgr.create['pack_to'] = self.options.pack_to
239 if self.options.copy_kernel:
240 configmgr.create['copy_kernel'] = self.options.copy_kernel
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)
250 configmgr.create['install_pkgs'].append(pkgtype)
252 if self.options.check_pkgs:
253 for pkg in self.options.check_pkgs.split(','):
254 configmgr.create['check_pkgs'].append(pkg)
256 if self.options.enabletmpfs:
257 configmgr.create['enabletmpfs'] = self.options.enabletmpfs
259 if self.options.repourl:
260 for item in self.options.repourl:
262 key, val = item.split('=')
265 configmgr.create['repourl'][key] = val
267 def main(self, argv=None):
271 argv = argv[:] # don't modify caller's list
273 self.optparser = self.get_optparser()
276 argv = self.preoptparse(argv)
277 self.options, args = self.optparser.parse_args(argv)
279 except cmdln.CmdlnUserError, ex:
280 msg = "%s: %s\nTry '%s help' for info.\n"\
281 % (self.name, ex, self.name)
284 except cmdln.StopOptionProcessing, ex:
287 # optparser=None means no process for opts
288 self.options, args = None, argv[1:]
291 return self.emptyline()
295 return self.cmd(args)
297 def precmd(self, argv): # check help before cmd
299 if '-h' in argv or '?' in argv or '--help' in argv or 'help' in argv:
303 return ['help', argv[0]]
305 if os.geteuid() != 0:
306 msger.error("Root permission is required, abort")
309 w = pwd.getpwuid(os.geteuid())
311 msger.warning("Might fail in compressing stage for undetermined user")
315 def do_auto(self, subcmd, opts, *args):
316 """${cmd_name}: auto detect image type from magic header
319 ${name} ${cmd_name} <ksfile>
323 def parse_magic_line(re_str, pstr, ptype='mic'):
324 ptn = re.compile(re_str)
326 if not m or not m.groups():
329 inline_argv = m.group(1).strip()
331 m2 = re.search('(?P<format>\w+)', inline_argv)
332 elif ptype == 'mic2':
333 m2 = re.search('(-f|--format(=)?)\s*(?P<format>\w+)',
339 cmdname = m2.group('format')
340 inline_argv = inline_argv.replace(m2.group(0), '')
341 return (cmdname, inline_argv)
346 raise errors.Usage("Extra arguments given")
348 if not os.path.exists(args[0]):
349 raise errors.CreatorError("Can't find the file: %s" % args[0])
351 with open(args[0], 'r') as rf:
352 first_line = rf.readline()
354 mic_re = '^#\s*-\*-mic-options-\*-\s+(.*)\s+-\*-mic-options-\*-'
355 mic2_re = '^#\s*-\*-mic2-options-\*-\s+(.*)\s+-\*-mic2-options-\*-'
357 result = parse_magic_line(mic_re, first_line, 'mic') \
358 or parse_magic_line(mic2_re, first_line, 'mic2')
360 raise errors.KsError("Invalid magic line in file: %s" % args[0])
362 if result[0] not in self._subcmds:
363 raise errors.KsError("Unsupport format '%s' in %s"
364 % (result[0], args[0]))
366 argv = ' '.join(result + args).split()