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
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=[],
126 optparser.add_option('-R', '--repo', action='append',
127 dest='repo', default=[],
129 optparser.add_option('', '--ignore-ksrepo', action='store_true',
130 dest='ignore_ksrepo', default=False,
134 def preoptparse(self, argv):
135 optparser = self.get_optparser()
142 if arg in ('-h', '--help'):
145 elif optparser.has_option(arg):
148 if optparser.get_option(arg).takes_value():
150 largs.append(argv.pop(0))
152 raise errors.Usage("option %s requires arguments" % arg)
155 if arg.startswith("--"):
157 opt = arg.split("=")[0]
160 elif arg.startswith("-") and len(arg) > 2:
165 if opt and optparser.has_option(opt):
172 def postoptparse(self):
173 abspath = lambda pth: os.path.abspath(os.path.expanduser(pth))
175 if self.options.verbose:
176 msger.set_loglevel('VERBOSE')
177 if self.options.debug:
178 msger.set_loglevel('DEBUG')
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()
188 if self.options.config:
190 configmgr._siteconf = self.options.config
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']
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')))
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
216 if self.options.release:
217 configmgr.create['release'] = self.options.release.rstrip('/')
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"' \
227 configmgr.create['record_pkgs'].append(infotype)
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
234 raise errors.Usage('Invalid architecture: "%s".\n'
235 ' Supported architectures are: \n'
236 ' %s' % (self.options.arch,
237 ', '.join(supported_arch)))
239 if self.options.pkgmgr is not None:
240 configmgr.create['pkgmgr'] = self.options.pkgmgr
242 if self.options.runtime:
243 configmgr.set_runtime(self.options.runtime)
245 if self.options.pack_to is not None:
246 configmgr.create['pack_to'] = self.options.pack_to
248 if self.options.copy_kernel:
249 configmgr.create['copy_kernel'] = self.options.copy_kernel
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)
259 configmgr.create['install_pkgs'].append(pkgtype)
261 if self.options.check_pkgs:
262 for pkg in self.options.check_pkgs.split(','):
263 configmgr.create['check_pkgs'].append(pkg)
265 if self.options.enabletmpfs:
266 configmgr.create['enabletmpfs'] = self.options.enabletmpfs
268 if self.options.repourl:
269 for item in self.options.repourl:
271 key, val = item.split('=')
274 configmgr.create['repourl'][key] = val
276 if self.options.repo:
277 for optvalue in self.options.repo:
279 for item in optvalue.split(';'):
281 key, val = item.split('=')
284 repo[key.strip()] = val.strip()
286 configmgr.create['extrarepos'][repo['name']] = repo
288 if self.options.ignore_ksrepo:
289 configmgr.create['ignore_ksrepo'] = self.options.ignore_ksrepo
291 def main(self, argv=None):
295 argv = argv[:] # don't modify caller's list
297 self.optparser = self.get_optparser()
300 argv = self.preoptparse(argv)
301 self.options, args = self.optparser.parse_args(argv)
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)
308 except cmdln.StopOptionProcessing, ex:
311 # optparser=None means no process for opts
312 self.options, args = None, argv[1:]
315 return self.emptyline()
319 return self.cmd(args)
321 def precmd(self, argv): # check help before cmd
323 if '-h' in argv or '?' in argv or '--help' in argv or 'help' in argv:
327 return ['help', argv[0]]
329 if os.geteuid() != 0:
330 msger.error("Root permission is required, abort")
333 w = pwd.getpwuid(os.geteuid())
335 msger.warning("Might fail in compressing stage for undetermined user")
339 def do_auto(self, subcmd, opts, *args):
340 """${cmd_name}: auto detect image type from magic header
343 ${name} ${cmd_name} <ksfile>
347 def parse_magic_line(re_str, pstr, ptype='mic'):
348 ptn = re.compile(re_str)
350 if not m or not m.groups():
353 inline_argv = m.group(1).strip()
355 m2 = re.search('(?P<format>\w+)', inline_argv)
356 elif ptype == 'mic2':
357 m2 = re.search('(-f|--format(=)?)\s*(?P<format>\w+)',
363 cmdname = m2.group('format')
364 inline_argv = inline_argv.replace(m2.group(0), '')
365 return (cmdname, inline_argv)
370 raise errors.Usage("Extra arguments given")
372 if not os.path.exists(args[0]):
373 raise errors.CreatorError("Can't find the file: %s" % args[0])
375 with open(args[0], 'r') as rf:
376 first_line = rf.readline()
378 mic_re = '^#\s*-\*-mic-options-\*-\s+(.*)\s+-\*-mic-options-\*-'
379 mic2_re = '^#\s*-\*-mic2-options-\*-\s+(.*)\s+-\*-mic2-options-\*-'
381 result = parse_magic_line(mic_re, first_line, 'mic') \
382 or parse_magic_line(mic2_re, first_line, 'mic2')
384 raise errors.KsError("Invalid magic line in file: %s" % args[0])
386 if result[0] not in self._subcmds:
387 raise errors.KsError("Unsupport format '%s' in %s"
388 % (result[0], args[0]))
390 argv = ' '.join(result + args).split()