Add type field in the SysprepParam namedtuple
[snf-image-creator] / image_creator / os_type / __init__.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2012 GRNET S.A. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
7 # conditions are met:
8 #
9 #   1. Redistributions of source code must retain the above
10 #      copyright notice, this list of conditions and the following
11 #      disclaimer.
12 #
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.
17 #
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.
30 #
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.
35
36 """This package provides various classes for preparing different Operating
37 Systems for image creation.
38 """
39
40 from image_creator.util import FatalError
41
42 import textwrap
43 import re
44 from collections import namedtuple
45 from functools import wraps
46
47
48 def os_cls(distro, osfamily):
49     """Given the distro name and the osfamily, return the appropriate class"""
50     module = None
51     classname = None
52     try:
53         module = __import__("image_creator.os_type.%s" % distro,
54                             fromlist=['image_creator.os_type'])
55         classname = distro.capitalize()
56     except ImportError:
57         module = __import__("image_creator.os_type.%s" % osfamily,
58                             fromlist=['image_creator.os_type'])
59         classname = osfamily.capitalize()
60
61     return getattr(module, classname)
62
63
64 def add_prefix(target):
65     def wrapper(self, *args):
66         prefix = args[0]
67         return [prefix + path for path in target(self, *args)]
68     return wrapper
69
70
71 def sysprep(message, enabled=True, **kwargs):
72     """Decorator for system preparation tasks"""
73     def wrapper(method):
74         method.sysprep = True
75         method.enabled = enabled
76         method.executed = False
77
78         for key, val in kwargs.items():
79             setattr(method, key, val)
80
81         @wraps(method)
82         def inner(self, print_message=True):
83             if print_message:
84                 self.out.output(message)
85             return method(self)
86
87         return inner
88     return wrapper
89
90
91 def add_sysprep_param(name, type, default, descr, validate=lambda x: True):
92     """Decorator for __init__ that adds the definition for a system preparation
93     parameter in an instance of a os_type class
94     """
95     def wrapper(init):
96         @wraps(init)
97         def inner(self, *args, **kwargs):
98             init(self, *args, **kwargs)
99             self.needed_sysprep_params[name] = \
100                 self.SysprepParam(type, default, descr, validate)
101         return inner
102     return wrapper
103
104
105 def del_sysprep_param(name):
106     """Decorator for __init__ that deletes a previously added sysprep parameter
107     definition from an instance of a os_type class.
108     """
109     def wrapper(func):
110         @wraps(func)
111         def inner(self, *args, **kwargs):
112             del self.needed_sysprep_params[name]
113             func(self, *args, **kwargs)
114         return inner
115     return wrapper
116
117
118 class OSBase(object):
119     """Basic operating system class"""
120
121     SysprepParam = namedtuple('SysprepParam',
122                               ['type', 'default', 'description', 'validate'])
123
124     def __init__(self, image, **kargs):
125         self.image = image
126
127         self.root = image.root
128         self.g = image.g
129         self.out = image.out
130
131         self.needed_sysprep_params = {}
132         self.sysprep_params = \
133             kargs['sysprep_params'] if 'sysprep_params' in kargs else {}
134
135         self.meta = {}
136         self.mounted = False
137
138     def collect_metadata(self):
139         """Collect metadata about the OS"""
140         try:
141             if not self.mount(readonly=True):
142                 raise FatalError("Unable to mount the media read-only")
143
144             self.out.output('Collecting image metadata ...', False)
145             self._do_collect_metadata()
146             self.out.success('done')
147         finally:
148             self.umount()
149
150         self.out.output()
151
152     def list_syspreps(self):
153         """Returns a list of sysprep objects"""
154         objs = [getattr(self, name) for name in dir(self)
155                 if not name.startswith('_')]
156
157         return [x for x in objs if self._is_sysprep(x) and x.executed is False]
158
159     def sysprep_info(self, obj):
160         """Returns information about a sysprep object"""
161         assert self._is_sysprep(obj), "Object is not a sysprep"
162
163         SysprepInfo = namedtuple("SysprepInfo", "name description")
164
165         return SysprepInfo(obj.__name__.replace('_', '-'),
166                            textwrap.dedent(obj.__doc__))
167
168     def get_sysprep_by_name(self, name):
169         """Returns the sysprep object with the given name"""
170         error_msg = "Syprep operation %s does not exist for %s" % \
171                     (name, self.__class__.__name__)
172
173         method_name = name.replace('-', '_')
174         method = None
175         try:
176             method = getattr(self, method_name)
177         except AttributeError:
178             raise FatalError(error_msg)
179
180         if not self._is_sysprep(method):
181             raise FatalError(error_msg)
182
183         return method
184
185     def enable_sysprep(self, obj):
186         """Enable a system preparation operation"""
187         setattr(obj.im_func, 'enabled', True)
188
189     def disable_sysprep(self, obj):
190         """Disable a system preparation operation"""
191         setattr(obj.im_func, 'enabled', False)
192
193     def print_syspreps(self):
194         """Print enabled and disabled system preparation operations."""
195
196         syspreps = self.list_syspreps()
197         enabled = [sysprep for sysprep in syspreps if sysprep.enabled]
198         disabled = [sysprep for sysprep in syspreps if not sysprep.enabled]
199
200         wrapper = textwrap.TextWrapper()
201         wrapper.subsequent_indent = '\t'
202         wrapper.initial_indent = '\t'
203         wrapper.width = 72
204
205         self.out.output("Enabled system preparation operations:")
206         if len(enabled) == 0:
207             self.out.output("(none)")
208         else:
209             for sysprep in enabled:
210                 name = sysprep.__name__.replace('_', '-')
211                 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
212                 self.out.output('    %s:\n%s\n' % (name, descr))
213
214         self.out.output("Disabled system preparation operations:")
215         if len(disabled) == 0:
216             self.out.output("(none)")
217         else:
218             for sysprep in disabled:
219                 name = sysprep.__name__.replace('_', '-')
220                 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
221                 self.out.output('    %s:\n%s\n' % (name, descr))
222
223     def print_sysprep_params(self):
224         """Print the system preparation parameter the user may use"""
225
226         self.out.output("Needed system preparation parameters:")
227
228         if len(self.needed_sysprep_params) == 0:
229             self.out.output("(none)")
230             return
231
232         for name, param in self.needed_sysprep_params.items():
233             self.out.output("\t%s (%s): %s" %
234                             (param.description, name,
235                              self.sysprep_params[name] if name in
236                              self.sysprep_params else "(none)"))
237
238     def do_sysprep(self):
239         """Prepare system for image creation."""
240
241         try:
242             if not self.mount(readonly=False):
243                 raise FatalError("Unable to mount the media read-write")
244
245             self.out.output('Preparing system for image creation:')
246
247             enabled = [task for task in self.list_syspreps() if task.enabled]
248
249             size = len(enabled)
250             cnt = 0
251             for task in enabled:
252                 cnt += 1
253                 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
254                 task()
255                 setattr(task.im_func, 'executed', True)
256         finally:
257             self.umount()
258
259         self.out.output()
260
261     def mount(self, readonly=False):
262         """Mount image."""
263
264         if getattr(self, "mounted", False):
265             return True
266
267         mount_type = 'read-only' if readonly else 'read-write'
268         self.out.output("Mounting the media %s ..." % mount_type, False)
269
270         if not self._do_mount(readonly):
271             return False
272
273         self.mounted = True
274         self.out.success('done')
275         return True
276
277     def umount(self):
278         """Umount all mounted filesystems."""
279
280         self.out.output("Umounting the media ...", False)
281         self.g.umount_all()
282         self.mounted = False
283         self.out.success('done')
284
285     def _is_sysprep(self, obj):
286         """Checks if an object is a sysprep"""
287         return getattr(obj, 'sysprep', False) and callable(obj)
288
289     @add_prefix
290     def _ls(self, directory):
291         """List the name of all files under a directory"""
292         return self.g.ls(directory)
293
294     @add_prefix
295     def _find(self, directory):
296         """List the name of all files recursively under a directory"""
297         return self.g.find(directory)
298
299     def _foreach_file(self, directory, action, **kargs):
300         """Perform an action recursively on all files under a directory.
301
302         The following options are allowed:
303
304         * maxdepth: If defined the action will not be performed on
305           files that are below this level of directories under the
306           directory parameter.
307
308         * ftype: The action will only be performed on files of this
309           type. For a list of all allowed filetypes, see here:
310           http://libguestfs.org/guestfs.3.html#guestfs_readdir
311
312         * exclude: Exclude all files that follow this pattern.
313         """
314         maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
315         if maxdepth == 0:
316             return
317
318         # maxdepth -= 1
319         maxdepth = None if maxdepth is None else maxdepth - 1
320         kargs['maxdepth'] = maxdepth
321
322         exclude = None if 'exclude' not in kargs else kargs['exclude']
323         ftype = None if 'ftype' not in kargs else kargs['ftype']
324         has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
325
326         for f in self.g.readdir(directory):
327             if f['name'] in ('.', '..'):
328                 continue
329
330             full_path = "%s/%s" % (directory, f['name'])
331
332             if exclude and re.match(exclude, full_path):
333                 continue
334
335             if has_ftype(f, 'd'):
336                 self._foreach_file(full_path, action, **kargs)
337
338             if has_ftype(f, ftype):
339                 action(full_path)
340
341     def _do_collect_metadata(self):
342         """helper method for collect_metadata"""
343         self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
344         self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
345         self.meta['OS'] = self.g.inspect_get_distro(self.root)
346         if self.meta['OS'] == "unknown":
347             self.meta['OS'] = self.meta['OSFAMILY']
348         self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
349
350     def _do_mount(self, readonly):
351         """helper method for mount"""
352         try:
353             self.g.mount_options('ro' if readonly else 'rw', self.root, '/')
354         except RuntimeError as msg:
355             self.out.warn("unable to mount the root partition: %s" % msg)
356             return False
357
358         return True
359
360 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :