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 map(lambda x: prefix + x, target(self, *args))
71 def sysprep(message, enabled=True, **kwargs):
72 """Decorator for system preparation tasks"""
75 func.enabled = enabled
78 for key, val in kwargs.items():
79 setattr(func, key, val)
82 def wrapper2(self, print_message=True):
84 self.out.output(message)
93 """Basic operating system class"""
95 SysprepParam = namedtuple('SysprepParam',
96 'name description length validator')
98 def __init__(self, image, **kargs):
101 self.root = image.root
105 self.sysprep_params = \
106 kargs['sysprep_params'] if 'sysprep_params' in kargs else {}
110 def collect_metadata(self):
111 """Collect metadata about the OS"""
113 if not self.mount(readonly=True):
114 raise FatalError("Unable to mount the media read-only")
116 self.out.output('Collecting image metadata ...', False)
117 self._do_collect_metadata()
118 self.out.success('done')
124 def needed_sysprep_params(self):
125 """Returns a list of needed sysprep parameters. Each element in the
126 list is a SysprepParam object.
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('_')]
135 return [x for x in objs if self._is_sysprep(x) and x.executed is False]
137 def sysprep_info(self, obj):
138 """Returns information about a sysprep object"""
139 assert self._is_sysprep(obj), "Object is not a sysprep"
141 return (obj.__name__.replace('_', '-'), textwrap.dedent(obj.__doc__))
143 def get_sysprep_by_name(self, name):
144 """Returns the sysprep object with the given name"""
145 error_msg = "Syprep operation %s does not exist for %s" % \
146 (name, self.__class__.__name__)
148 method_name = name.replace('-', '_')
151 method = getattr(self, method_name)
152 except AttributeError:
153 raise FatalError(error_msg)
155 if not self._is_sysprep(method):
156 raise FatalError(error_msg)
160 def enable_sysprep(self, obj):
161 """Enable a system preparation operation"""
162 setattr(obj.im_func, 'enabled', True)
164 def disable_sysprep(self, obj):
165 """Disable a system preparation operation"""
166 setattr(obj.im_func, 'enabled', False)
168 def print_syspreps(self):
169 """Print enabled and disabled system preparation operations."""
171 syspreps = self.list_syspreps()
172 enabled = filter(lambda x: x.enabled, syspreps)
173 disabled = filter(lambda x: not x.enabled, syspreps)
175 wrapper = textwrap.TextWrapper()
176 wrapper.subsequent_indent = '\t'
177 wrapper.initial_indent = '\t'
180 self.out.output("Enabled system preparation operations:")
181 if len(enabled) == 0:
182 self.out.output("(none)")
184 for sysprep in enabled:
185 name = sysprep.__name__.replace('_', '-')
186 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
187 self.out.output(' %s:\n%s\n' % (name, descr))
189 self.out.output("Disabled system preparation operations:")
190 if len(disabled) == 0:
191 self.out.output("(none)")
193 for sysprep in disabled:
194 name = sysprep.__name__.replace('_', '-')
195 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
196 self.out.output(' %s:\n%s\n' % (name, descr))
198 def print_sysprep_params(self):
199 """Print the system preparation parameter the user may use"""
201 self.out.output("Needed system preparation parameters:")
203 params = self.needed_sysprep_params()
206 self.out.output("(none)")
210 self.out.output("\t%s (%s): %s" %
211 (param.description, param.name,
212 self.sysprep_params[param.name] if param.name in
213 self.sysprep_params else "(none)"))
215 def do_sysprep(self):
216 """Prepare system for image creation."""
219 if not self.mount(readonly=False):
220 raise FatalError("Unable to mount the media read-write")
222 self.out.output('Preparing system for image creation:')
224 tasks = self.list_syspreps()
225 enabled = filter(lambda x: x.enabled, tasks)
231 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
233 setattr(task.im_func, 'executed', True)
239 def mount(self, readonly=False):
242 if getattr(self, "mounted", False):
245 mount_type = 'read-only' if readonly else 'read-write'
246 self.out.output("Mounting the media %s ..." % mount_type, False)
248 if not self._do_mount(readonly):
252 self.out.success('done')
256 """Umount all mounted filesystems."""
258 self.out.output("Umounting the media ...", False)
261 self.out.success('done')
263 def _is_sysprep(self, obj):
264 """Checks if an object is a sysprep"""
265 return getattr(obj, 'sysprep', False) and callable(obj)
268 def _ls(self, directory):
269 """List the name of all files under a directory"""
270 return self.g.ls(directory)
273 def _find(self, directory):
274 """List the name of all files recursively under a directory"""
275 return self.g.find(directory)
277 def _foreach_file(self, directory, action, **kargs):
278 """Perform an action recursively on all files under a directory.
280 The following options are allowed:
282 * maxdepth: If defined the action will not be performed on
283 files that are below this level of directories under the
286 * ftype: The action will only be performed on files of this
287 type. For a list of all allowed filetypes, see here:
288 http://libguestfs.org/guestfs.3.html#guestfs_readdir
290 * exclude: Exclude all files that follow this pattern.
292 maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
297 maxdepth = None if maxdepth is None else maxdepth - 1
298 kargs['maxdepth'] = maxdepth
300 exclude = None if 'exclude' not in kargs else kargs['exclude']
301 ftype = None if 'ftype' not in kargs else kargs['ftype']
302 has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
304 for f in self.g.readdir(directory):
305 if f['name'] in ('.', '..'):
308 full_path = "%s/%s" % (directory, f['name'])
310 if exclude and re.match(exclude, full_path):
313 if has_ftype(f, 'd'):
314 self._foreach_file(full_path, action, **kargs)
316 if has_ftype(f, ftype):
319 def _do_collect_metadata(self):
320 """helper method for collect_metadata"""
321 self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
322 self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
323 self.meta['OS'] = self.g.inspect_get_distro(self.root)
324 if self.meta['OS'] == "unknown":
325 self.meta['OS'] = self.meta['OSFAMILY']
326 self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
328 def _do_mount(self, readonly):
329 """helper method for mount"""
331 self.g.mount_options('ro' if readonly else 'rw', self.root, '/')
332 except RuntimeError as msg:
333 self.out.warn("unable to mount the root partition: %s" % msg)
338 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :