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.
19 from optparse import SUPPRESS_HELP
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
26 class Creator(cmdln.Cmdln):
27 """${name}: create an image
30 ${name} SUBCOMMAND <ksfile> [OPTS]
36 name = 'mic create(cr)'
38 def __init__(self, *args, **kwargs):
39 cmdln.Cmdln.__init__(self, *args, **kwargs)
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)
49 func = getattr(klass, 'do_create')
50 setattr(self.__class__, "do_"+subcmd, func)
51 self._subcmds.append(subcmd)
53 def get_optparser(self):
54 optparser = cmdln.CmdlnOptionParser(self)
55 optparser.add_option('-d', '--debug', action='store_true',
58 optparser.add_option('-v', '--verbose', action='store_true',
61 optparser.add_option('', '--logfile', type='string', dest='logfile',
63 help='Path of logfile')
64 optparser.add_option('-c', '--config', type='string', dest='config',
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',
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',
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,
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 '
106 optparser.add_option('', '--copy-kernel', action='store_true',
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=[],
115 def preoptparse(self, argv):
116 optparser = self.get_optparser()
123 if arg in ('-h', '--help'):
126 elif optparser.has_option(arg):
129 if optparser.get_option(arg).takes_value():
131 largs.append(argv.pop(0))
133 raise errors.Usage("option %s requires arguments" % arg)
136 if arg.startswith("--"):
138 opt = arg.split("=")[0]
141 elif arg.startswith("-") and len(arg) > 2:
146 if opt and optparser.has_option(opt):
153 def postoptparse(self):
154 abspath = lambda pth: os.path.abspath(os.path.expanduser(pth))
156 if self.options.verbose:
157 msger.set_loglevel('verbose')
158 if self.options.debug:
159 msger.set_loglevel('debug')
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
172 if self.options.config:
174 configmgr._siteconf = self.options.config
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']
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])
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
194 if self.options.release:
195 configmgr.create['release'] = self.options.release
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'):
201 raise errors.Usage('Invalid pkg recording: %s, valid ones:'
202 ' "name", "content", "license"' \
205 configmgr.create['record_pkgs'].append(infotype)
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
212 raise errors.Usage('Invalid architecture: "%s".\n'
213 ' Supported architectures are: \n'
214 ' %s' % (self.options.arch,
215 ', '.join(supported_arch)))
217 if self.options.pkgmgr is not None:
218 configmgr.create['pkgmgr'] = self.options.pkgmgr
220 if self.options.runtime:
221 configmgr.set_runtime(self.options.runtime)
223 if self.options.pack_to is not None:
224 configmgr.create['pack_to'] = self.options.pack_to
226 if self.options.copy_kernel:
227 configmgr.create['copy_kernel'] = self.options.copy_kernel
229 if self.options.repourl:
230 for item in self.options.repourl:
232 key, val = item.split('=')
235 configmgr.create['repourl'][key] = val
237 def main(self, argv=None):
241 argv = argv[:] # don't modify caller's list
243 self.optparser = self.get_optparser()
246 argv = self.preoptparse(argv)
247 self.options, args = self.optparser.parse_args(argv)
249 except cmdln.CmdlnUserError, ex:
250 msg = "%s: %s\nTry '%s help' for info.\n"\
251 % (self.name, ex, self.name)
254 except cmdln.StopOptionProcessing, ex:
257 # optparser=None means no process for opts
258 self.options, args = None, argv[1:]
261 return self.emptyline()
265 return self.cmd(args)
267 def precmd(self, argv): # check help before cmd
269 if '-h' in argv or '?' in argv or '--help' in argv or 'help' in argv:
273 return ['help', argv[0]]
275 if os.geteuid() != 0:
276 raise msger.error("Root permission is required, abort")
280 def do_auto(self, subcmd, opts, *args):
281 """${cmd_name}: auto detect image type from magic header
284 ${name} ${cmd_name} <ksfile>
288 def parse_magic_line(re_str, pstr, ptype='mic'):
289 ptn = re.compile(re_str)
291 if not m or not m.groups():
294 inline_argv = m.group(1).strip()
296 m2 = re.search('(?P<format>\w+)', inline_argv)
297 elif ptype == 'mic2':
298 m2 = re.search('(-f|--format(=)?)\s*(?P<format>\w+)',
304 cmdname = m2.group('format')
305 inline_argv = inline_argv.replace(m2.group(0), '')
306 return (cmdname, inline_argv)
311 raise errors.Usage("Extra arguments given")
313 if not os.path.exists(args[0]):
314 raise errors.CreatorError("Can't find the file: %s" % args[0])
316 with open(args[0], 'r') as rf:
317 first_line = rf.readline()
319 mic_re = '^#\s*-\*-mic-options-\*-\s+(.*)\s+-\*-mic-options-\*-'
320 mic2_re = '^#\s*-\*-mic2-options-\*-\s+(.*)\s+-\*-mic2-options-\*-'
322 result = parse_magic_line(mic_re, first_line, 'mic') \
323 or parse_magic_line(mic2_re, first_line, 'mic2')
325 raise errors.KsError("Invalid magic line in file: %s" % args[0])
327 if result[0] not in self._subcmds:
328 raise errors.KsError("Unsupport format '%s' in %s"
329 % (result[0], args[0]))
331 argv = ' '.join(result + args).split()