1 # Copyright 2012 GRNET S.A. All rights reserved.
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
7 # 1. Redistributions of source code must retain the above
8 # copyright notice, this list of conditions and the following
11 # 2. Redistributions in binary form must reproduce the above
12 # copyright notice, this list of conditions and the following
13 # disclaimer in the documentation and/or other materials
14 # provided with the distribution.
16 # THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 # USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 # POSSIBILITY OF SUCH DAMAGE.
29 # The views and conclusions contained in the software and
30 # documentation are those of the authors and should not be
31 # interpreted as representing official policies, either expressed
32 # or implied, of GRNET S.A.
34 from image_creator.util import FatalError
40 def os_cls(distro, osfamily):
41 """Given the distro name and the osfamily, return the appropriate class"""
45 module = __import__("image_creator.os_type.%s" % distro,
46 fromlist=['image_creator.os_type'])
47 classname = distro.capitalize()
49 module = __import__("image_creator.os_type.%s" % osfamily,
50 fromlist=['image_creator.os_type'])
51 classname = osfamily.capitalize()
53 return getattr(module, classname)
56 def add_prefix(target):
57 def wrapper(self, *args):
59 return map(lambda x: prefix + x, target(self, *args))
63 def sysprep(enabled=True):
64 """Decorator for system preparation tasks"""
67 func.enabled = enabled
73 """Basic operating system class"""
75 def __init__(self, rootdev, ghandler, output):
80 # Collect metadata about the OS
82 self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
83 self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
84 self.meta['OS'] = self.g.inspect_get_distro(self.root)
85 self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
87 def _is_sysprep(self, obj):
88 return getattr(obj, 'sysprep', False) and callable(obj)
90 def list_syspreps(self):
92 objs = [getattr(self, name) for name in dir(self)
93 if not name.startswith('_')]
95 return [x for x in objs if self._is_sysprep(x)]
97 def sysprep_info(self, obj):
98 assert self._is_sysprep(obj), "Object is not a sysprep"
100 return (obj.__name__.replace('_', '-'), textwrap.dedent(obj.__doc__))
102 def get_sysprep_by_name(self, name):
103 """Returns the sysprep object with the given name"""
104 error_msg = "Syprep operation %s does not exist for %s" % \
105 (name, self.__class__.__name__)
107 method_name = name.replace('-', '_')
110 method = getattr(self, method_name)
111 except AttributeError:
112 raise FatalError(error_msg)
114 if not self._is_sysprep(method):
115 raise FatalError(error_msg)
119 def enable_sysprep(self, obj):
120 """Enable a system preparation operation"""
121 setattr(obj.im_func, 'enabled', True)
123 def disable_sysprep(self, obj):
124 """Disable a system preparation operation"""
125 setattr(obj.im_func, 'enabled', False)
127 def print_syspreps(self):
128 """Print enabled and disabled system preparation operations."""
130 syspreps = self.list_syspreps()
131 enabled = filter(lambda x: x.enabled, syspreps)
132 disabled = filter(lambda x: not x.enabled, syspreps)
134 wrapper = textwrap.TextWrapper()
135 wrapper.subsequent_indent = '\t'
136 wrapper.initial_indent = '\t'
139 self.out.output("Enabled system preparation operations:")
140 if len(enabled) == 0:
141 self.out.output("(none)")
143 for sysprep in enabled:
144 name = sysprep.__name__.replace('_', '-')
145 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
146 self.out.output(' %s:\n%s\n' % (name, descr))
148 self.out.output("Disabled system preparation operations:")
149 if len(disabled) == 0:
150 self.out.output("(none)")
152 for sysprep in disabled:
153 name = sysprep.__name__.replace('_', '-')
154 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
155 self.out.output(' %s:\n%s\n' % (name, descr))
158 def ls(self, directory):
159 """List the name of all files under a directory"""
160 return self.g.ls(directory)
163 def find(self, directory):
164 """List the name of all files recursively under a directory"""
165 return self.g.find(directory)
167 def foreach_file(self, directory, action, **kargs):
168 """Perform an action recursively on all files under a directory.
170 The following options are allowed:
172 * maxdepth: If defined the action will not be performed on
173 files that are below this level of directories under the
176 * ftype: The action will only be performed on files of this
177 type. For a list of all allowed filetypes, see here:
178 http://libguestfs.org/guestfs.3.html#guestfs_readdir
180 * exclude: Exclude all files that follow this pattern.
182 maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
187 maxdepth = None if maxdepth is None else maxdepth - 1
188 kargs['maxdepth'] = maxdepth
190 exclude = None if 'exclude' not in kargs else kargs['exclude']
191 ftype = None if 'ftype' not in kargs else kargs['ftype']
192 has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
194 for f in self.g.readdir(directory):
195 if f['name'] in ('.', '..'):
198 full_path = "%s/%s" % (directory, f['name'])
200 if exclude and re.match(exclude, full_path):
203 if has_ftype(f, 'd'):
204 self.foreach_file(full_path, action, **kargs)
206 if has_ftype(f, ftype):
209 def do_sysprep(self):
210 """Prepere system for image creation."""
212 self.out.output('Preparing system for image creation:')
214 tasks = self.list_syspreps()
215 enabled = filter(lambda x: x.enabled, tasks)
221 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
225 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :