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