Merge branch 'hotfix-0.4.4' into develop
[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     """Decorator that adds a prefix to the result of a function"""
66     def wrapper(self, *args):
67         prefix = args[0]
68         return [prefix + path for path in target(self, *args)]
69     return wrapper
70
71
72 def sysprep(message, enabled=True, **kwargs):
73     """Decorator for system preparation tasks"""
74     def wrapper(method):
75         method.sysprep = True
76         method.enabled = enabled
77         method.executed = False
78
79         for key, val in kwargs.items():
80             setattr(method, key, val)
81
82         @wraps(method)
83         def inner(self, print_message=True):
84             if print_message:
85                 self.out.output(message)
86             return method(self)
87
88         return inner
89     return wrapper
90
91
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
95     """
96     def wrapper(init):
97         @wraps(init)
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
104         return inner
105     return wrapper
106
107
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.
111     """
112     def wrapper(func):
113         @wraps(func)
114         def inner(self, *args, **kwargs):
115             del self.needed_sysprep_params[name]
116             func(self, *args, **kwargs)
117         return inner
118     return wrapper
119
120
121 class OSBase(object):
122     """Basic operating system class"""
123
124     SysprepParam = namedtuple('SysprepParam',
125                               ['type', 'default', 'description', 'validate'])
126
127     def __init__(self, image, **kargs):
128         self.image = image
129
130         self.root = image.root
131         self.g = image.g
132         self.out = image.out
133
134         self.needed_sysprep_params = {}
135         self.sysprep_params = \
136             kargs['sysprep_params'] if 'sysprep_params' in kargs else {}
137
138         self.meta = {}
139         self.mounted = False
140
141         # Many guestfs compilations don't support scrub
142         self._scrub_support = True
143         try:
144             self.g.available(['scrub'])
145         except RuntimeError:
146             self._scrub_support = False
147
148     def collect_metadata(self):
149         """Collect metadata about the OS"""
150         try:
151             if not self.mount(readonly=True):
152                 raise FatalError("Unable to mount the media read-only")
153
154             self.out.output('Collecting image metadata ...', False)
155             self._do_collect_metadata()
156             self.out.success('done')
157         finally:
158             self.umount()
159
160         self.out.output()
161
162     def list_syspreps(self):
163         """Returns a list of sysprep objects"""
164         objs = [getattr(self, name) for name in dir(self)
165                 if not name.startswith('_')]
166
167         return [x for x in objs if self._is_sysprep(x) and x.executed is False]
168
169     def sysprep_info(self, obj):
170         """Returns information about a sysprep object"""
171         assert self._is_sysprep(obj), "Object is not a sysprep"
172
173         SysprepInfo = namedtuple("SysprepInfo", "name description")
174
175         return SysprepInfo(obj.__name__.replace('_', '-'),
176                            textwrap.dedent(obj.__doc__))
177
178     def get_sysprep_by_name(self, name):
179         """Returns the sysprep object with the given name"""
180         error_msg = "Syprep operation %s does not exist for %s" % \
181                     (name, self.__class__.__name__)
182
183         method_name = name.replace('-', '_')
184         method = None
185         try:
186             method = getattr(self, method_name)
187         except AttributeError:
188             raise FatalError(error_msg)
189
190         if not self._is_sysprep(method):
191             raise FatalError(error_msg)
192
193         return method
194
195     def enable_sysprep(self, obj):
196         """Enable a system preparation operation"""
197         setattr(obj.im_func, 'enabled', True)
198
199     def disable_sysprep(self, obj):
200         """Disable a system preparation operation"""
201         setattr(obj.im_func, 'enabled', False)
202
203     def print_syspreps(self):
204         """Print enabled and disabled system preparation operations."""
205
206         syspreps = self.list_syspreps()
207         enabled = [sysprep for sysprep in syspreps if sysprep.enabled]
208         disabled = [sysprep for sysprep in syspreps if not sysprep.enabled]
209
210         wrapper = textwrap.TextWrapper()
211         wrapper.subsequent_indent = '\t'
212         wrapper.initial_indent = '\t'
213         wrapper.width = 72
214
215         self.out.output("Enabled system preparation operations:")
216         if len(enabled) == 0:
217             self.out.output("(none)")
218         else:
219             for sysprep in enabled:
220                 name = sysprep.__name__.replace('_', '-')
221                 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
222                 self.out.output('    %s:\n%s\n' % (name, descr))
223
224         self.out.output("Disabled system preparation operations:")
225         if len(disabled) == 0:
226             self.out.output("(none)")
227         else:
228             for sysprep in disabled:
229                 name = sysprep.__name__.replace('_', '-')
230                 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
231                 self.out.output('    %s:\n%s\n' % (name, descr))
232
233     def print_sysprep_params(self):
234         """Print the system preparation parameter the user may use"""
235
236         self.out.output("Needed system preparation parameters:")
237
238         if len(self.needed_sysprep_params) == 0:
239             self.out.output("(none)")
240             return
241
242         for name, param in self.needed_sysprep_params.items():
243             self.out.output("\t%s (%s): %s" %
244                             (param.description, name,
245                              self.sysprep_params[name] if name in
246                              self.sysprep_params else "(none)"))
247
248     def do_sysprep(self):
249         """Prepare system for image creation."""
250
251         try:
252             if not self.mount(readonly=False):
253                 raise FatalError("Unable to mount the media read-write")
254
255             self.out.output('Preparing system for image creation:')
256
257             enabled = [task for task in self.list_syspreps() if task.enabled]
258
259             size = len(enabled)
260             cnt = 0
261             for task in enabled:
262                 cnt += 1
263                 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
264                 task()
265                 setattr(task.im_func, 'executed', True)
266         finally:
267             self.umount()
268
269         self.out.output()
270
271     def mount(self, readonly=False):
272         """Mount image."""
273
274         if getattr(self, "mounted", False):
275             return True
276
277         mount_type = 'read-only' if readonly else 'read-write'
278         self.out.output("Mounting the media %s ..." % mount_type, False)
279
280         if not self._do_mount(readonly):
281             return False
282
283         self.mounted = True
284         self.out.success('done')
285         return True
286
287     def umount(self):
288         """Umount all mounted filesystems."""
289
290         self.out.output("Umounting the media ...", False)
291         self.g.umount_all()
292         self.mounted = False
293         self.out.success('done')
294
295     def _is_sysprep(self, obj):
296         """Checks if an object is a sysprep"""
297         return getattr(obj, 'sysprep', False) and callable(obj)
298
299     @add_prefix
300     def _ls(self, directory):
301         """List the name of all files under a directory"""
302         return self.g.ls(directory)
303
304     @add_prefix
305     def _find(self, directory):
306         """List the name of all files recursively under a directory"""
307         return self.g.find(directory)
308
309     def _foreach_file(self, directory, action, **kargs):
310         """Perform an action recursively on all files under a directory.
311
312         The following options are allowed:
313
314         * maxdepth: If defined the action will not be performed on
315           files that are below this level of directories under the
316           directory parameter.
317
318         * ftype: The action will only be performed on files of this
319           type. For a list of all allowed filetypes, see here:
320           http://libguestfs.org/guestfs.3.html#guestfs_readdir
321
322         * exclude: Exclude all files that follow this pattern.
323         """
324         maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
325         if maxdepth == 0:
326             return
327
328         # maxdepth -= 1
329         maxdepth = None if maxdepth is None else maxdepth - 1
330         kargs['maxdepth'] = maxdepth
331
332         exclude = None if 'exclude' not in kargs else kargs['exclude']
333         ftype = None if 'ftype' not in kargs else kargs['ftype']
334         has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
335
336         for f in self.g.readdir(directory):
337             if f['name'] in ('.', '..'):
338                 continue
339
340             full_path = "%s/%s" % (directory, f['name'])
341
342             if exclude and re.match(exclude, full_path):
343                 continue
344
345             if has_ftype(f, 'd'):
346                 self._foreach_file(full_path, action, **kargs)
347
348             if has_ftype(f, ftype):
349                 action(full_path)
350
351     def _do_collect_metadata(self):
352         """helper method for collect_metadata"""
353         self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
354         self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
355         self.meta['OS'] = self.g.inspect_get_distro(self.root)
356         if self.meta['OS'] == "unknown":
357             self.meta['OS'] = self.meta['OSFAMILY']
358         self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
359
360     def _do_mount(self, readonly):
361         """helper method for mount"""
362         try:
363             self.g.mount_options('ro' if readonly else 'rw', self.root, '/')
364         except RuntimeError as msg:
365             self.out.warn("unable to mount the root partition: %s" % msg)
366             return False
367
368         return True
369
370 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :