063b4100b6db15ec0ed6a227e465954ecf7686ee
[snf-image-creator] / image_creator / os_type / __init__.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2012 GRNET S.A. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or
6 # without modification, are permitted provided that the following
7 # conditions are met:
8 #
9 #   1. Redistributions of source code must retain the above
10 #      copyright notice, this list of conditions and the following
11 #      disclaimer.
12 #
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.
17 #
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.
30 #
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.
35
36 """This package provides various classes for preparing different Operating
37 Systems for image creation.
38 """
39
40 from image_creator.util import FatalError
41
42 import textwrap
43 import re
44
45
46 def os_cls(distro, osfamily):
47     """Given the distro name and the osfamily, return the appropriate class"""
48     module = None
49     classname = None
50     try:
51         module = __import__("image_creator.os_type.%s" % distro,
52                             fromlist=['image_creator.os_type'])
53         classname = distro.capitalize()
54     except ImportError:
55         module = __import__("image_creator.os_type.%s" % osfamily,
56                             fromlist=['image_creator.os_type'])
57         classname = osfamily.capitalize()
58
59     return getattr(module, classname)
60
61
62 def add_prefix(target):
63     def wrapper(self, *args):
64         prefix = args[0]
65         return map(lambda x: prefix + x, target(self, *args))
66     return wrapper
67
68
69 def sysprep(enabled=True):
70     """Decorator for system preparation tasks"""
71     def wrapper(func):
72         func.sysprep = True
73         func.enabled = enabled
74         func.executed = False
75         return func
76     return wrapper
77
78
79 class OSBase(object):
80     """Basic operating system class"""
81
82     def __init__(self, image):
83         self.image = image
84
85         self.root = image.root
86         self.g = image.g
87         self.out = image.out
88
89         self.meta = {}
90
91     def collect_metadata(self):
92         """Collect metadata about the OS"""
93         try:
94             if not self.mount(readonly=True):
95                 raise FatalError("Unable to mount the media read-only")
96
97             self.out.output('Collecting image metadata ...', False)
98             self._do_collect_metadata()
99             self.out.success('done')
100         finally:
101             self.umount()
102
103         self.out.output()
104
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('_')]
109
110         return [x for x in objs if self._is_sysprep(x) and x.executed is False]
111
112     def sysprep_info(self, obj):
113         """Returns information about a sysprep object"""
114         assert self._is_sysprep(obj), "Object is not a sysprep"
115
116         return (obj.__name__.replace('_', '-'), textwrap.dedent(obj.__doc__))
117
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__)
122
123         method_name = name.replace('-', '_')
124         method = None
125         try:
126             method = getattr(self, method_name)
127         except AttributeError:
128             raise FatalError(error_msg)
129
130         if not self._is_sysprep(method):
131             raise FatalError(error_msg)
132
133         return method
134
135     def enable_sysprep(self, obj):
136         """Enable a system preparation operation"""
137         setattr(obj.im_func, 'enabled', True)
138
139     def disable_sysprep(self, obj):
140         """Disable a system preparation operation"""
141         setattr(obj.im_func, 'enabled', False)
142
143     def print_syspreps(self):
144         """Print enabled and disabled system preparation operations."""
145
146         syspreps = self.list_syspreps()
147         enabled = filter(lambda x: x.enabled, syspreps)
148         disabled = filter(lambda x: not x.enabled, syspreps)
149
150         wrapper = textwrap.TextWrapper()
151         wrapper.subsequent_indent = '\t'
152         wrapper.initial_indent = '\t'
153         wrapper.width = 72
154
155         self.out.output("Enabled system preparation operations:")
156         if len(enabled) == 0:
157             self.out.output("(none)")
158         else:
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))
163
164         self.out.output("Disabled system preparation operations:")
165         if len(disabled) == 0:
166             self.out.output("(none)")
167         else:
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))
172
173     def do_sysprep(self):
174         """Prepare system for image creation."""
175
176         try:
177             if not self.mount(readonly=False):
178                 raise FatalError("Unable to mount the media read-write")
179
180             self.out.output('Preparing system for image creation:')
181
182             tasks = self.list_syspreps()
183             enabled = filter(lambda x: x.enabled, tasks)
184
185             size = len(enabled)
186             cnt = 0
187             for task in enabled:
188                 cnt += 1
189                 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
190                 task()
191                 setattr(task.im_func, 'executed', True)
192         finally:
193             self.umount()
194
195         self.out.output()
196
197     def mount(self, readonly=False):
198         """Mount image."""
199
200         if getattr(self, "mounted", False):
201             return True
202
203         mount_type = 'read-only' if readonly else 'read-write'
204         self.out.output("Mounting the media %s ..." % mount_type, False)
205
206         if not self._do_mount(readonly):
207             return False
208
209         self.mounted = True
210         self.out.success('done')
211         return True
212
213     def umount(self):
214         """Umount all mounted filesystems."""
215
216         self.out.output("Umounting the media ...", False)
217         self.g.umount_all()
218         self.mounted = False
219         self.out.success('done')
220
221     def _is_sysprep(self, obj):
222         """Checks if an object is a sysprep"""
223         return getattr(obj, 'sysprep', False) and callable(obj)
224
225     @add_prefix
226     def _ls(self, directory):
227         """List the name of all files under a directory"""
228         return self.g.ls(directory)
229
230     @add_prefix
231     def _find(self, directory):
232         """List the name of all files recursively under a directory"""
233         return self.g.find(directory)
234
235     def _foreach_file(self, directory, action, **kargs):
236         """Perform an action recursively on all files under a directory.
237
238         The following options are allowed:
239
240         * maxdepth: If defined the action will not be performed on
241           files that are below this level of directories under the
242           directory parameter.
243
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
247
248         * exclude: Exclude all files that follow this pattern.
249         """
250         maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
251         if maxdepth == 0:
252             return
253
254         # maxdepth -= 1
255         maxdepth = None if maxdepth is None else maxdepth - 1
256         kargs['maxdepth'] = maxdepth
257
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
261
262         for f in self.g.readdir(directory):
263             if f['name'] in ('.', '..'):
264                 continue
265
266             full_path = "%s/%s" % (directory, f['name'])
267
268             if exclude and re.match(exclude, full_path):
269                 continue
270
271             if has_ftype(f, 'd'):
272                 self._foreach_file(full_path, action, **kargs)
273
274             if has_ftype(f, ftype):
275                 action(full_path)
276
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)
285
286     def _do_mount(self, readonly):
287         """helper method for mount"""
288         try:
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)
292             return False
293
294         return True
295
296 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :