Statistics
| Branch: | Tag: | Revision:

root / image_creator / os_type / __init__.py @ c71f38be

History | View | Annotate | Download (9.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

    
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, rootdev, ghandler, output):
83
        self.root = rootdev
84
        self.g = ghandler
85
        self.out = output
86
        self.meta = {}
87

    
88
    def collect_metadata(self):
89
        """Collect metadata about the OS"""
90
        try:
91
            if not self.mount(readonly=True):
92
                raise FatalError("Unable to mount the media read-only")
93

    
94
            self.out.output('Collecting image metadata ...', False)
95
            self._do_collect_metadata()
96
            self.out.success('done')
97
        finally:
98
            self.umount()
99

    
100
        self.out.output()
101

    
102
    def list_syspreps(self):
103
        """Returns a list of sysprep objects"""
104
        objs = [getattr(self, name) for name in dir(self)
105
                if not name.startswith('_')]
106

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

    
109
    def sysprep_info(self, obj):
110
        """Returns information about a sysprep object"""
111
        assert self._is_sysprep(obj), "Object is not a sysprep"
112

    
113
        return (obj.__name__.replace('_', '-'), textwrap.dedent(obj.__doc__))
114

    
115
    def get_sysprep_by_name(self, name):
116
        """Returns the sysprep object with the given name"""
117
        error_msg = "Syprep operation %s does not exist for %s" % \
118
                    (name, self.__class__.__name__)
119

    
120
        method_name = name.replace('-', '_')
121
        method = None
122
        try:
123
            method = getattr(self, method_name)
124
        except AttributeError:
125
            raise FatalError(error_msg)
126

    
127
        if not self._is_sysprep(method):
128
            raise FatalError(error_msg)
129

    
130
        return method
131

    
132
    def enable_sysprep(self, obj):
133
        """Enable a system preparation operation"""
134
        setattr(obj.im_func, 'enabled', True)
135

    
136
    def disable_sysprep(self, obj):
137
        """Disable a system preparation operation"""
138
        setattr(obj.im_func, 'enabled', False)
139

    
140
    def print_syspreps(self):
141
        """Print enabled and disabled system preparation operations."""
142

    
143
        syspreps = self.list_syspreps()
144
        enabled = filter(lambda x: x.enabled, syspreps)
145
        disabled = filter(lambda x: not x.enabled, syspreps)
146

    
147
        wrapper = textwrap.TextWrapper()
148
        wrapper.subsequent_indent = '\t'
149
        wrapper.initial_indent = '\t'
150
        wrapper.width = 72
151

    
152
        self.out.output("Enabled system preparation operations:")
153
        if len(enabled) == 0:
154
            self.out.output("(none)")
155
        else:
156
            for sysprep in enabled:
157
                name = sysprep.__name__.replace('_', '-')
158
                descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
159
                self.out.output('    %s:\n%s\n' % (name, descr))
160

    
161
        self.out.output("Disabled system preparation operations:")
162
        if len(disabled) == 0:
163
            self.out.output("(none)")
164
        else:
165
            for sysprep in disabled:
166
                name = sysprep.__name__.replace('_', '-')
167
                descr = wrapper.fill(textwrap.dedent(sysprep.__doc__))
168
                self.out.output('    %s:\n%s\n' % (name, descr))
169

    
170
    def do_sysprep(self):
171
        """Prepare system for image creation."""
172

    
173
        try:
174
            if not self.mount(readonly=False):
175
                raise FatalError("Unable to mount the media read-write")
176

    
177
            self.out.output('Preparing system for image creation:')
178

    
179
            tasks = self.list_syspreps()
180
            enabled = filter(lambda x: x.enabled, tasks)
181

    
182
            size = len(enabled)
183
            cnt = 0
184
            for task in enabled:
185
                cnt += 1
186
                self.out.output(('(%d/%d)' % (cnt, size)).ljust(7), False)
187
                task()
188
                setattr(task.im_func, 'executed', True)
189
        finally:
190
            self.umount()
191

    
192
        self.out.output()
193

    
194
    def mount(self, readonly=False):
195
        """Mount image."""
196

    
197
        if getattr(self, "mounted", False):
198
            return True
199

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

    
203
        if not self._do_mount(readonly):
204
            return False
205

    
206
        self.mounted = True
207
        self.out.success('done')
208
        return True
209

    
210
    def umount(self):
211
        """Umount all mounted filesystems."""
212

    
213
        self.out.output("Umounting the media ...", False)
214
        self.g.umount_all()
215
        self.mounted = False
216
        self.out.success('done')
217

    
218
    def _is_sysprep(self, obj):
219
        """Checks if an object is a sysprep"""
220
        return getattr(obj, 'sysprep', False) and callable(obj)
221

    
222
    @add_prefix
223
    def _ls(self, directory):
224
        """List the name of all files under a directory"""
225
        return self.g.ls(directory)
226

    
227
    @add_prefix
228
    def _find(self, directory):
229
        """List the name of all files recursively under a directory"""
230
        return self.g.find(directory)
231

    
232
    def _foreach_file(self, directory, action, **kargs):
233
        """Perform an action recursively on all files under a directory.
234

235
        The following options are allowed:
236

237
        * maxdepth: If defined the action will not be performed on
238
          files that are below this level of directories under the
239
          directory parameter.
240

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

245
        * exclude: Exclude all files that follow this pattern.
246
        """
247
        maxdepth = None if 'maxdepth' not in kargs else kargs['maxdepth']
248
        if maxdepth == 0:
249
            return
250

    
251
        # maxdepth -= 1
252
        maxdepth = None if maxdepth is None else maxdepth - 1
253
        kargs['maxdepth'] = maxdepth
254

    
255
        exclude = None if 'exclude' not in kargs else kargs['exclude']
256
        ftype = None if 'ftype' not in kargs else kargs['ftype']
257
        has_ftype = lambda x, y: y is None and True or x['ftyp'] == y
258

    
259
        for f in self.g.readdir(directory):
260
            if f['name'] in ('.', '..'):
261
                continue
262

    
263
            full_path = "%s/%s" % (directory, f['name'])
264

    
265
            if exclude and re.match(exclude, full_path):
266
                continue
267

    
268
            if has_ftype(f, 'd'):
269
                self._foreach_file(full_path, action, **kargs)
270

    
271
            if has_ftype(f, ftype):
272
                action(full_path)
273

    
274
    def _do_collect_metadata(self):
275
        """helper method for collect_metadata"""
276
        self.meta['ROOT_PARTITION'] = "%d" % self.g.part_to_partnum(self.root)
277
        self.meta['OSFAMILY'] = self.g.inspect_get_type(self.root)
278
        self.meta['OS'] = self.g.inspect_get_distro(self.root)
279
        if self.meta['OS'] == "unknown":
280
            self.meta['OS'] = self.meta['OSFAMILY']
281
        self.meta['DESCRIPTION'] = self.g.inspect_get_product_name(self.root)
282

    
283
    def _do_mount(self, readonly):
284
        """helper method for mount"""
285
        try:
286
            self.g.mount_options('ro' if readonly else 'rw', self.root, '/')
287
        except RuntimeError as msg:
288
            self.out.warn("unable to mount the root partition: %s" % msg)
289
            return False
290

    
291
        return True
292

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