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, image):
85 self.root = image.root
91 def collect_metadata(self):
92 """Collect metadata about the OS"""
94 if not self.mount(readonly=True):
95 raise FatalError("Unable to mount the media read-only")
97 self.out.output('Collecting image metadata ...', False)
98 self._do_collect_metadata()
99 self.out.success('done')
105 def list_syspreps(self):
106 """Returns a list of sysprep objects"""
107 objs = [getattr(self, name) for name in dir(self)
108 if not name.startswith('_')]
110 return [x for x in objs if self._is_sysprep(x) and x.executed is False]
112 def sysprep_info(self, obj):
113 """Returns information about a sysprep object"""
114 assert self._is_sysprep(obj), "Object is not a sysprep"
116 return (obj.__name__.replace('_', '-'), textwrap.dedent(obj.__doc__))
118 def get_sysprep_by_name(self, name):
119 """Returns the sysprep object with the given name"""
120 error_msg = "Syprep operation %s does not exist for %s" % \
121 (name, self.__class__.__name__)
123 method_name = name.replace('-', '_')
126 method = getattr(self, method_name)
127 except AttributeError:
128 raise FatalError(error_msg)
130 if not self._is_sysprep(method):
131 raise FatalError(error_msg)
135 def enable_sysprep(self, obj):
136 """Enable a system preparation operation"""
137 setattr(obj.im_func, 'enabled', True)
139 def disable_sysprep(self, obj):
140 """Disable a system preparation operation"""
141 setattr(obj.im_func, 'enabled', False)
143 def print_syspreps(self):
144 """Print enabled and disabled system preparation operations."""
146 syspreps = self.list_syspreps()
147 enabled = filter(lambda x: x.enabled, syspreps)
148 disabled = filter(lambda x: not x.enabled, syspreps)
150 wrapper = textwrap.TextWrapper()
151 wrapper.subsequent_indent = '\t'
152 wrapper.initial_indent = '\t'
155 self.out.output("Enabled system preparation operations:")
156 if len(enabled) == 0:
157 self.out.output("(none)")
159 for sysprep in enabled:
160 name = sysprep.__name__.replace('_', '-')
161 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
162 self.out.output(' %s:\n%s\n' % (name, descr))
164 self.out.output("Disabled system preparation operations:")
165 if len(disabled) == 0:
166 self.out.output("(none)")
168 for sysprep in disabled:
169 name = sysprep.__name__.replace('_', '-')
170 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
171 self.out.output(' %s:\n%s\n' % (name, descr))
173 def do_sysprep(self):
174 """Prepare system for image creation."""
177 if not self.mount(readonly=False):
178 raise FatalError("Unable to mount the media read-write")
180 self.out.output('Preparing system for image creation:')
182 tasks = self.list_syspreps()
183 enabled = filter(lambda x: x.enabled, tasks)
189 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
191 setattr(task.im_func, 'executed', True)
197 def mount(self, readonly=False):
200 if getattr(self, "mounted", False):
203 mount_type = 'read-only' if readonly else 'read-write'
204 self.out.output("Mounting the media %s ..." % mount_type, False)
206 if not self._do_mount(readonly):
210 self.out.success('done')
214 """Umount all mounted filesystems."""
216 self.out.output("Umounting the media ...", False)
219 self.out.success('done')
221 def _is_sysprep(self, obj):
222 """Checks if an object is a sysprep"""
223 return getattr(obj, 'sysprep', False) and callable(obj)
226 def _ls(self, directory):
227 """List the name of all files under a directory"""
228 return self.g.ls(directory)
231 def _find(self, directory):
232 """List the name of all files recursively under a directory"""
233 return self.g.find(directory)
235 def _foreach_file(self, directory, action, **kargs):
236 """Perform an action recursively on all files under a directory.
238 The following options are allowed:
240 * maxdepth: If defined the action will not be performed on
241 files that are below this level of directories under the
244 * ftype: The action will only be performed on files of this
245 type. For a list of all allowed filetypes, see here:
246 http://libguestfs.org/guestfs.3.html#guestfs_readdir
248 * exclude: Exclude all files that follow this pattern.
250 maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
255 maxdepth = None if maxdepth is None else maxdepth - 1
256 kargs['maxdepth'] = maxdepth
258 exclude = None if 'exclude' not in kargs else kargs['exclude']
259 ftype = None if 'ftype' not in kargs else kargs['ftype']
260 has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
262 for f in self.g.readdir(directory):
263 if f['name'] in ('.', '..'):
266 full_path = "%s/%s" % (directory, f['name'])
268 if exclude and re.match(exclude, full_path):
271 if has_ftype(f, 'd'):
272 self._foreach_file(full_path, action, **kargs)
274 if has_ftype(f, ftype):
277 def _do_collect_metadata(self):
278 """helper method for collect_metadata"""
279 self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
280 self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
281 self.meta['OS'] = self.g.inspect_get_distro(self.root)
282 if self.meta['OS'] == "unknown":
283 self.meta['OS'] = self.meta['OSFAMILY']
284 self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
286 def _do_mount(self, readonly):
287 """helper method for mount"""
289 self.g.mount_options('ro' if readonly else 'rw', self.root, '/')
290 except RuntimeError as msg:
291 self.out.warn("unable to mount the root partition: %s" % msg)
296 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :