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):
44 module = __import__("image_creator.os_type.%s"
45 % distro, fromlist=['image_creator.os_type'])
46 classname = distro.capitalize()
48 module = __import__("image_creator.os_type.%s"
49 % osfamily, fromlist=['image_creator.os_type'])
50 classname = osfamily.capitalize()
52 return getattr(module, classname)
55 def add_prefix(target):
56 def wrapper(self, *args):
58 return map(lambda x: prefix + x, target(self, *args))
62 def sysprep(enabled=True):
65 func.enabled = enabled
71 """Basic operating system class"""
73 def __init__(self, rootdev, ghandler, output):
78 # Collect metadata about the OS
80 self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
81 self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
82 self.meta['OS'] = self.g.inspect_get_distro(self.root)
83 self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
85 def _is_sysprep(self, obj):
86 return getattr(obj, 'sysprep', False) and callable(obj)
88 def list_syspreps(self):
90 objs = [getattr(self, name) for name in dir(self) \
91 if not name.startswith('_')]
93 return [x for x in objs if self._is_sysprep(x)]
95 def _sysprep_change_status(self, name, status):
97 error_msg = "Syprep operation %s does not exist for %s" % \
98 (name, self.__class__.__name__)
100 method_name = name.replace('-', '_')
103 method = getattr(self, method_name)
104 except AttributeError:
105 raise FatalError(error_msg)
107 if not self._is_sysprep(method):
108 raise FatalError(error_msg)
110 setattr(method.im_func, 'enabled', status)
112 def enable_sysprep(self, name):
113 """Enable a system preperation operation"""
114 self._sysprep_change_status(name, True)
116 def disable_sysprep(self, name):
117 """Disable a system preperation operation"""
118 self._sysprep_change_status(name, False)
120 def print_syspreps(self):
121 """Print enabled and disabled system preperation operations."""
123 syspreps = self.list_syspreps()
124 enabled = filter(lambda x: x.enabled, syspreps)
125 disabled = filter(lambda x: not x.enabled, syspreps)
127 wrapper = textwrap.TextWrapper()
128 wrapper.subsequent_indent = '\t'
129 wrapper.initial_indent = '\t'
132 self.out.output("Enabled system preperation operations:")
133 if len(enabled) == 0:
134 self.out.output("(none)")
136 for sysprep in enabled:
137 name = sysprep.__name__.replace('_', '-')
138 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
139 self.out.output(' %s:\n%s\n' % (name, descr))
141 self.out.output("Disabled system preperation operations:")
142 if len(disabled) == 0:
143 self.out.output("(none)")
145 for sysprep in disabled:
146 name = sysprep.__name__.replace('_', '-')
147 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
148 self.out.output(' %s:\n%s\n' % (name, descr))
151 def ls(self, directory):
152 """List the name of all files under a directory"""
153 return self.g.ls(directory)
156 def find(self, directory):
157 """List the name of all files recursively under a directory"""
158 return self.g.find(directory)
160 def foreach_file(self, directory, action, **kargs):
161 """Perform an action recursively on all files under a directory.
163 The following options are allowed:
165 * maxdepth: If defined the action will not be performed on
166 files that are below this level of directories under the
169 * ftype: The action will only be performed on files of this
170 type. For a list of all allowed filetypes, see here:
171 http://libguestfs.org/guestfs.3.html#guestfs_readdir
173 * exclude: Exclude all files that follow this pattern.
175 maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
180 maxdepth = None if maxdepth is None else maxdepth - 1
181 kargs['maxdepth'] = maxdepth
183 exclude = None if 'exclude' not in kargs else kargs['exclude']
184 ftype = None if 'ftype' not in kargs else kargs['ftype']
185 has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
187 for f in self.g.readdir(directory):
188 if f['name'] in ('.', '..'):
191 full_path = "%s/%s" % (directory, f['name'])
193 if exclude and re.match(exclude, full_path):
196 if has_ftype(f, 'd'):
197 self.foreach_file(full_path, action, **kargs)
199 if has_ftype(f, ftype):
202 def do_sysprep(self):
203 """Prepere system for image creation."""
205 self.out.output('Preparing system for image creation:')
207 tasks, _ = self.list_syspreps()
212 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
216 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :