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