root / lib / hypervisor / hv_base.py @ 823bfa49
History | View | Annotate | Download (13.9 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Google Inc.
|
5 |
#
|
6 |
# This program is free software; you can redistribute it and/or modify
|
7 |
# it under the terms of the GNU General Public License as published by
|
8 |
# the Free Software Foundation; either version 2 of the License, or
|
9 |
# (at your option) any later version.
|
10 |
#
|
11 |
# This program is distributed in the hope that it will be useful, but
|
12 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 |
# General Public License for more details.
|
15 |
#
|
16 |
# You should have received a copy of the GNU General Public License
|
17 |
# along with this program; if not, write to the Free Software
|
18 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
|
22 |
"""Base class for all hypervisors
|
23 |
|
24 |
The syntax for the _CHECK variables and the contents of the PARAMETERS
|
25 |
dict is the same, see the docstring for L{BaseHypervisor.PARAMETERS}.
|
26 |
|
27 |
@var _FILE_CHECK: stub for file checks, without the required flag
|
28 |
@var _DIR_CHECK: stub for directory checks, without the required flag
|
29 |
@var REQ_FILE_CHECK: mandatory file parameter
|
30 |
@var OPT_FILE_CHECK: optional file parameter
|
31 |
@var REQ_DIR_CHECK: mandatory directory parametr
|
32 |
@var OPT_DIR_CHECK: optional directory parameter
|
33 |
@var NO_CHECK: parameter without any checks at all
|
34 |
@var REQUIRED_CHECK: parameter required to exist (and non-false), but
|
35 |
without other checks; beware that this can't be used for boolean
|
36 |
parameters, where you should use NO_CHECK or a custom checker
|
37 |
|
38 |
"""
|
39 |
|
40 |
import os |
41 |
import re |
42 |
import logging |
43 |
|
44 |
|
45 |
from ganeti import errors |
46 |
from ganeti import utils |
47 |
from ganeti import constants |
48 |
|
49 |
|
50 |
def _IsCpuMaskWellFormed(cpu_mask): |
51 |
try:
|
52 |
cpu_list = utils.ParseCpuMask(cpu_mask) |
53 |
except errors.ParseError, _:
|
54 |
return False |
55 |
return isinstance(cpu_list, list) and len(cpu_list) > 0 |
56 |
|
57 |
|
58 |
# Read the BaseHypervisor.PARAMETERS docstring for the syntax of the
|
59 |
# _CHECK values
|
60 |
|
61 |
# must be afile
|
62 |
_FILE_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
|
63 |
os.path.isfile, "not found or not a file")
|
64 |
|
65 |
# must be a file or a URL
|
66 |
_FILE_OR_URL_CHECK = (utils.IsNormAbsPathOrURL, |
67 |
"must be an absolute normalized path or a URL",
|
68 |
lambda x: os.path.isfile(x) or |
69 |
re.match(r'(https?|ftp)://', x),
|
70 |
"not found or not a file or URL")
|
71 |
|
72 |
# must be a directory
|
73 |
_DIR_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
|
74 |
os.path.isdir, "not found or not a directory")
|
75 |
|
76 |
# CPU mask must be well-formed
|
77 |
# TODO: implement node level check for the CPU mask
|
78 |
_CPU_MASK_CHECK = (_IsCpuMaskWellFormed, |
79 |
"CPU mask definition is not well-formed",
|
80 |
None, None) |
81 |
|
82 |
# nice wrappers for users
|
83 |
REQ_FILE_CHECK = (True, ) + _FILE_CHECK
|
84 |
OPT_FILE_CHECK = (False, ) + _FILE_CHECK
|
85 |
REQ_FILE_OR_URL_CHECK = (True, ) + _FILE_OR_URL_CHECK
|
86 |
OPT_FILE_OR_URL_CHECK = (False, ) + _FILE_OR_URL_CHECK
|
87 |
REQ_DIR_CHECK = (True, ) + _DIR_CHECK
|
88 |
OPT_DIR_CHECK = (False, ) + _DIR_CHECK
|
89 |
NET_PORT_CHECK = (True, lambda x: x > 0 and x < 65535, "invalid port number", |
90 |
None, None) |
91 |
OPT_CPU_MASK_CHECK = (False, ) + _CPU_MASK_CHECK
|
92 |
REQ_CPU_MASK_CHECK = (True, ) + _CPU_MASK_CHECK
|
93 |
|
94 |
# no checks at all
|
95 |
NO_CHECK = (False, None, None, None, None) |
96 |
|
97 |
# required, but no other checks
|
98 |
REQUIRED_CHECK = (True, None, None, None, None) |
99 |
|
100 |
# migration type
|
101 |
MIGRATION_MODE_CHECK = (True, lambda x: x in constants.HT_MIGRATION_MODES, |
102 |
"invalid migration mode", None, None) |
103 |
|
104 |
|
105 |
def ParamInSet(required, my_set): |
106 |
"""Builds parameter checker for set membership.
|
107 |
|
108 |
@type required: boolean
|
109 |
@param required: whether this is a required parameter
|
110 |
@type my_set: tuple, list or set
|
111 |
@param my_set: allowed values set
|
112 |
|
113 |
"""
|
114 |
fn = lambda x: x in my_set |
115 |
err = ("The value must be one of: %s" % utils.CommaJoin(my_set))
|
116 |
return (required, fn, err, None, None) |
117 |
|
118 |
|
119 |
class BaseHypervisor(object): |
120 |
"""Abstract virtualisation technology interface
|
121 |
|
122 |
The goal is that all aspects of the virtualisation technology are
|
123 |
abstracted away from the rest of code.
|
124 |
|
125 |
@cvar PARAMETERS: a dict of parameter name: check type; the check type is
|
126 |
a five-tuple containing:
|
127 |
- the required flag (boolean)
|
128 |
- a function to check for syntax, that will be used in
|
129 |
L{CheckParameterSyntax}, in the master daemon process
|
130 |
- an error message for the above function
|
131 |
- a function to check for parameter validity on the remote node,
|
132 |
in the L{ValidateParameters} function
|
133 |
- an error message for the above function
|
134 |
@type CAN_MIGRATE: boolean
|
135 |
@cvar CAN_MIGRATE: whether this hypervisor can do migration (either
|
136 |
live or non-live)
|
137 |
|
138 |
"""
|
139 |
PARAMETERS = {} |
140 |
ANCILLARY_FILES = [] |
141 |
CAN_MIGRATE = False
|
142 |
|
143 |
def __init__(self): |
144 |
pass
|
145 |
|
146 |
def StartInstance(self, instance, block_devices): |
147 |
"""Start an instance."""
|
148 |
raise NotImplementedError |
149 |
|
150 |
def StopInstance(self, instance, force=False, retry=False, name=None): |
151 |
"""Stop an instance
|
152 |
|
153 |
@type instance: L{objects.Instance}
|
154 |
@param instance: instance to stop
|
155 |
@type force: boolean
|
156 |
@param force: whether to do a "hard" stop (destroy)
|
157 |
@type retry: boolean
|
158 |
@param retry: whether this is just a retry call
|
159 |
@type name: string or None
|
160 |
@param name: if this parameter is passed, the the instance object
|
161 |
should not be used (will be passed as None), and the shutdown
|
162 |
must be done by name only
|
163 |
|
164 |
"""
|
165 |
raise NotImplementedError |
166 |
|
167 |
def CleanupInstance(self, instance_name): |
168 |
"""Cleanup after a stopped instance
|
169 |
|
170 |
This is an optional method, used by hypervisors that need to cleanup after
|
171 |
an instance has been stopped.
|
172 |
|
173 |
@type instance_name: string
|
174 |
@param instance_name: instance name to cleanup after
|
175 |
|
176 |
"""
|
177 |
pass
|
178 |
|
179 |
def RebootInstance(self, instance): |
180 |
"""Reboot an instance."""
|
181 |
raise NotImplementedError |
182 |
|
183 |
def ListInstances(self): |
184 |
"""Get the list of running instances."""
|
185 |
raise NotImplementedError |
186 |
|
187 |
def GetInstanceInfo(self, instance_name): |
188 |
"""Get instance properties.
|
189 |
|
190 |
@type instance_name: string
|
191 |
@param instance_name: the instance name
|
192 |
|
193 |
@return: tuple (name, id, memory, vcpus, state, times)
|
194 |
|
195 |
"""
|
196 |
raise NotImplementedError |
197 |
|
198 |
def GetAllInstancesInfo(self): |
199 |
"""Get properties of all instances.
|
200 |
|
201 |
@return: list of tuples (name, id, memory, vcpus, stat, times)
|
202 |
|
203 |
"""
|
204 |
raise NotImplementedError |
205 |
|
206 |
def GetNodeInfo(self): |
207 |
"""Return information about the node.
|
208 |
|
209 |
@return: a dict with the following keys (values in MiB):
|
210 |
- memory_total: the total memory size on the node
|
211 |
- memory_free: the available memory on the node for instances
|
212 |
- memory_dom0: the memory used by the node itself, if available
|
213 |
|
214 |
"""
|
215 |
raise NotImplementedError |
216 |
|
217 |
@classmethod
|
218 |
def GetInstanceConsole(cls, instance, hvparams, beparams): |
219 |
"""Return information for connecting to the console of an instance.
|
220 |
|
221 |
"""
|
222 |
raise NotImplementedError |
223 |
|
224 |
@classmethod
|
225 |
def GetAncillaryFiles(cls): |
226 |
"""Return a list of ancillary files to be copied to all nodes as ancillary
|
227 |
configuration files.
|
228 |
|
229 |
@rtype: list of strings
|
230 |
@return: list of absolute paths of files to ship cluster-wide
|
231 |
|
232 |
"""
|
233 |
# By default we return a member variable, so that if an hypervisor has just
|
234 |
# a static list of files it doesn't have to override this function.
|
235 |
return cls.ANCILLARY_FILES
|
236 |
|
237 |
def Verify(self): |
238 |
"""Verify the hypervisor.
|
239 |
|
240 |
"""
|
241 |
raise NotImplementedError |
242 |
|
243 |
def MigrationInfo(self, instance): # pylint: disable-msg=R0201,W0613 |
244 |
"""Get instance information to perform a migration.
|
245 |
|
246 |
By default assume no information is needed.
|
247 |
|
248 |
@type instance: L{objects.Instance}
|
249 |
@param instance: instance to be migrated
|
250 |
@rtype: string/data (opaque)
|
251 |
@return: instance migration information - serialized form
|
252 |
|
253 |
"""
|
254 |
return '' |
255 |
|
256 |
def AcceptInstance(self, instance, info, target): |
257 |
"""Prepare to accept an instance.
|
258 |
|
259 |
By default assume no preparation is needed.
|
260 |
|
261 |
@type instance: L{objects.Instance}
|
262 |
@param instance: instance to be accepted
|
263 |
@type info: string/data (opaque)
|
264 |
@param info: migration information, from the source node
|
265 |
@type target: string
|
266 |
@param target: target host (usually ip), on this node
|
267 |
|
268 |
"""
|
269 |
pass
|
270 |
|
271 |
def FinalizeMigration(self, instance, info, success): |
272 |
"""Finalized an instance migration.
|
273 |
|
274 |
Should finalize or revert any preparation done to accept the instance.
|
275 |
Since by default we do no preparation, we also don't have anything to do
|
276 |
|
277 |
@type instance: L{objects.Instance}
|
278 |
@param instance: instance whose migration is being finalized
|
279 |
@type info: string/data (opaque)
|
280 |
@param info: migration information, from the source node
|
281 |
@type success: boolean
|
282 |
@param success: whether the migration was a success or a failure
|
283 |
|
284 |
"""
|
285 |
pass
|
286 |
|
287 |
def MigrateInstance(self, instance, target, live): |
288 |
"""Migrate an instance.
|
289 |
|
290 |
@type instance: L{objects.Instance}
|
291 |
@param instance: the instance to be migrated
|
292 |
@type target: string
|
293 |
@param target: hostname (usually ip) of the target node
|
294 |
@type live: boolean
|
295 |
@param live: whether to do a live or non-live migration
|
296 |
|
297 |
"""
|
298 |
raise NotImplementedError |
299 |
|
300 |
@classmethod
|
301 |
def CheckParameterSyntax(cls, hvparams): |
302 |
"""Check the given parameters for validity.
|
303 |
|
304 |
This should check the passed set of parameters for
|
305 |
validity. Classes should extend, not replace, this function.
|
306 |
|
307 |
@type hvparams: dict
|
308 |
@param hvparams: dictionary with parameter names/value
|
309 |
@raise errors.HypervisorError: when a parameter is not valid
|
310 |
|
311 |
"""
|
312 |
for key in hvparams: |
313 |
if key not in cls.PARAMETERS: |
314 |
raise errors.HypervisorError("Parameter '%s' is not supported" % key) |
315 |
|
316 |
# cheap tests that run on the master, should not access the world
|
317 |
for name, (required, check_fn, errstr, _, _) in cls.PARAMETERS.items(): |
318 |
if name not in hvparams: |
319 |
raise errors.HypervisorError("Parameter '%s' is missing" % name) |
320 |
value = hvparams[name] |
321 |
if not required and not value: |
322 |
continue
|
323 |
if not value: |
324 |
raise errors.HypervisorError("Parameter '%s' is required but" |
325 |
" is currently not defined" % (name, ))
|
326 |
if check_fn is not None and not check_fn(value): |
327 |
raise errors.HypervisorError("Parameter '%s' fails syntax" |
328 |
" check: %s (current value: '%s')" %
|
329 |
(name, errstr, value)) |
330 |
|
331 |
@classmethod
|
332 |
def ValidateParameters(cls, hvparams): |
333 |
"""Check the given parameters for validity.
|
334 |
|
335 |
This should check the passed set of parameters for
|
336 |
validity. Classes should extend, not replace, this function.
|
337 |
|
338 |
@type hvparams: dict
|
339 |
@param hvparams: dictionary with parameter names/value
|
340 |
@raise errors.HypervisorError: when a parameter is not valid
|
341 |
|
342 |
"""
|
343 |
for name, (required, _, _, check_fn, errstr) in cls.PARAMETERS.items(): |
344 |
value = hvparams[name] |
345 |
if not required and not value: |
346 |
continue
|
347 |
if check_fn is not None and not check_fn(value): |
348 |
raise errors.HypervisorError("Parameter '%s' fails" |
349 |
" validation: %s (current value: '%s')" %
|
350 |
(name, errstr, value)) |
351 |
|
352 |
@classmethod
|
353 |
def PowercycleNode(cls): |
354 |
"""Hard powercycle a node using hypervisor specific methods.
|
355 |
|
356 |
This method should hard powercycle the node, using whatever
|
357 |
methods the hypervisor provides. Note that this means that all
|
358 |
instances running on the node must be stopped too.
|
359 |
|
360 |
"""
|
361 |
raise NotImplementedError |
362 |
|
363 |
@staticmethod
|
364 |
def GetLinuxNodeInfo(): |
365 |
"""For linux systems, return actual OS information.
|
366 |
|
367 |
This is an abstraction for all non-hypervisor-based classes, where
|
368 |
the node actually sees all the memory and CPUs via the /proc
|
369 |
interface and standard commands. The other case if for example
|
370 |
xen, where you only see the hardware resources via xen-specific
|
371 |
tools.
|
372 |
|
373 |
@return: a dict with the following keys (values in MiB):
|
374 |
- memory_total: the total memory size on the node
|
375 |
- memory_free: the available memory on the node for instances
|
376 |
- memory_dom0: the memory used by the node itself, if available
|
377 |
|
378 |
"""
|
379 |
try:
|
380 |
data = utils.ReadFile("/proc/meminfo").splitlines()
|
381 |
except EnvironmentError, err: |
382 |
raise errors.HypervisorError("Failed to list node info: %s" % (err,)) |
383 |
|
384 |
result = {} |
385 |
sum_free = 0
|
386 |
try:
|
387 |
for line in data: |
388 |
splitfields = line.split(":", 1) |
389 |
|
390 |
if len(splitfields) > 1: |
391 |
key = splitfields[0].strip()
|
392 |
val = splitfields[1].strip()
|
393 |
if key == 'MemTotal': |
394 |
result['memory_total'] = int(val.split()[0])/1024 |
395 |
elif key in ('MemFree', 'Buffers', 'Cached'): |
396 |
sum_free += int(val.split()[0])/1024 |
397 |
elif key == 'Active': |
398 |
result['memory_dom0'] = int(val.split()[0])/1024 |
399 |
except (ValueError, TypeError), err: |
400 |
raise errors.HypervisorError("Failed to compute memory usage: %s" % |
401 |
(err,)) |
402 |
result['memory_free'] = sum_free
|
403 |
|
404 |
cpu_total = 0
|
405 |
try:
|
406 |
fh = open("/proc/cpuinfo") |
407 |
try:
|
408 |
cpu_total = len(re.findall("(?m)^processor\s*:\s*[0-9]+\s*$", |
409 |
fh.read())) |
410 |
finally:
|
411 |
fh.close() |
412 |
except EnvironmentError, err: |
413 |
raise errors.HypervisorError("Failed to list node info: %s" % (err,)) |
414 |
result['cpu_total'] = cpu_total
|
415 |
# FIXME: export correct data here
|
416 |
result['cpu_nodes'] = 1 |
417 |
result['cpu_sockets'] = 1 |
418 |
|
419 |
return result
|
420 |
|
421 |
@classmethod
|
422 |
def LinuxPowercycle(cls): |
423 |
"""Linux-specific powercycle method.
|
424 |
|
425 |
"""
|
426 |
try:
|
427 |
fd = os.open("/proc/sysrq-trigger", os.O_WRONLY)
|
428 |
try:
|
429 |
os.write(fd, "b")
|
430 |
finally:
|
431 |
fd.close() |
432 |
except OSError: |
433 |
logging.exception("Can't open the sysrq-trigger file")
|
434 |
result = utils.RunCmd(["reboot", "-n", "-f"]) |
435 |
if not result: |
436 |
logging.error("Can't run shutdown: %s", result.output)
|