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
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')
97 # --taring-to is alias to --pack-to
98 optparser.add_option('', '--taring-to', type='string',
99 dest='pack_to', default=None,
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 '
107 optparser.add_option('', '--copy-kernel', action='store_true',
109 help='Copy kernel files from image /boot directory'
110 ' to the image output directory.')
113 def preoptparse(self, argv):
114 optparser = self.get_optparser()
121 if arg in ('-h', '--help'):
124 elif optparser.has_option(arg):
127 if optparser.get_option(arg).takes_value():
129 largs.append(argv.pop(0))
131 raise errors.Usage("option %s requires arguments" % arg)
134 if arg.startswith("--"):
136 opt = arg.split("=")[0]
139 elif arg.startswith("-") and len(arg) > 2:
144 if opt and optparser.has_option(opt):
151 def postoptparse(self):
152 abspath = lambda pth: os.path.abspath(os.path.expanduser(pth))
154 if self.options.verbose:
155 msger.set_loglevel('verbose')
156 if self.options.debug:
157 msger.set_loglevel('debug')
159 if self.options.logfile:
160 msger.set_interactive(False)
161 msger.set_logfile(self.options.logfile)
162 configmgr.create['logfile'] = self.options.logfile
164 if self.options.config:
166 configmgr._siteconf = self.options.config
168 if self.options.outdir is not None:
169 configmgr.create['outdir'] = abspath(self.options.outdir)
170 if self.options.cachedir is not None:
171 configmgr.create['cachedir'] = abspath(self.options.cachedir)
172 os.environ['ZYPP_LOCKFILE_ROOT'] = configmgr.create['cachedir']
174 if self.options.local_pkgs_path is not None:
175 if not os.path.exists(self.options.local_pkgs_path):
176 msger.error('Local pkgs directory: \'%s\' not exist' \
177 % self.options.local_pkgs_path)
178 configmgr.create['local_pkgs_path'] = self.options.local_pkgs_path
180 if self.options.release:
181 configmgr.create['release'] = self.options.release
183 if self.options.record_pkgs:
184 configmgr.create['record_pkgs'] = []
185 for infotype in self.options.record_pkgs.split(','):
186 if infotype not in ('name', 'content', 'license'):
187 raise errors.Usage('Invalid pkg recording: %s, valid ones:'
188 ' "name", "content", "license"' \
191 configmgr.create['record_pkgs'].append(infotype)
193 if self.options.arch is not None:
194 supported_arch = sorted(rpmmisc.archPolicies.keys(), reverse=True)
195 if self.options.arch in supported_arch:
196 configmgr.create['arch'] = self.options.arch
198 raise errors.Usage('Invalid architecture: "%s".\n'
199 ' Supported architectures are: \n'
200 ' %s' % (self.options.arch,
201 ', '.join(supported_arch)))
203 if self.options.pkgmgr is not None:
204 configmgr.create['pkgmgr'] = self.options.pkgmgr
206 if self.options.runtime:
207 configmgr.create['runtime'] = self.options.runtime
209 if self.options.pack_to is not None:
210 configmgr.create['pack_to'] = self.options.pack_to
212 if self.options.copy_kernel:
213 configmgr.create['copy_kernel'] = self.options.copy_kernel
215 def main(self, argv=None):
219 argv = argv[:] # don't modify caller's list
221 self.optparser = self.get_optparser()
224 argv = self.preoptparse(argv)
225 self.options, args = self.optparser.parse_args(argv)
227 except cmdln.CmdlnUserError, ex:
228 msg = "%s: %s\nTry '%s help' for info.\n"\
229 % (self.name, ex, self.name)
232 except cmdln.StopOptionProcessing, ex:
235 # optparser=None means no process for opts
236 self.options, args = None, argv[1:]
239 return self.emptyline()
243 if os.geteuid() != 0 and args[0] != 'help':
244 msger.error('root permission is required to continue, abort')
246 return self.cmd(args)
248 def do_auto(self, subcmd, opts, *args):
249 """${cmd_name}: auto detect image type from magic header
252 ${name} ${cmd_name} <ksfile>
256 def parse_magic_line(re_str, pstr, ptype='mic'):
257 ptn = re.compile(re_str)
259 if not m or not m.groups():
262 inline_argv = m.group(1).strip()
264 m2 = re.search('(?P<format>\w+)', inline_argv)
265 elif ptype == 'mic2':
266 m2 = re.search('(-f|--format(=)?)\s*(?P<format>\w+)',
272 cmdname = m2.group('format')
273 inline_argv = inline_argv.replace(m2.group(0), '')
274 return (cmdname, inline_argv)
279 self.do_help(['help', subcmd])
283 raise errors.Usage("Extra arguments given")
285 if not os.path.exists(args[0]):
286 raise errors.CreatorError("Can't find the file: %s" % args[0])
288 with open(args[0], 'r') as rf:
289 first_line = rf.readline()
291 mic_re = '^#\s*-\*-mic-options-\*-\s+(.*)\s+-\*-mic-options-\*-'
292 mic2_re = '^#\s*-\*-mic2-options-\*-\s+(.*)\s+-\*-mic2-options-\*-'
294 result = parse_magic_line(mic_re, first_line, 'mic') \
295 or parse_magic_line(mic2_re, first_line, 'mic2')
297 raise errors.KsError("Invalid magic line in file: %s" % args[0])
299 if result[0] not in self._subcmds:
300 raise errors.KsError("Unsupport format '%s' in %s"
301 % (result[0], args[0]))
303 argv = ' '.join(result + args).split()