Add decorators defining sysprep params
[snf-image-creator] / image_creator / os_type / __init__.py
index d093172..7e6c452 100644 (file)
@@ -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
 # interpreted as representing official policies, either expressed
 # or implied, of GRNET S.A.
 
+"""This package provides various classes for preparing different Operating
+Systems for image creation.
+"""
+
 from image_creator.util import FatalError
 
 import textwrap
 import re
+from collections import namedtuple
+from functools import wraps
 
 
 def os_cls(distro, osfamily):
@@ -60,28 +68,83 @@ def add_prefix(target):
     return wrapper
 
 
-def sysprep(enabled=True):
+def sysprep(message, enabled=True, **kwargs):
     """Decorator for system preparation tasks"""
     def wrapper(func):
         func.sysprep = True
         func.enabled = enabled
         func.executed = False
-        return func
+
+        for key, val in kwargs.items():
+            setattr(func, key, val)
+
+        @wraps(func)
+        def inner(self, print_message=True):
+            if print_message:
+                self.out.output(message)
+            return func(self)
+
+        return inner
+
+    return wrapper
+
+
+def add_sysprep_param(name, descr, maxlen, default=None,
+                      validator=lambda x: True):
+    """Decorator for init that adds the definition for a system preparation
+    parameter
+    """
+    def wrapper(func):
+
+        @wraps(func)
+        def inner(self, *args, **kwargs):
+
+            func(self, *args, **kwargs)
+
+            if not hasattr(self, 'needed_sysprep_params'):
+                self.needed_sysprep_params = {}
+            getattr(self, 'needed_sysprep_params')[name] = \
+                self.SysprepParam(descr, maxlen, validator)
+        return inner
+
+    return wrapper
+
+
+def del_sysprep_param(name):
+    """Decorator for init that deletes a previously added sysprep parameter
+    definition .
+    """
+    def wrapper(func):
+
+        @wraps(func)
+        def inner(self, *args, **kwargs):
+            del self.needed_sysprep_params[nam]
+            func(self, *args, **kwargs)
+
+        return inner
+
     return wrapper
 
 
 class OSBase(object):
     """Basic operating system class"""
 
-    def __init__(self, rootdev, ghandler, output):
-        self.root = rootdev
-        self.g = ghandler
-        self.out = output
+    SysprepParam = namedtuple('SysprepParam', 'description maxlen validator')
+
+    def __init__(self, image, **kargs):
+        self.image = image
+
+        self.root = image.root
+        self.g = image.g
+        self.out = image.out
+
+        self.sysprep_params = \
+            kargs['sysprep_params'] if 'sysprep_params' in kargs else {}
+
         self.meta = {}
 
     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")
@@ -92,29 +155,23 @@ class OSBase(object):
         finally:
             self.umount()
 
-    def _do_collect_metadata(self):
-
-        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 _is_sysprep(self, obj):
-        return getattr(obj, 'sysprep', False) and callable(obj)
+        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('_')]
 
         return [x for x in objs if self._is_sysprep(x) and x.executed is False]
 
     def sysprep_info(self, obj):
+        """Returns information about a sysprep object"""
         assert self._is_sysprep(obj), "Object is not a sysprep"
 
-        return (obj.__name__.replace('_', '-'), textwrap.dedent(obj.__doc__))
+        SysprepInfo = namedtuple("SysprepInfo", "name description")
+
+        return SysprepInfo(obj.__name__.replace('_', '-'),
+                           textwrap.dedent(obj.__doc__))
 
     def get_sysprep_by_name(self, name):
         """Returns the sysprep object with the given name"""
@@ -171,17 +228,86 @@ class OSBase(object):
                 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
                 self.out.output('    %s:\n%s\n' % (name, descr))
 
+    def print_sysprep_params(self):
+        """Print the system preparation parameter the user may use"""
+
+        self.out.output("Needed system preparation parameters:")
+
+        params = self.needed_sysprep_params()
+
+        if len(params) == 0:
+            self.out.output("(none)")
+            return
+
+        for param in params:
+            self.out.output("\t%s (%s): %s" %
+                            (param.description, param.name,
+                             self.sysprep_params[param.name] if param.name in
+                             self.sysprep_params else "(none)"))
+
+    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:
@@ -218,35 +344,22 @@ 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 do_sysprep(self):
-        """Prepere 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)
-            self.out.output()
-        finally:
-            self.umount()
+    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:
@@ -255,25 +368,4 @@ class OSBase(object):
 
         return True
 
-    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("Mount 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.g.umount_all()
-        self.mounted = False
-
 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :