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