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