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