d0931722afdfabb36bbf677ba89a6643bc3cf0dd
[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         self.meta = {}
81
82     def collect_metadata(self):
83         """Collect metadata about the OS"""
84
85         try:
86             if not self.mount(readonly=True):
87                 raise FatalError("Unable to mount the media read-only")
88
89             self.out.output('Collecting image metadata ...', False)
90             self._do_collect_metadata()
91             self.out.success('done')
92         finally:
93             self.umount()
94
95     def _do_collect_metadata(self):
96
97         self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
98         self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
99         self.meta['OS'] = self.g.inspect_get_distro(self.root)
100         if self.meta['OS'] == "unknown":
101             self.meta['OS'] = self.meta['OSFAMILY']
102         self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
103
104     def _is_sysprep(self, obj):
105         return getattr(obj, 'sysprep', False) and callable(obj)
106
107     def list_syspreps(self):
108
109         objs = [getattr(self, name) for name in dir(self)
110                 if not name.startswith('_')]
111
112         return [x for x in objs if self._is_sysprep(x) and x.executed is False]
113
114     def sysprep_info(self, obj):
115         assert self._is_sysprep(obj), "Object is not a sysprep"
116
117         return (obj.__name__.replace('_', '-'), textwrap.dedent(obj.__doc__))
118
119     def get_sysprep_by_name(self, name):
120         """Returns the sysprep object with the given name"""
121         error_msg = "Syprep operation %s does not exist for %s" % \
122                     (name, self.__class__.__name__)
123
124         method_name = name.replace('-', '_')
125         method = None
126         try:
127             method = getattr(self, method_name)
128         except AttributeError:
129             raise FatalError(error_msg)
130
131         if not self._is_sysprep(method):
132             raise FatalError(error_msg)
133
134         return method
135
136     def enable_sysprep(self, obj):
137         """Enable a system preparation operation"""
138         setattr(obj.im_func, 'enabled', True)
139
140     def disable_sysprep(self, obj):
141         """Disable a system preparation operation"""
142         setattr(obj.im_func, 'enabled', False)
143
144     def print_syspreps(self):
145         """Print enabled and disabled system preparation operations."""
146
147         syspreps = self.list_syspreps()
148         enabled = filter(lambda x: x.enabled, syspreps)
149         disabled = filter(lambda x: not x.enabled, syspreps)
150
151         wrapper = textwrap.TextWrapper()
152         wrapper.subsequent_indent = '\t'
153         wrapper.initial_indent = '\t'
154         wrapper.width = 72
155
156         self.out.output("Enabled system preparation operations:")
157         if len(enabled) == 0:
158             self.out.output("(none)")
159         else:
160             for sysprep in enabled:
161                 name = sysprep.__name__.replace('_', '-')
162                 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
163                 self.out.output('    %s:\n%s\n' % (name, descr))
164
165         self.out.output("Disabled system preparation operations:")
166         if len(disabled) == 0:
167             self.out.output("(none)")
168         else:
169             for sysprep in disabled:
170                 name = sysprep.__name__.replace('_', '-')
171                 descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
172                 self.out.output('    %s:\n%s\n' % (name, descr))
173
174     @add_prefix
175     def ls(self, directory):
176         """List the name of all files under a directory"""
177         return self.g.ls(directory)
178
179     @add_prefix
180     def find(self, directory):
181         """List the name of all files recursively under a directory"""
182         return self.g.find(directory)
183
184     def foreach_file(self, directory, action, **kargs):
185         """Perform an action recursively on all files under a directory.
186
187         The following options are allowed:
188
189         * maxdepth: If defined the action will not be performed on
190           files that are below this level of directories under the
191           directory parameter.
192
193         * ftype: The action will only be performed on files of this
194           type. For a list of all allowed filetypes, see here:
195           http://libguestfs.org/guestfs.3.html#guestfs_readdir
196
197         * exclude: Exclude all files that follow this pattern.
198         """
199         maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
200         if maxdepth == 0:
201             return
202
203         # maxdepth -= 1
204         maxdepth = None if maxdepth is None else maxdepth - 1
205         kargs['maxdepth'] = maxdepth
206
207         exclude = None if 'exclude' not in kargs else kargs['exclude']
208         ftype = None if 'ftype' not in kargs else kargs['ftype']
209         has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
210
211         for f in self.g.readdir(directory):
212             if f['name'] in ('.', '..'):
213                 continue
214
215             full_path = "%s/%s" % (directory, f['name'])
216
217             if exclude and re.match(exclude, full_path):
218                 continue
219
220             if has_ftype(f, 'd'):
221                 self.foreach_file(full_path, action, **kargs)
222
223             if has_ftype(f, ftype):
224                 action(full_path)
225
226     def do_sysprep(self):
227         """Prepere system for image creation."""
228
229         try:
230             if not self.mount(readonly=False):
231                 raise FatalError("Unable to mount the media read-write")
232
233             self.out.output('Preparing system for image creation:')
234
235             tasks = self.list_syspreps()
236             enabled = filter(lambda x: x.enabled, tasks)
237
238             size = len(enabled)
239             cnt = 0
240             for task in enabled:
241                 cnt += 1
242                 self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
243                 task()
244                 setattr(task.im_func, 'executed', True)
245             self.out.output()
246         finally:
247             self.umount()
248
249     def _do_mount(self, readonly):
250         try:
251             self.g.mount_options('ro' if readonly else 'rw', self.root, '/')
252         except RuntimeError as msg:
253             self.out.warn("unable to mount the root partition: %s" % msg)
254             return False
255
256         return True
257
258     def mount(self, readonly=False):
259         """Mount image."""
260
261         if getattr(self, "mounted", False):
262             return True
263
264         mount_type = 'read-only' if readonly else 'read-write'
265         self.out.output("Mount the media %s ..." % mount_type, False)
266
267         if not self._do_mount(readonly):
268             return False
269
270         self.mounted = True
271         self.out.success('done')
272         return True
273
274     def umount(self):
275         """Umount all mounted filesystems."""
276         self.g.umount_all()
277         self.mounted = False
278
279 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :