cea08a32a8ac43575f4c0e167a858674ca5e8fc7
[snf-image-creator] / image_creator / os_type / __init__.py
1 # Copyright 2012 GRNET S.A. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or
4 # without modification, are permitted provided that the following
5 # conditions are met:
6 #
7 #   1. Redistributions of source code must retain the above
8 #      copyright notice, this list of conditions and the following
9 #      disclaimer.
10 #
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.
15 #
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.
28 #
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.
33
34 from image_creator.util import FatalError
35
36 import textwrap
37 import re
38
39
40 def os_cls(distro, osfamily):
41     """Given the distro name and the osfamily, return the appropriate class"""
42     module = None
43     classname = None
44     try:
45         module = __import__("image_creator.os_type.%s" % distro,
46                             fromlist=['image_creator.os_type'])
47         classname = distro.capitalize()
48     except ImportError:
49         module = __import__("image_creator.os_type.%s" % osfamily,
50                             fromlist=['image_creator.os_type'])
51         classname = osfamily.capitalize()
52
53     return getattr(module, classname)
54
55
56 def add_prefix(target):
57     def wrapper(self, *args):
58         prefix = args[0]
59         return map(lambda x: prefix + x, target(self, *args))
60     return wrapper
61
62
63 def sysprep(enabled=True):
64     """Decorator for system preparation tasks"""
65     def wrapper(func):
66         func.sysprep = True
67         func.enabled = enabled
68         func.executed = False
69         return func
70     return wrapper
71
72
73 class OSBase(object):
74     """Basic operating system class"""
75
76     def __init__(self, rootdev, ghandler, output):
77         self.root = rootdev
78         self.g = ghandler
79         self.out = output
80
81         # Collect metadata about the OS
82         self.meta = {}
83         self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
84         self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
85         self.meta['OS'] = self.g.inspect_get_distro(self.root)
86         if self.meta['OS'] == "unknown":
87             self.meta['OS'] = self.meta['OSFAMILY']
88         self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
89
90     def _is_sysprep(self, obj):
91         return getattr(obj, 'sysprep', False) and callable(obj)
92
93     def list_syspreps(self):
94
95         objs = [getattr(self, name) for name in dir(self)
96                 if not name.startswith('_')]
97
98         return [x for x in objs if self._is_sysprep(x) and x.executed is False]
99
100     def sysprep_info(self, obj):
101         assert self._is_sysprep(obj), "Object is not a sysprep"
102
103         return (obj.__name__.replace('_', '-'), textwrap.dedent(obj.__doc__))
104
105     def get_sysprep_by_name(self, name):
106         """Returns the sysprep object with the given name"""
107         error_msg = "Syprep operation %s does not exist for %s" % \
108                     (name, self.__class__.__name__)
109
110         method_name = name.replace('-', '_')
111         method = None
112         try:
113             method = getattr(self, method_name)
114         except AttributeError:
115             raise FatalError(error_msg)
116
117         if not self._is_sysprep(method):
118             raise FatalError(error_msg)
119
120         return method
121
122     def enable_sysprep(self, obj):
123         """Enable a system preparation operation"""
124         setattr(obj.im_func, 'enabled', True)
125
126     def disable_sysprep(self, obj):
127         """Disable a system preparation operation"""
128         setattr(obj.im_func, 'enabled', False)
129
130     def print_syspreps(self):
131         """Print enabled and disabled system preparation operations."""
132
133         syspreps = self.list_syspreps()
134         enabled = filter(lambda x: x.enabled, syspreps)
135         disabled = filter(lambda x: not x.enabled, syspreps)
136
137         wrapper = textwrap.TextWrapper()
138         wrapper.subsequent_indent = '\t'
139         wrapper.initial_indent = '\t'
140         wrapper.width = 72
141
142         self.out.output("Enabled system preparation operations:")
143         if len(enabled) == 0:
144             self.out.output("(none)")
145         else:
146             for sysprep in enabled:
147                 name = sysprep.__name__.replace('_', '-')
148                 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
149                 self.out.output('    %s:\n%s\n' % (name, descr))
150
151         self.out.output("Disabled system preparation operations:")
152         if len(disabled) == 0:
153             self.out.output("(none)")
154         else:
155             for sysprep in disabled:
156                 name = sysprep.__name__.replace('_', '-')
157                 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
158                 self.out.output('    %s:\n%s\n' % (name, descr))
159
160     @add_prefix
161     def ls(self, directory):
162         """List the name of all files under a directory"""
163         return self.g.ls(directory)
164
165     @add_prefix
166     def find(self, directory):
167         """List the name of all files recursively under a directory"""
168         return self.g.find(directory)
169
170     def foreach_file(self, directory, action, **kargs):
171         """Perform an action recursively on all files under a directory.
172
173         The following options are allowed:
174
175         * maxdepth: If defined the action will not be performed on
176           files that are below this level of directories under the
177           directory parameter.
178
179         * ftype: The action will only be performed on files of this
180           type. For a list of all allowed filetypes, see here:
181           http://libguestfs.org/guestfs.3.html#guestfs_readdir
182
183         * exclude: Exclude all files that follow this pattern.
184         """
185         maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
186         if maxdepth == 0:
187             return
188
189         # maxdepth -= 1
190         maxdepth = None if maxdepth is None else maxdepth - 1
191         kargs['maxdepth'] = maxdepth
192
193         exclude = None if 'exclude' not in kargs else kargs['exclude']
194         ftype = None if 'ftype' not in kargs else kargs['ftype']
195         has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
196
197         for f in self.g.readdir(directory):
198             if f['name'] in ('.', '..'):
199                 continue
200
201             full_path = "%s/%s" % (directory, f['name'])
202
203             if exclude and re.match(exclude, full_path):
204                 continue
205
206             if has_ftype(f, 'd'):
207                 self.foreach_file(full_path, action, **kargs)
208
209             if has_ftype(f, ftype):
210                 action(full_path)
211
212     def do_sysprep(self):
213         """Prepere system for image creation."""
214
215         self.out.output('Preparing system for image creation:')
216
217         tasks = self.list_syspreps()
218         enabled = filter(lambda x: x.enabled, tasks)
219
220         size = len(enabled)
221         cnt = 0
222         for task in enabled:
223             cnt += 1
224             self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
225             task()
226             setattr(task.im_func, 'executed', True)
227         self.out.output()
228
229 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :