1 # -*- coding: utf-8 -*-
3 # Copyright 2012 GRNET S.A. All rights reserved.
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
9 # 1. Redistributions of source code must retain the above
10 # copyright notice, this list of conditions and the following
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.
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.
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.
36 """This package provides various classes for preparing different Operating
37 Systems for image creation.
40 from image_creator.util import FatalError
44 from collections import namedtuple
45 from functools import wraps
48 def os_cls(distro, osfamily):
49 """Given the distro name and the osfamily, return the appropriate class"""
53 module = __import__("image_creator.os_type.%s" % distro,
54 fromlist=['image_creator.os_type'])
55 classname = distro.capitalize()
57 module = __import__("image_creator.os_type.%s" % osfamily,
58 fromlist=['image_creator.os_type'])
59 classname = osfamily.capitalize()
61 return getattr(module, classname)
64 def add_prefix(target):
65 def wrapper(self, *args):
67 return [prefix + path for path in target(self, *args)]
71 def sysprep(message, enabled=True, **kwargs):
72 """Decorator for system preparation tasks"""
75 method.enabled = enabled
76 method.executed = False
78 for key, val in kwargs.items():
79 setattr(method, key, val)
82 def inner(self, print_message=True):
84 self.out.output(message)
91 def add_sysprep_param(name, type, default, descr, validate=lambda x: True):
92 """Decorator for __init__ that adds the definition for a system preparation
93 parameter in an instance of a os_type class
97 def inner(self, *args, **kwargs):
98 init(self, *args, **kwargs)
99 self.needed_sysprep_params[name] = \
100 self.SysprepParam(type, default, descr, validate)
105 def del_sysprep_param(name):
106 """Decorator for __init__ that deletes a previously added sysprep parameter
107 definition from an instance of a os_type class.
111 def inner(self, *args, **kwargs):
112 del self.needed_sysprep_params[name]
113 func(self, *args, **kwargs)
118 class OSBase(object):
119 """Basic operating system class"""
121 SysprepParam = namedtuple('SysprepParam',
122 ['type', 'default', 'description', 'validate'])
124 def __init__(self, image, **kargs):
127 self.root = image.root
131 self.needed_sysprep_params = {}
132 self.sysprep_params = \
133 kargs['sysprep_params'] if 'sysprep_params' in kargs else {}
138 def collect_metadata(self):
139 """Collect metadata about the OS"""
141 if not self.mount(readonly=True):
142 raise FatalError("Unable to mount the media read-only")
144 self.out.output('Collecting image metadata ...', False)
145 self._do_collect_metadata()
146 self.out.success('done')
152 def list_syspreps(self):
153 """Returns a list of sysprep objects"""
154 objs = [getattr(self, name) for name in dir(self)
155 if not name.startswith('_')]
157 return [x for x in objs if self._is_sysprep(x) and x.executed is False]
159 def sysprep_info(self, obj):
160 """Returns information about a sysprep object"""
161 assert self._is_sysprep(obj), "Object is not a sysprep"
163 SysprepInfo = namedtuple("SysprepInfo", "name description")
165 return SysprepInfo(obj.__name__.replace('_', '-'),
166 textwrap.dedent(obj.__doc__))
168 def get_sysprep_by_name(self, name):
169 """Returns the sysprep object with the given name"""
170 error_msg = "Syprep operation %s does not exist for %s" % \
171 (name, self.__class__.__name__)
173 method_name = name.replace('-', '_')
176 method = getattr(self, method_name)
177 except AttributeError:
178 raise FatalError(error_msg)
180 if not self._is_sysprep(method):
181 raise FatalError(error_msg)
185 def enable_sysprep(self, obj):
186 """Enable a system preparation operation"""
187 setattr(obj.im_func, 'enabled', True)
189 def disable_sysprep(self, obj):
190 """Disable a system preparation operation"""
191 setattr(obj.im_func, 'enabled', False)
193 def print_syspreps(self):
194 """Print enabled and disabled system preparation operations."""
196 syspreps = self.list_syspreps()
197 enabled = [sysprep for sysprep in syspreps if sysprep.enabled]
198 disabled = [sysprep for sysprep in syspreps if not sysprep.enabled]
200 wrapper = textwrap.TextWrapper()
201 wrapper.subsequent_indent = '\t'
202 wrapper.initial_indent = '\t'
205 self.out.output("Enabled system preparation operations:")
206 if len(enabled) == 0:
207 self.out.output("(none)")
209 for sysprep in enabled:
210 name = sysprep.__name__.replace('_', '-')
211 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
212 self.out.output(' %s:\n%s\n' % (name, descr))
214 self.out.output("Disabled system preparation operations:")
215 if len(disabled) == 0:
216 self.out.output("(none)")
218 for sysprep in disabled:
219 name = sysprep.__name__.replace('_', '-')
220 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
221 self.out.output(' %s:\n%s\n' % (name, descr))
223 def print_sysprep_params(self):
224 """Print the system preparation parameter the user may use"""
226 self.out.output("Needed system preparation parameters:")
228 if len(self.needed_sysprep_params) == 0:
229 self.out.output("(none)")
232 for name, param in self.needed_sysprep_params.items():
233 self.out.output("\t%s (%s): %s" %
234 (param.description, name,
235 self.sysprep_params[name] if name in
236 self.sysprep_params else "(none)"))
238 def do_sysprep(self):
239 """Prepare system for image creation."""
242 if not self.mount(readonly=False):
243 raise FatalError("Unable to mount the media read-write")
245 self.out.output('Preparing system for image creation:')
247 enabled = [task for task in self.list_syspreps() if task.enabled]
253 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
255 setattr(task.im_func, 'executed', True)
261 def mount(self, readonly=False):
264 if getattr(self, "mounted", False):
267 mount_type = 'read-only' if readonly else 'read-write'
268 self.out.output("Mounting the media %s ..." % mount_type, False)
270 if not self._do_mount(readonly):
274 self.out.success('done')
278 """Umount all mounted filesystems."""
280 self.out.output("Umounting the media ...", False)
283 self.out.success('done')
285 def _is_sysprep(self, obj):
286 """Checks if an object is a sysprep"""
287 return getattr(obj, 'sysprep', False) and callable(obj)
290 def _ls(self, directory):
291 """List the name of all files under a directory"""
292 return self.g.ls(directory)
295 def _find(self, directory):
296 """List the name of all files recursively under a directory"""
297 return self.g.find(directory)
299 def _foreach_file(self, directory, action, **kargs):
300 """Perform an action recursively on all files under a directory.
302 The following options are allowed:
304 * maxdepth: If defined the action will not be performed on
305 files that are below this level of directories under the
308 * ftype: The action will only be performed on files of this
309 type. For a list of all allowed filetypes, see here:
310 http://libguestfs.org/guestfs.3.html#guestfs_readdir
312 * exclude: Exclude all files that follow this pattern.
314 maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
319 maxdepth = None if maxdepth is None else maxdepth - 1
320 kargs['maxdepth'] = maxdepth
322 exclude = None if 'exclude' not in kargs else kargs['exclude']
323 ftype = None if 'ftype' not in kargs else kargs['ftype']
324 has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
326 for f in self.g.readdir(directory):
327 if f['name'] in ('.', '..'):
330 full_path = "%s/%s" % (directory, f['name'])
332 if exclude and re.match(exclude, full_path):
335 if has_ftype(f, 'd'):
336 self._foreach_file(full_path, action, **kargs)
338 if has_ftype(f, ftype):
341 def _do_collect_metadata(self):
342 """helper method for collect_metadata"""
343 self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
344 self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
345 self.meta['OS'] = self.g.inspect_get_distro(self.root)
346 if self.meta['OS'] == "unknown":
347 self.meta['OS'] = self.meta['OSFAMILY']
348 self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
350 def _do_mount(self, readonly):
351 """helper method for mount"""
353 self.g.mount_options('ro' if readonly else 'rw', self.root, '/')
354 except RuntimeError as msg:
355 self.out.warn("unable to mount the root partition: %s" % msg)
360 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :