Statistics
| Branch: | Tag: | Revision:

root / image_creator / os_type / __init__.py @ d9aff2ae

History | View | Annotate | Download (10.7 kB)

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
from collections import namedtuple
45

    
46

    
47
def os_cls(distro, osfamily):
48
    """Given the distro name and the osfamily, return the appropriate class"""
49
    module = None
50
    classname = None
51
    try:
52
        module = __import__("image_creator.os_type.%s" % distro,
53
                            fromlist=['image_creator.os_type'])
54
        classname = distro.capitalize()
55
    except ImportError:
56
        module = __import__("image_creator.os_type.%s" % osfamily,
57
                            fromlist=['image_creator.os_type'])
58
        classname = osfamily.capitalize()
59

    
60
    return getattr(module, classname)
61

    
62

    
63
def add_prefix(target):
64
    def wrapper(self, *args):
65
        prefix = args[0]
66
        return map(lambda x: prefix + x, target(self, *args))
67
    return wrapper
68

    
69

    
70
def sysprep(enabled=True):
71
    """Decorator for system preparation tasks"""
72
    def wrapper(func):
73
        func.sysprep = True
74
        func.enabled = enabled
75
        func.executed = False
76
        return func
77
    return wrapper
78

    
79

    
80
class OSBase(object):
81
    """Basic operating system class"""
82

    
83
    SysprepParam = namedtuple('SysprepParam',
84
                              'name description length validator')
85

    
86
    def __init__(self, image, **kargs):
87
        self.image = image
88

    
89
        self.root = image.root
90
        self.g = image.g
91
        self.out = image.out
92

    
93
        self.sysprep_params = \
94
            kargs['sysprep_params'] if 'sysprep_params' in kargs else {}
95

    
96
        self.meta = {}
97

    
98
    def collect_metadata(self):
99
        """Collect metadata about the OS"""
100
        try:
101
            if not self.mount(readonly=True):
102
                raise FatalError("Unable to mount the media read-only")
103

    
104
            self.out.output('Collecting image metadata ...', False)
105
            self._do_collect_metadata()
106
            self.out.success('done')
107
        finally:
108
            self.umount()
109

    
110
        self.out.output()
111

    
112
    def needed_sysprep_params(self):
113
        """Returns a list of needed sysprep parameters. Each element in the
114
        list is a SysprepParam object.
115
        """
116
        return []
117

    
118
    def list_syspreps(self):
119
        """Returns a list of sysprep objects"""
120
        objs = [getattr(self, name) for name in dir(self)
121
                if not name.startswith('_')]
122

    
123
        return [x for x in objs if self._is_sysprep(x) and x.executed is False]
124

    
125
    def sysprep_info(self, obj):
126
        """Returns information about a sysprep object"""
127
        assert self._is_sysprep(obj), "Object is not a sysprep"
128

    
129
        return (obj.__name__.replace('_', '-'), textwrap.dedent(obj.__doc__))
130

    
131
    def get_sysprep_by_name(self, name):
132
        """Returns the sysprep object with the given name"""
133
        error_msg = "Syprep operation %s does not exist for %s" % \
134
                    (name, self.__class__.__name__)
135

    
136
        method_name = name.replace('-', '_')
137
        method = None
138
        try:
139
            method = getattr(self, method_name)
140
        except AttributeError:
141
            raise FatalError(error_msg)
142

    
143
        if not self._is_sysprep(method):
144
            raise FatalError(error_msg)
145

    
146
        return method
147

    
148
    def enable_sysprep(self, obj):
149
        """Enable a system preparation operation"""
150
        setattr(obj.im_func, 'enabled', True)
151

    
152
    def disable_sysprep(self, obj):
153
        """Disable a system preparation operation"""
154
        setattr(obj.im_func, 'enabled', False)
155

    
156
    def print_syspreps(self):
157
        """Print enabled and disabled system preparation operations."""
158

    
159
        syspreps = self.list_syspreps()
160
        enabled = filter(lambda x: x.enabled, syspreps)
161
        disabled = filter(lambda x: not x.enabled, syspreps)
162

    
163
        wrapper = textwrap.TextWrapper()
164
        wrapper.subsequent_indent = '\t'
165
        wrapper.initial_indent = '\t'
166
        wrapper.width = 72
167

    
168
        self.out.output("Enabled system preparation operations:")
169
        if len(enabled) == 0:
170
            self.out.output("(none)")
171
        else:
172
            for sysprep in enabled:
173
                name = sysprep.__name__.replace('_', '-')
174
                descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
175
                self.out.output('    %s:\n%s\n' % (name, descr))
176

    
177
        self.out.output("Disabled system preparation operations:")
178
        if len(disabled) == 0:
179
            self.out.output("(none)")
180
        else:
181
            for sysprep in disabled:
182
                name = sysprep.__name__.replace('_', '-')
183
                descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
184
                self.out.output('    %s:\n%s\n' % (name, descr))
185

    
186
    def print_sysprep_params(self):
187
        """Print the system preparation parameter the user may use"""
188

    
189
        self.out.output("Needed system preparation parameters:")
190

    
191
        params = self.needed_sysprep_params()
192

    
193
        if len(params) == 0:
194
            self.out.output("(none)")
195
            return
196

    
197
        for param in params:
198
            self.out.output("\t%s (%s): %s" %
199
                            (param.description, param.name,
200
                             self.sysprep_params[param.name] if param.name in
201
                             self.sysprep_params else "(none)"))
202

    
203
    def do_sysprep(self):
204
        """Prepare system for image creation."""
205

    
206
        try:
207
            if not self.mount(readonly=False):
208
                raise FatalError("Unable to mount the media read-write")
209

    
210
            self.out.output('Preparing system for image creation:')
211

    
212
            tasks = self.list_syspreps()
213
            enabled = filter(lambda x: x.enabled, tasks)
214

    
215
            size = len(enabled)
216
            cnt = 0
217
            for task in enabled:
218
                cnt += 1
219
                self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
220
                task()
221
                setattr(task.im_func, 'executed', True)
222
        finally:
223
            self.umount()
224

    
225
        self.out.output()
226

    
227
    def mount(self, readonly=False):
228
        """Mount image."""
229

    
230
        if getattr(self, "mounted", False):
231
            return True
232

    
233
        mount_type = 'read-only' if readonly else 'read-write'
234
        self.out.output("Mounting the media %s ..." % mount_type, False)
235

    
236
        if not self._do_mount(readonly):
237
            return False
238

    
239
        self.mounted = True
240
        self.out.success('done')
241
        return True
242

    
243
    def umount(self):
244
        """Umount all mounted filesystems."""
245

    
246
        self.out.output("Umounting the media ...", False)
247
        self.g.umount_all()
248
        self.mounted = False
249
        self.out.success('done')
250

    
251
    def _is_sysprep(self, obj):
252
        """Checks if an object is a sysprep"""
253
        return getattr(obj, 'sysprep', False) and callable(obj)
254

    
255
    @add_prefix
256
    def _ls(self, directory):
257
        """List the name of all files under a directory"""
258
        return self.g.ls(directory)
259

    
260
    @add_prefix
261
    def _find(self, directory):
262
        """List the name of all files recursively under a directory"""
263
        return self.g.find(directory)
264

    
265
    def _foreach_file(self, directory, action, **kargs):
266
        """Perform an action recursively on all files under a directory.
267

268
        The following options are allowed:
269

270
        * maxdepth: If defined the action will not be performed on
271
          files that are below this level of directories under the
272
          directory parameter.
273

274
        * ftype: The action will only be performed on files of this
275
          type. For a list of all allowed filetypes, see here:
276
          http://libguestfs.org/guestfs.3.html#guestfs_readdir
277

278
        * exclude: Exclude all files that follow this pattern.
279
        """
280
        maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
281
        if maxdepth == 0:
282
            return
283

    
284
        # maxdepth -= 1
285
        maxdepth = None if maxdepth is None else maxdepth - 1
286
        kargs['maxdepth'] = maxdepth
287

    
288
        exclude = None if 'exclude' not in kargs else kargs['exclude']
289
        ftype = None if 'ftype' not in kargs else kargs['ftype']
290
        has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
291

    
292
        for f in self.g.readdir(directory):
293
            if f['name'] in ('.', '..'):
294
                continue
295

    
296
            full_path = "%s/%s" % (directory, f['name'])
297

    
298
            if exclude and re.match(exclude, full_path):
299
                continue
300

    
301
            if has_ftype(f, 'd'):
302
                self._foreach_file(full_path, action, **kargs)
303

    
304
            if has_ftype(f, ftype):
305
                action(full_path)
306

    
307
    def _do_collect_metadata(self):
308
        """helper method for collect_metadata"""
309
        self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
310
        self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
311
        self.meta['OS'] = self.g.inspect_get_distro(self.root)
312
        if self.meta['OS'] == "unknown":
313
            self.meta['OS'] = self.meta['OSFAMILY']
314
        self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
315

    
316
    def _do_mount(self, readonly):
317
        """helper method for mount"""
318
        try:
319
            self.g.mount_options('ro' if readonly else 'rw', self.root, '/')
320
        except RuntimeError as msg:
321
            self.out.warn("unable to mount the root partition: %s" % msg)
322
            return False
323

    
324
        return True
325

    
326
# vim: set sta sts=4 shiftwidth=4 sw=4 et ai :