X-Git-Url: https://code.grnet.gr/git/snf-image-creator/blobdiff_plain/4a2fd05c4fad9b757ad1ae2df973ddc790a6921e..b9a8a12121f5d6823ac2ee223a0b32a951255788:/image_creator/os_type/__init__.py diff --git a/image_creator/os_type/__init__.py b/image_creator/os_type/__init__.py index 052a3e3..ec4f20d 100644 --- a/image_creator/os_type/__init__.py +++ b/image_creator/os_type/__init__.py @@ -1,3 +1,5 @@ +# -*- coding: utf-8 -*- +# # Copyright 2012 GRNET S.A. All rights reserved. # # Redistribution and use in source and binary forms, with or @@ -31,22 +33,27 @@ # interpreted as representing official policies, either expressed # or implied, of GRNET S.A. -from image_creator.util import output, FatalError +"""This package provides various classes for preparing different Operating +Systems for image creation. +""" + +from image_creator.util import FatalError import textwrap import re -def get_os_class(distro, osfamily): +def os_cls(distro, osfamily): + """Given the distro name and the osfamily, return the appropriate class""" module = None classname = None try: - module = __import__("image_creator.os_type.%s" - % distro, fromlist=['image_creator.os_type']) + module = __import__("image_creator.os_type.%s" % distro, + fromlist=['image_creator.os_type']) classname = distro.capitalize() except ImportError: - module = __import__("image_creator.os_type.%s" - % osfamily, fromlist=['image_creator.os_type']) + module = __import__("image_creator.os_type.%s" % osfamily, + fromlist=['image_creator.os_type']) classname = osfamily.capitalize() return getattr(module, classname) @@ -60,9 +67,11 @@ def add_prefix(target): def sysprep(enabled=True): + """Decorator for system preparation tasks""" def wrapper(func): func.sysprep = True func.enabled = enabled + func.executed = False return func return wrapper @@ -70,27 +79,43 @@ def sysprep(enabled=True): class OSBase(object): """Basic operating system class""" - def __init__(self, rootdev, ghandler): + def __init__(self, rootdev, ghandler, output): self.root = rootdev self.g = ghandler + self.out = output + self.meta = {} - def _is_sysprep(self, obj): - return getattr(obj, 'sysprep', False) and callable(obj) + def collect_metadata(self): + """Collect metadata about the OS""" + try: + if not self.mount(readonly=True): + raise FatalError("Unable to mount the media read-only") - def list_syspreps(self): + self.out.output('Collecting image metadata ...', False) + self._do_collect_metadata() + self.out.success('done') + finally: + self.umount() - objs = [getattr(self, name) for name in dir(self) \ - if not name.startswith('_')] + self.out.output() + + def list_syspreps(self): + """Returns a list of sysprep objects""" + objs = [getattr(self, name) for name in dir(self) + if not name.startswith('_')] - enabled = [x for x in objs if self._is_sysprep(x) and x.enabled] - disabled = [x for x in objs if self._is_sysprep(x) and not x.enabled] + return [x for x in objs if self._is_sysprep(x) and x.executed is False] - return enabled, disabled + def sysprep_info(self, obj): + """Returns information about a sysprep object""" + assert self._is_sysprep(obj), "Object is not a sysprep" - def _sysprep_change_status(self, name, status): + return (obj.__name__.replace('_', '-'), textwrap.dedent(obj.__doc__)) + def get_sysprep_by_name(self, name): + """Returns the sysprep object with the given name""" error_msg = "Syprep operation %s does not exist for %s" % \ - (name, self.__class__.__name__) + (name, self.__class__.__name__) method_name = name.replace('-', '_') method = None @@ -102,55 +127,109 @@ class OSBase(object): if not self._is_sysprep(method): raise FatalError(error_msg) - setattr(method.im_func, 'enabled', status) + return method - def enable_sysprep(self, name): - """Enable a system preperation operation""" - self._sysprep_change_status(name, True) + def enable_sysprep(self, obj): + """Enable a system preparation operation""" + setattr(obj.im_func, 'enabled', True) - def disable_sysprep(self, name): - """Disable a system preperation operation""" - self._sysprep_change_status(name, False) + def disable_sysprep(self, obj): + """Disable a system preparation operation""" + setattr(obj.im_func, 'enabled', False) def print_syspreps(self): - """Print enabled and disabled system preperation operations.""" + """Print enabled and disabled system preparation operations.""" - enabled, disabled = self.list_syspreps() + syspreps = self.list_syspreps() + enabled = filter(lambda x: x.enabled, syspreps) + disabled = filter(lambda x: not x.enabled, syspreps) wrapper = textwrap.TextWrapper() wrapper.subsequent_indent = '\t' wrapper.initial_indent = '\t' wrapper.width = 72 - output("Enabled system preperation operations:") + self.out.output("Enabled system preparation operations:") if len(enabled) == 0: - output("(none)") + self.out.output("(none)") else: for sysprep in enabled: name = sysprep.__name__.replace('_', '-') descr = wrapper.fill(textwrap.dedent(sysprep.__doc__)) - output(' %s:\n%s\n' % (name, descr)) + self.out.output(' %s:\n%s\n' % (name, descr)) - output("Disabled system preperation operations:") + self.out.output("Disabled system preparation operations:") if len(disabled) == 0: - output("(none)") + self.out.output("(none)") else: for sysprep in disabled: name = sysprep.__name__.replace('_', '-') descr = wrapper.fill(textwrap.dedent(sysprep.__doc__)) - output(' %s:\n%s\n' % (name, descr)) + self.out.output(' %s:\n%s\n' % (name, descr)) + + def do_sysprep(self): + """Prepare system for image creation.""" + + try: + if not self.mount(readonly=False): + raise FatalError("Unable to mount the media read-write") + + self.out.output('Preparing system for image creation:') + + tasks = self.list_syspreps() + enabled = filter(lambda x: x.enabled, tasks) + + size = len(enabled) + cnt = 0 + for task in enabled: + cnt += 1 + self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False) + task() + setattr(task.im_func, 'executed', True) + finally: + self.umount() + + self.out.output() + + def mount(self, readonly=False): + """Mount image.""" + + if getattr(self, "mounted", False): + return True + + mount_type = 'read-only' if readonly else 'read-write' + self.out.output("Mounting the media %s ..." % mount_type, False) + + if not self._do_mount(readonly): + return False + + self.mounted = True + self.out.success('done') + return True + + def umount(self): + """Umount all mounted filesystems.""" + + self.out.output("Umounting the media ...", False) + self.g.umount_all() + self.mounted = False + self.out.success('done') + + def _is_sysprep(self, obj): + """Checks if an object is a sysprep""" + return getattr(obj, 'sysprep', False) and callable(obj) @add_prefix - def ls(self, directory): + def _ls(self, directory): """List the name of all files under a directory""" return self.g.ls(directory) @add_prefix - def find(self, directory): + def _find(self, directory): """List the name of all files recursively under a directory""" return self.g.find(directory) - def foreach_file(self, directory, action, **kargs): + def _foreach_file(self, directory, action, **kargs): """Perform an action recursively on all files under a directory. The following options are allowed: @@ -187,33 +266,28 @@ class OSBase(object): continue if has_ftype(f, 'd'): - self.foreach_file(full_path, action, **kargs) + self._foreach_file(full_path, action, **kargs) if has_ftype(f, ftype): action(full_path) - def get_metadata(self): - """Returns some descriptive metadata about the OS.""" - meta = {} - meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root) - meta['OSFAMILY'] = self.g.inspect_get_type(self.root) - meta['OS'] = self.g.inspect_get_distro(self.root) - meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root) - - return meta + def _do_collect_metadata(self): + """helper method for collect_metadata""" + self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root) + self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root) + self.meta['OS'] = self.g.inspect_get_distro(self.root) + if self.meta['OS'] == "unknown": + self.meta['OS'] = self.meta['OSFAMILY'] + self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root) + + def _do_mount(self, readonly): + """helper method for mount""" + try: + self.g.mount_options('ro' if readonly else 'rw', self.root, '/') + except RuntimeError as msg: + self.out.warn("unable to mount the root partition: %s" % msg) + return False - def do_sysprep(self): - """Prepere system for image creation.""" - - output('Preparing system for image creation:') - - tasks, _ = self.list_syspreps() - size = len(tasks) - cnt = 0 - for task in tasks: - cnt += 1 - output(('(%d/%d)' % (cnt, size)).ljust(7), False) - task() - output() + return True # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :