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
46 def os_cls(distro, osfamily):
47 """Given the distro name and the osfamily, return the appropriate class"""
51 module = __import__("image_creator.os_type.%s" % distro,
52 fromlist=['image_creator.os_type'])
53 classname = distro.capitalize()
55 module = __import__("image_creator.os_type.%s" % osfamily,
56 fromlist=['image_creator.os_type'])
57 classname = osfamily.capitalize()
59 return getattr(module, classname)
62 def add_prefix(target):
63 def wrapper(self, *args):
65 return map(lambda x: prefix + x, target(self, *args))
69 def sysprep(enabled=True):
70 """Decorator for system preparation tasks"""
73 func.enabled = enabled
80 """Basic operating system class"""
82 def __init__(self, rootdev, ghandler, output):
88 def collect_metadata(self):
89 """Collect metadata about the OS"""
91 if not self.mount(readonly=True):
92 raise FatalError("Unable to mount the media read-only")
94 self.out.output('Collecting image metadata ...', False)
95 self._do_collect_metadata()
96 self.out.success('done')
102 def list_syspreps(self):
103 """Returns a list of sysprep objects"""
104 objs = [getattr(self, name) for name in dir(self)
105 if not name.startswith('_')]
107 return [x for x in objs if self._is_sysprep(x) and x.executed is False]
109 def sysprep_info(self, obj):
110 """Returns information about a sysprep object"""
111 assert self._is_sysprep(obj), "Object is not a sysprep"
113 return (obj.__name__.replace('_', '-'), textwrap.dedent(obj.__doc__))
115 def get_sysprep_by_name(self, name):
116 """Returns the sysprep object with the given name"""
117 error_msg = "Syprep operation %s does not exist for %s" % \
118 (name, self.__class__.__name__)
120 method_name = name.replace('-', '_')
123 method = getattr(self, method_name)
124 except AttributeError:
125 raise FatalError(error_msg)
127 if not self._is_sysprep(method):
128 raise FatalError(error_msg)
132 def enable_sysprep(self, obj):
133 """Enable a system preparation operation"""
134 setattr(obj.im_func, 'enabled', True)
136 def disable_sysprep(self, obj):
137 """Disable a system preparation operation"""
138 setattr(obj.im_func, 'enabled', False)
140 def print_syspreps(self):
141 """Print enabled and disabled system preparation operations."""
143 syspreps = self.list_syspreps()
144 enabled = filter(lambda x: x.enabled, syspreps)
145 disabled = filter(lambda x: not x.enabled, syspreps)
147 wrapper = textwrap.TextWrapper()
148 wrapper.subsequent_indent = '\t'
149 wrapper.initial_indent = '\t'
152 self.out.output("Enabled system preparation operations:")
153 if len(enabled) == 0:
154 self.out.output("(none)")
156 for sysprep in enabled:
157 name = sysprep.__name__.replace('_', '-')
158 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
159 self.out.output(' %s:\n%s\n' % (name, descr))
161 self.out.output("Disabled system preparation operations:")
162 if len(disabled) == 0:
163 self.out.output("(none)")
165 for sysprep in disabled:
166 name = sysprep.__name__.replace('_', '-')
167 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
168 self.out.output(' %s:\n%s\n' % (name, descr))
170 def do_sysprep(self):
171 """Prepare system for image creation."""
174 if not self.mount(readonly=False):
175 raise FatalError("Unable to mount the media read-write")
177 self.out.output('Preparing system for image creation:')
179 tasks = self.list_syspreps()
180 enabled = filter(lambda x: x.enabled, tasks)
186 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
188 setattr(task.im_func, 'executed', True)
194 def mount(self, readonly=False):
197 if getattr(self, "mounted", False):
200 mount_type = 'read-only' if readonly else 'read-write'
201 self.out.output("Mounting the media %s ..." % mount_type, False)
203 if not self._do_mount(readonly):
207 self.out.success('done')
211 """Umount all mounted filesystems."""
213 self.out.output("Umounting the media ...", False)
216 self.out.success('done')
218 def _is_sysprep(self, obj):
219 """Checks if an object is a sysprep"""
220 return getattr(obj, 'sysprep', False) and callable(obj)
223 def _ls(self, directory):
224 """List the name of all files under a directory"""
225 return self.g.ls(directory)
228 def _find(self, directory):
229 """List the name of all files recursively under a directory"""
230 return self.g.find(directory)
232 def _foreach_file(self, directory, action, **kargs):
233 """Perform an action recursively on all files under a directory.
235 The following options are allowed:
237 * maxdepth: If defined the action will not be performed on
238 files that are below this level of directories under the
241 * ftype: The action will only be performed on files of this
242 type. For a list of all allowed filetypes, see here:
243 http://libguestfs.org/guestfs.3.html#guestfs_readdir
245 * exclude: Exclude all files that follow this pattern.
247 maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
252 maxdepth = None if maxdepth is None else maxdepth - 1
253 kargs['maxdepth'] = maxdepth
255 exclude = None if 'exclude' not in kargs else kargs['exclude']
256 ftype = None if 'ftype' not in kargs else kargs['ftype']
257 has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
259 for f in self.g.readdir(directory):
260 if f['name'] in ('.', '..'):
263 full_path = "%s/%s" % (directory, f['name'])
265 if exclude and re.match(exclude, full_path):
268 if has_ftype(f, 'd'):
269 self._foreach_file(full_path, action, **kargs)
271 if has_ftype(f, ftype):
274 def _do_collect_metadata(self):
275 """helper method for collect_metadata"""
276 self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
277 self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
278 self.meta['OS'] = self.g.inspect_get_distro(self.root)
279 if self.meta['OS'] == "unknown":
280 self.meta['OS'] = self.meta['OSFAMILY']
281 self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
283 def _do_mount(self, readonly):
284 """helper method for mount"""
286 self.g.mount_options('ro' if readonly else 'rw', self.root, '/')
287 except RuntimeError as msg:
288 self.out.warn("unable to mount the root partition: %s" % msg)
293 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :