Fix typos in var names
[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 output, FatalError
35
36 import textwrap
37 import re
38
39
40 def add_prefix(target):
41     def wrapper(self, *args):
42         prefix = args[0]
43         return map(lambda x: prefix + x, target(self, *args))
44     return wrapper
45
46
47 def sysprep(enabled=True):
48     def wrapper(func):
49         func.sysprep = True
50         func.enabled = enabled
51         return func
52     return wrapper
53
54
55 class OSBase(object):
56     """Basic operating system class"""
57
58     def __init__(self, rootdev, ghandler):
59         self.root = rootdev
60         self.g = ghandler
61
62     def _is_sysprep(self, obj):
63         return getattr(obj, 'sysprep', False) and callable(obj)
64
65     def list_syspreps(self):
66
67         objs = [getattr(self, name) for name in dir(self) \
68             if not name.startswith('_')]
69
70         enabled = [x for x in objs if self._is_sysprep(x) and x.enabled]
71         disabled = [x for x in objs if self._is_sysprep(x) and not x.enabled]
72
73         return enabled, disabled
74
75     def _sysprep_change_status(self, name, status):
76
77         error_msg = "Syprep operation %s does not exist for %s" % \
78                 (name, self.__class__.__name__)
79
80         method_name = name.replace('-', '_')
81         method = None
82         try:
83             method = getattr(self, method_name)
84         except AttributeError:
85             raise FatalError(error_msg)
86
87         if not self._is_sysprep(method):
88             raise FatalError(error_msg)
89
90         setattr(method.im_func, 'enabled', status)
91
92     def enable_sysprep(self, name):
93         """Enable a system preperation operation"""
94         self._sysprep_change_status(name, True)
95
96     def disable_sysprep(self, name):
97         """Disable a system preperation operation"""
98         self._sysprep_change_status(name, False)
99
100     def print_syspreps(self):
101         """Print enabled and disabled system preperation operations."""
102
103         enabled, disabled = self.list_syspreps()
104
105         wrapper = textwrap.TextWrapper()
106         wrapper.subsequent_indent = '\t'
107         wrapper.initial_indent = '\t'
108
109         output("Enabled system preperation operations:")
110         if len(enabled) == 0:
111             output("(none)")
112         else:
113             for sysprep in enabled:
114                 name = sysprep.__name__.replace('_', '-')
115                 descr = wrapper.fill(sysprep.__doc__)
116                 output('    %s:\n%s\n' % (name, descr))
117
118         output("Disabled system preperation operations:")
119         if len(disabled) == 0:
120             output("(none)")
121         else:
122             for sysprep in disabled:
123                 name = sysprep.__name__.replace('_', '-')
124                 descr = wrapper.fill(sysprep.__doc__)
125                 output('    %s:\n%s\n' % (name, descr))
126
127     @add_prefix
128     def ls(self, directory):
129         """List the name of all files under a directory"""
130         return self.g.ls(directory)
131
132     @add_prefix
133     def find(self, directory):
134         """List the name of all files recursively under a directory"""
135         return self.g.find(directory)
136
137     def foreach_file(self, directory, action, **kargs):
138         """Perform an action recursively on all files under a directory.
139
140         The following options are allowed:
141
142         * maxdepth: If defined the action will not be performed on
143           files that are below this level of directories under the
144           directory parameter.
145
146         * ftype: The action will only be performed on files of this
147           type. For a list of all allowed filetypes, see here:
148           http://libguestfs.org/guestfs.3.html#guestfs_readdir
149
150         * exclude: Exclude all files that follow this pattern.
151         """
152         maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
153         if maxdepth == 0:
154             return
155
156         # maxdepth -= 1
157         maxdepth = None if maxdepth is None else maxdepth - 1
158         kargs['maxdepth'] = maxdepth
159
160         exclude = None if 'exclude' not in kargs else kargs['exclude']
161         ftype = None if 'ftype' not in kargs else kargs['ftype']
162         has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
163
164         for f in self.g.readdir(directory):
165             if f['name'] in ('.', '..'):
166                 continue
167
168             full_path = "%s/%s" % (directory, f['name'])
169
170             if exclude and re.match(exclude, full_path):
171                 continue
172
173             if has_ftype(f, 'd'):
174                 self.foreach_file(full_path, action, **kargs)
175
176             if has_ftype(f, ftype):
177                 action(full_path)
178
179     def get_metadata(self):
180         """Returns some descriptive metadata about the OS."""
181         meta = {}
182         meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
183         meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
184         meta['OS'] = self.g.inspect_get_distro(self.root)
185         meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
186
187         return meta
188
189     def do_sysprep(self):
190         """Prepere system for image creation."""
191
192         output('Preparing system for image creation:')
193
194         tasks, _ = self.list_syspreps()
195         size = len(tasks)
196         cnt = 0
197         for task in tasks:
198             cnt += 1
199             output(('(%d/%d)' % (cnt, size)).ljust(7), False)
200             task()
201         output()
202
203 # vim: set sta sts=4 shiftwidth=4 sw=4 et ai :