1 # -*- coding: utf-8 -*-
3 # Copyright 2012 GRNET S.A. All rights reserved.
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
9 # 1. Redistributions of source code must retain the above
10 # copyright notice, this list of conditions and the following
13 # 2. Redistributions in binary form must reproduce the above
14 # copyright notice, this list of conditions and the following
15 # disclaimer in the documentation and/or other materials
16 # provided with the distribution.
18 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
19 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
22 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
25 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
28 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 # POSSIBILITY OF SUCH DAMAGE.
31 # The views and conclusions contained in the software and
32 # documentation are those of the authors and should not be
33 # interpreted as representing official policies, either expressed
34 # or implied, of GRNET S.A.
36 """This package provides various classes for preparing different Operating
37 Systems for image creation.
40 from image_creator.util import FatalError
44 from collections import namedtuple
45 from functools import wraps
48 def os_cls(distro, osfamily):
49 """Given the distro name and the osfamily, return the appropriate class"""
53 module = __import__("image_creator.os_type.%s" % distro,
54 fromlist=['image_creator.os_type'])
55 classname = distro.capitalize()
57 module = __import__("image_creator.os_type.%s" % osfamily,
58 fromlist=['image_creator.os_type'])
59 classname = osfamily.capitalize()
61 return getattr(module, classname)
64 def add_prefix(target):
65 """Decorator that adds a prefix to the result of a function"""
66 def wrapper(self, *args):
68 return [prefix + path for path in target(self, *args)]
72 def sysprep(message, enabled=True, **kwargs):
73 """Decorator for system preparation tasks"""
76 method.enabled = enabled
77 method.executed = False
79 for key, val in kwargs.items():
80 setattr(method, key, val)
83 def inner(self, print_message=True):
85 self.out.output(message)
92 def add_sysprep_param(name, type, default, descr, validate=lambda x: True):
93 """Decorator for __init__ that adds the definition for a system preparation
94 parameter in an instance of a os_type class
98 def inner(self, *args, **kwargs):
99 init(self, *args, **kwargs)
100 self.needed_sysprep_params[name] = \
101 self.SysprepParam(type, default, descr, validate)
102 if default is not None:
103 self.sysprep_params[name] = default
108 def del_sysprep_param(name):
109 """Decorator for __init__ that deletes a previously added sysprep parameter
110 definition from an instance of a os_type class.
114 def inner(self, *args, **kwargs):
115 del self.needed_sysprep_params[name]
116 func(self, *args, **kwargs)
121 class OSBase(object):
122 """Basic operating system class"""
124 SysprepParam = namedtuple('SysprepParam',
125 ['type', 'default', 'description', 'validate'])
127 def __init__(self, image, **kargs):
130 self.root = image.root
133 self.needed_sysprep_params = {}
134 self.sysprep_params = \
135 kargs['sysprep_params'] if 'sysprep_params' in kargs else {}
140 # Many guestfs compilations don't support scrub
141 self._scrub_support = True
143 self.image.g.available(['scrub'])
145 self._scrub_support = False
148 """Inspect the media to check if it is supported"""
150 if self.image.is_unsupported():
153 self.out.output('Running OS inspection:')
155 if not self.mount(readonly=True):
156 raise FatalError("Unable to mount the media read-only")
163 def collect_metadata(self):
164 """Collect metadata about the OS"""
166 if not self.mount(readonly=True):
167 raise FatalError("Unable to mount the media read-only")
169 self.out.output('Collecting image metadata ...', False)
170 self._do_collect_metadata()
171 self.out.success('done')
177 def list_syspreps(self):
178 """Returns a list of sysprep objects"""
179 objs = [getattr(self, name) for name in dir(self)
180 if not name.startswith('_')]
182 return [x for x in objs if self._is_sysprep(x) and x.executed is False]
184 def sysprep_info(self, obj):
185 """Returns information about a sysprep object"""
186 assert self._is_sysprep(obj), "Object is not a sysprep"
188 SysprepInfo = namedtuple("SysprepInfo", "name description")
190 return SysprepInfo(obj.__name__.replace('_', '-'),
191 textwrap.dedent(obj.__doc__))
193 def get_sysprep_by_name(self, name):
194 """Returns the sysprep object with the given name"""
195 error_msg = "Syprep operation %s does not exist for %s" % \
196 (name, self.__class__.__name__)
198 method_name = name.replace('-', '_')
201 method = getattr(self, method_name)
202 except AttributeError:
203 raise FatalError(error_msg)
205 if not self._is_sysprep(method):
206 raise FatalError(error_msg)
210 def enable_sysprep(self, obj):
211 """Enable a system preparation operation"""
212 setattr(obj.im_func, 'enabled', True)
214 def disable_sysprep(self, obj):
215 """Disable a system preparation operation"""
216 setattr(obj.im_func, 'enabled', False)
218 def print_syspreps(self):
219 """Print enabled and disabled system preparation operations."""
221 syspreps = self.list_syspreps()
222 enabled = [sysprep for sysprep in syspreps if sysprep.enabled]
223 disabled = [sysprep for sysprep in syspreps if not sysprep.enabled]
225 wrapper = textwrap.TextWrapper()
226 wrapper.subsequent_indent = '\t'
227 wrapper.initial_indent = '\t'
230 self.out.output("Enabled system preparation operations:")
231 if len(enabled) == 0:
232 self.out.output("(none)")
234 for sysprep in enabled:
235 name = sysprep.__name__.replace('_', '-')
236 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
237 self.out.output(' %s:\n%s\n' % (name, descr))
239 self.out.output("Disabled system preparation operations:")
240 if len(disabled) == 0:
241 self.out.output("(none)")
243 for sysprep in disabled:
244 name = sysprep.__name__.replace('_', '-')
245 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
246 self.out.output(' %s:\n%s\n' % (name, descr))
248 def print_sysprep_params(self):
249 """Print the system preparation parameter the user may use"""
251 self.out.output("Needed system preparation parameters:")
253 if len(self.needed_sysprep_params) == 0:
254 self.out.output("(none)")
257 for name, param in self.needed_sysprep_params.items():
258 self.out.output("\t%s [%s]: %s" %
259 (param.description, name,
260 self.sysprep_params[name] if name in
261 self.sysprep_params else "(none)"))
263 def do_sysprep(self):
264 """Prepare system for image creation."""
266 self.out.output('Preparing system for image creation:')
268 if self.image.is_unsupported():
270 "System preparation is disabled for unsupported media")
274 if not self.mount(readonly=False):
275 raise FatalError("Unable to mount the media read-write")
277 enabled = [task for task in self.list_syspreps() if task.enabled]
283 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
285 setattr(task.im_func, 'executed', True)
291 def mount(self, readonly=False):
294 if getattr(self, "mounted", False):
297 mount_type = 'read-only' if readonly else 'read-write'
298 self.out.output("Mounting the media %s ..." % mount_type, False)
300 if not self._do_mount(readonly):
304 self.out.success('done')
308 """Umount all mounted filesystems."""
310 self.out.output("Umounting the media ...", False)
311 self.image.g.umount_all()
313 self.out.success('done')
315 def _is_sysprep(self, obj):
316 """Checks if an object is a sysprep"""
317 return getattr(obj, 'sysprep', False) and callable(obj)
320 def _ls(self, directory):
321 """List the name of all files under a directory"""
322 return self.image.g.ls(directory)
325 def _find(self, directory):
326 """List the name of all files recursively under a directory"""
327 return self.image.g.find(directory)
329 def _foreach_file(self, directory, action, **kargs):
330 """Perform an action recursively on all files under a directory.
332 The following options are allowed:
334 * maxdepth: If defined the action will not be performed on
335 files that are below this level of directories under the
338 * ftype: The action will only be performed on files of this
339 type. For a list of all allowed filetypes, see here:
340 http://libguestfs.org/guestfs.3.html#guestfs_readdir
342 * exclude: Exclude all files that follow this pattern.
344 if not self.image.g.is_dir(directory):
345 self.out.warn("Directory: `%s' does not exist!" % directory)
348 maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
353 maxdepth = None if maxdepth is None else maxdepth - 1
354 kargs['maxdepth'] = maxdepth
356 exclude = None if 'exclude' not in kargs else kargs['exclude']
357 ftype = None if 'ftype' not in kargs else kargs['ftype']
358 has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
360 for f in self.image.g.readdir(directory):
361 if f['name'] in ('.', '..'):
364 full_path = "%s/%s" % (directory, f['name'])
366 if exclude and re.match(exclude, full_path):
369 if has_ftype(f, 'd'):
370 self._foreach_file(full_path, action, **kargs)
372 if has_ftype(f, ftype):
375 def _do_inspect(self):
376 """helper method for inspect"""
379 def _do_collect_metadata(self):
380 """helper method for collect_metadata"""
383 self.meta['ROOT_PARTITION'] = \
384 "%d" % self.image.g.part_to_partnum(self.root)
386 self.out.warn("Unable to identify the partition number from root "
387 "partition: %s" % self.root)
389 self.meta['OSFAMILY'] = self.image.g.inspect_get_type(self.root)
390 self.meta['OS'] = self.image.g.inspect_get_distro(self.root)
391 if self.meta['OS'] == "unknown":
392 self.meta['OS'] = self.meta['OSFAMILY']
393 self.meta['DESCRIPTION'] = \
394 self.image.g.inspect_get_product_name(self.root)
396 def _do_mount(self, readonly):
397 """helper method for mount"""
399 self.image.g.mount_options(
400 'ro' if readonly else 'rw', self.root, '/')
401 except RuntimeError as msg:
402 self.out.warn("unable to mount the root partition: %s" % msg)
407 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :