root / lib / hypervisor / hv_base.py @ 6e043e60
History | View | Annotate | Download (16.8 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2012 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 |
"""Verifies if the given single CPU mask is valid
|
52 |
|
53 |
The single CPU mask should be in the form "a,b,c,d", where each
|
54 |
letter is a positive number or range.
|
55 |
|
56 |
"""
|
57 |
try:
|
58 |
cpu_list = utils.ParseCpuMask(cpu_mask) |
59 |
except errors.ParseError, _:
|
60 |
return False |
61 |
return isinstance(cpu_list, list) and len(cpu_list) > 0 |
62 |
|
63 |
|
64 |
def _IsMultiCpuMaskWellFormed(cpu_mask): |
65 |
"""Verifies if the given multiple CPU mask is valid
|
66 |
|
67 |
A valid multiple CPU mask is in the form "a:b:c:d", where each
|
68 |
letter is a single CPU mask.
|
69 |
|
70 |
"""
|
71 |
try:
|
72 |
utils.ParseMultiCpuMask(cpu_mask) |
73 |
except errors.ParseError, _:
|
74 |
return False |
75 |
|
76 |
return True |
77 |
|
78 |
|
79 |
# Read the BaseHypervisor.PARAMETERS docstring for the syntax of the
|
80 |
# _CHECK values
|
81 |
|
82 |
# must be afile
|
83 |
_FILE_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
|
84 |
os.path.isfile, "not found or not a file")
|
85 |
|
86 |
# must be a directory
|
87 |
_DIR_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
|
88 |
os.path.isdir, "not found or not a directory")
|
89 |
|
90 |
# CPU mask must be well-formed
|
91 |
# TODO: implement node level check for the CPU mask
|
92 |
_CPU_MASK_CHECK = (_IsCpuMaskWellFormed, |
93 |
"CPU mask definition is not well-formed",
|
94 |
None, None) |
95 |
|
96 |
# Multiple CPU mask must be well-formed
|
97 |
_MULTI_CPU_MASK_CHECK = (_IsMultiCpuMaskWellFormed, |
98 |
"Multiple CPU mask definition is not well-formed",
|
99 |
None, None) |
100 |
|
101 |
# Check for validity of port number
|
102 |
_NET_PORT_CHECK = (lambda x: 0 < x < 65535, "invalid port number", |
103 |
None, None) |
104 |
|
105 |
# Check that an integer is non negative
|
106 |
_NONNEGATIVE_INT_CHECK = (lambda x: x >= 0, "cannot be negative", None, None) |
107 |
|
108 |
# nice wrappers for users
|
109 |
REQ_FILE_CHECK = (True, ) + _FILE_CHECK
|
110 |
OPT_FILE_CHECK = (False, ) + _FILE_CHECK
|
111 |
REQ_DIR_CHECK = (True, ) + _DIR_CHECK
|
112 |
OPT_DIR_CHECK = (False, ) + _DIR_CHECK
|
113 |
REQ_NET_PORT_CHECK = (True, ) + _NET_PORT_CHECK
|
114 |
OPT_NET_PORT_CHECK = (False, ) + _NET_PORT_CHECK
|
115 |
REQ_CPU_MASK_CHECK = (True, ) + _CPU_MASK_CHECK
|
116 |
OPT_CPU_MASK_CHECK = (False, ) + _CPU_MASK_CHECK
|
117 |
REQ_MULTI_CPU_MASK_CHECK = (True, ) + _MULTI_CPU_MASK_CHECK
|
118 |
OPT_MULTI_CPU_MASK_CHECK = (False, ) + _MULTI_CPU_MASK_CHECK
|
119 |
REQ_NONNEGATIVE_INT_CHECK = (True, ) + _NONNEGATIVE_INT_CHECK
|
120 |
OPT_NONNEGATIVE_INT_CHECK = (False, ) + _NONNEGATIVE_INT_CHECK
|
121 |
|
122 |
# no checks at all
|
123 |
NO_CHECK = (False, None, None, None, None) |
124 |
|
125 |
# required, but no other checks
|
126 |
REQUIRED_CHECK = (True, None, None, None, None) |
127 |
|
128 |
# migration type
|
129 |
MIGRATION_MODE_CHECK = (True, lambda x: x in constants.HT_MIGRATION_MODES, |
130 |
"invalid migration mode", None, None) |
131 |
|
132 |
|
133 |
def ParamInSet(required, my_set): |
134 |
"""Builds parameter checker for set membership.
|
135 |
|
136 |
@type required: boolean
|
137 |
@param required: whether this is a required parameter
|
138 |
@type my_set: tuple, list or set
|
139 |
@param my_set: allowed values set
|
140 |
|
141 |
"""
|
142 |
fn = lambda x: x in my_set |
143 |
err = ("The value must be one of: %s" % utils.CommaJoin(my_set))
|
144 |
return (required, fn, err, None, None) |
145 |
|
146 |
|
147 |
class BaseHypervisor(object): |
148 |
"""Abstract virtualisation technology interface
|
149 |
|
150 |
The goal is that all aspects of the virtualisation technology are
|
151 |
abstracted away from the rest of code.
|
152 |
|
153 |
@cvar PARAMETERS: a dict of parameter name: check type; the check type is
|
154 |
a five-tuple containing:
|
155 |
- the required flag (boolean)
|
156 |
- a function to check for syntax, that will be used in
|
157 |
L{CheckParameterSyntax}, in the master daemon process
|
158 |
- an error message for the above function
|
159 |
- a function to check for parameter validity on the remote node,
|
160 |
in the L{ValidateParameters} function
|
161 |
- an error message for the above function
|
162 |
@type CAN_MIGRATE: boolean
|
163 |
@cvar CAN_MIGRATE: whether this hypervisor can do migration (either
|
164 |
live or non-live)
|
165 |
|
166 |
"""
|
167 |
PARAMETERS = {} |
168 |
ANCILLARY_FILES = [] |
169 |
ANCILLARY_FILES_OPT = [] |
170 |
CAN_MIGRATE = False
|
171 |
|
172 |
def __init__(self): |
173 |
pass
|
174 |
|
175 |
def StartInstance(self, instance, block_devices, startup_paused): |
176 |
"""Start an instance."""
|
177 |
raise NotImplementedError |
178 |
|
179 |
def StopInstance(self, instance, force=False, retry=False, name=None): |
180 |
"""Stop an instance
|
181 |
|
182 |
@type instance: L{objects.Instance}
|
183 |
@param instance: instance to stop
|
184 |
@type force: boolean
|
185 |
@param force: whether to do a "hard" stop (destroy)
|
186 |
@type retry: boolean
|
187 |
@param retry: whether this is just a retry call
|
188 |
@type name: string or None
|
189 |
@param name: if this parameter is passed, the the instance object
|
190 |
should not be used (will be passed as None), and the shutdown
|
191 |
must be done by name only
|
192 |
|
193 |
"""
|
194 |
raise NotImplementedError |
195 |
|
196 |
def CleanupInstance(self, instance_name): |
197 |
"""Cleanup after a stopped instance
|
198 |
|
199 |
This is an optional method, used by hypervisors that need to cleanup after
|
200 |
an instance has been stopped.
|
201 |
|
202 |
@type instance_name: string
|
203 |
@param instance_name: instance name to cleanup after
|
204 |
|
205 |
"""
|
206 |
pass
|
207 |
|
208 |
def RebootInstance(self, instance): |
209 |
"""Reboot an instance."""
|
210 |
raise NotImplementedError |
211 |
|
212 |
def ListInstances(self): |
213 |
"""Get the list of running instances."""
|
214 |
raise NotImplementedError |
215 |
|
216 |
def GetInstanceInfo(self, instance_name): |
217 |
"""Get instance properties.
|
218 |
|
219 |
@type instance_name: string
|
220 |
@param instance_name: the instance name
|
221 |
|
222 |
@return: tuple (name, id, memory, vcpus, state, times)
|
223 |
|
224 |
"""
|
225 |
raise NotImplementedError |
226 |
|
227 |
def GetAllInstancesInfo(self): |
228 |
"""Get properties of all instances.
|
229 |
|
230 |
@return: list of tuples (name, id, memory, vcpus, stat, times)
|
231 |
|
232 |
"""
|
233 |
raise NotImplementedError |
234 |
|
235 |
def GetNodeInfo(self): |
236 |
"""Return information about the node.
|
237 |
|
238 |
@return: a dict with the following keys (values in MiB):
|
239 |
- memory_total: the total memory size on the node
|
240 |
- memory_free: the available memory on the node for instances
|
241 |
- memory_dom0: the memory used by the node itself, if available
|
242 |
|
243 |
"""
|
244 |
raise NotImplementedError |
245 |
|
246 |
@classmethod
|
247 |
def GetInstanceConsole(cls, instance, hvparams, beparams): |
248 |
"""Return information for connecting to the console of an instance.
|
249 |
|
250 |
"""
|
251 |
raise NotImplementedError |
252 |
|
253 |
@classmethod
|
254 |
def GetAncillaryFiles(cls): |
255 |
"""Return a list of ancillary files to be copied to all nodes as ancillary
|
256 |
configuration files.
|
257 |
|
258 |
@rtype: (list of absolute paths, list of absolute paths)
|
259 |
@return: (all files, optional files)
|
260 |
|
261 |
"""
|
262 |
# By default we return a member variable, so that if an hypervisor has just
|
263 |
# a static list of files it doesn't have to override this function.
|
264 |
assert set(cls.ANCILLARY_FILES).issuperset(cls.ANCILLARY_FILES_OPT), \ |
265 |
"Optional ancillary files must be a subset of ancillary files"
|
266 |
|
267 |
return (cls.ANCILLARY_FILES, cls.ANCILLARY_FILES_OPT)
|
268 |
|
269 |
def Verify(self): |
270 |
"""Verify the hypervisor.
|
271 |
|
272 |
"""
|
273 |
raise NotImplementedError |
274 |
|
275 |
def MigrationInfo(self, instance): # pylint: disable=R0201,W0613 |
276 |
"""Get instance information to perform a migration.
|
277 |
|
278 |
By default assume no information is needed.
|
279 |
|
280 |
@type instance: L{objects.Instance}
|
281 |
@param instance: instance to be migrated
|
282 |
@rtype: string/data (opaque)
|
283 |
@return: instance migration information - serialized form
|
284 |
|
285 |
"""
|
286 |
return "" |
287 |
|
288 |
def AcceptInstance(self, instance, info, target): |
289 |
"""Prepare to accept an instance.
|
290 |
|
291 |
By default assume no preparation is needed.
|
292 |
|
293 |
@type instance: L{objects.Instance}
|
294 |
@param instance: instance to be accepted
|
295 |
@type info: string/data (opaque)
|
296 |
@param info: migration information, from the source node
|
297 |
@type target: string
|
298 |
@param target: target host (usually ip), on this node
|
299 |
|
300 |
"""
|
301 |
pass
|
302 |
|
303 |
def BalloonInstanceMemory(self, instance, mem): |
304 |
"""Balloon an instance memory to a certain value.
|
305 |
|
306 |
@type instance: L{objects.Instance}
|
307 |
@param instance: instance to be accepted
|
308 |
@type mem: int
|
309 |
@param mem: actual memory size to use for instance runtime
|
310 |
|
311 |
"""
|
312 |
raise NotImplementedError |
313 |
|
314 |
def FinalizeMigrationDst(self, instance, info, success): |
315 |
"""Finalize the instance migration on the target node.
|
316 |
|
317 |
Should finalize or revert any preparation done to accept the instance.
|
318 |
Since by default we do no preparation, we also don't have anything to do
|
319 |
|
320 |
@type instance: L{objects.Instance}
|
321 |
@param instance: instance whose migration is being finalized
|
322 |
@type info: string/data (opaque)
|
323 |
@param info: migration information, from the source node
|
324 |
@type success: boolean
|
325 |
@param success: whether the migration was a success or a failure
|
326 |
|
327 |
"""
|
328 |
pass
|
329 |
|
330 |
def MigrateInstance(self, instance, target, live): |
331 |
"""Migrate an instance.
|
332 |
|
333 |
@type instance: L{objects.Instance}
|
334 |
@param instance: the instance to be migrated
|
335 |
@type target: string
|
336 |
@param target: hostname (usually ip) of the target node
|
337 |
@type live: boolean
|
338 |
@param live: whether to do a live or non-live migration
|
339 |
|
340 |
"""
|
341 |
raise NotImplementedError |
342 |
|
343 |
def FinalizeMigrationSource(self, instance, success, live): |
344 |
"""Finalize the instance migration on the source node.
|
345 |
|
346 |
@type instance: L{objects.Instance}
|
347 |
@param instance: the instance that was migrated
|
348 |
@type success: bool
|
349 |
@param success: whether the migration succeeded or not
|
350 |
@type live: bool
|
351 |
@param live: whether the user requested a live migration or not
|
352 |
|
353 |
"""
|
354 |
pass
|
355 |
|
356 |
def GetMigrationStatus(self, instance): |
357 |
"""Get the migration status
|
358 |
|
359 |
@type instance: L{objects.Instance}
|
360 |
@param instance: the instance that is being migrated
|
361 |
@rtype: L{objects.MigrationStatus}
|
362 |
@return: the status of the current migration (one of
|
363 |
L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
|
364 |
progress info that can be retrieved from the hypervisor
|
365 |
|
366 |
"""
|
367 |
raise NotImplementedError |
368 |
|
369 |
def _InstanceStartupMemory(self, instance): |
370 |
"""Get the correct startup memory for an instance
|
371 |
|
372 |
This function calculates how much memory an instance should be started
|
373 |
with, making sure it's a value between the minimum and the maximum memory,
|
374 |
but also trying to use no more than the current free memory on the node.
|
375 |
|
376 |
@type instance: L{objects.Instance}
|
377 |
@param instance: the instance that is being started
|
378 |
@rtype: integer
|
379 |
@return: memory the instance should be started with
|
380 |
|
381 |
"""
|
382 |
free_memory = self.GetNodeInfo()["memory_free"] |
383 |
max_start_mem = min(instance.beparams[constants.BE_MAXMEM], free_memory)
|
384 |
start_mem = max(instance.beparams[constants.BE_MINMEM], max_start_mem)
|
385 |
return start_mem
|
386 |
|
387 |
@classmethod
|
388 |
def CheckParameterSyntax(cls, hvparams): |
389 |
"""Check the given parameters for validity.
|
390 |
|
391 |
This should check the passed set of parameters for
|
392 |
validity. Classes should extend, not replace, this function.
|
393 |
|
394 |
@type hvparams: dict
|
395 |
@param hvparams: dictionary with parameter names/value
|
396 |
@raise errors.HypervisorError: when a parameter is not valid
|
397 |
|
398 |
"""
|
399 |
for key in hvparams: |
400 |
if key not in cls.PARAMETERS: |
401 |
raise errors.HypervisorError("Parameter '%s' is not supported" % key) |
402 |
|
403 |
# cheap tests that run on the master, should not access the world
|
404 |
for name, (required, check_fn, errstr, _, _) in cls.PARAMETERS.items(): |
405 |
if name not in hvparams: |
406 |
raise errors.HypervisorError("Parameter '%s' is missing" % name) |
407 |
value = hvparams[name] |
408 |
if not required and not value: |
409 |
continue
|
410 |
if not value: |
411 |
raise errors.HypervisorError("Parameter '%s' is required but" |
412 |
" is currently not defined" % (name, ))
|
413 |
if check_fn is not None and not check_fn(value): |
414 |
raise errors.HypervisorError("Parameter '%s' fails syntax" |
415 |
" check: %s (current value: '%s')" %
|
416 |
(name, errstr, value)) |
417 |
|
418 |
@classmethod
|
419 |
def ValidateParameters(cls, hvparams): |
420 |
"""Check the given parameters for validity.
|
421 |
|
422 |
This should check the passed set of parameters for
|
423 |
validity. Classes should extend, not replace, this function.
|
424 |
|
425 |
@type hvparams: dict
|
426 |
@param hvparams: dictionary with parameter names/value
|
427 |
@raise errors.HypervisorError: when a parameter is not valid
|
428 |
|
429 |
"""
|
430 |
for name, (required, _, _, check_fn, errstr) in cls.PARAMETERS.items(): |
431 |
value = hvparams[name] |
432 |
if not required and not value: |
433 |
continue
|
434 |
if check_fn is not None and not check_fn(value): |
435 |
raise errors.HypervisorError("Parameter '%s' fails" |
436 |
" validation: %s (current value: '%s')" %
|
437 |
(name, errstr, value)) |
438 |
|
439 |
@classmethod
|
440 |
def PowercycleNode(cls): |
441 |
"""Hard powercycle a node using hypervisor specific methods.
|
442 |
|
443 |
This method should hard powercycle the node, using whatever
|
444 |
methods the hypervisor provides. Note that this means that all
|
445 |
instances running on the node must be stopped too.
|
446 |
|
447 |
"""
|
448 |
raise NotImplementedError |
449 |
|
450 |
@staticmethod
|
451 |
def GetLinuxNodeInfo(): |
452 |
"""For linux systems, return actual OS information.
|
453 |
|
454 |
This is an abstraction for all non-hypervisor-based classes, where
|
455 |
the node actually sees all the memory and CPUs via the /proc
|
456 |
interface and standard commands. The other case if for example
|
457 |
xen, where you only see the hardware resources via xen-specific
|
458 |
tools.
|
459 |
|
460 |
@return: a dict with the following keys (values in MiB):
|
461 |
- memory_total: the total memory size on the node
|
462 |
- memory_free: the available memory on the node for instances
|
463 |
- memory_dom0: the memory used by the node itself, if available
|
464 |
|
465 |
"""
|
466 |
try:
|
467 |
data = utils.ReadFile("/proc/meminfo").splitlines()
|
468 |
except EnvironmentError, err: |
469 |
raise errors.HypervisorError("Failed to list node info: %s" % (err,)) |
470 |
|
471 |
result = {} |
472 |
sum_free = 0
|
473 |
try:
|
474 |
for line in data: |
475 |
splitfields = line.split(":", 1) |
476 |
|
477 |
if len(splitfields) > 1: |
478 |
key = splitfields[0].strip()
|
479 |
val = splitfields[1].strip()
|
480 |
if key == "MemTotal": |
481 |
result["memory_total"] = int(val.split()[0]) / 1024 |
482 |
elif key in ("MemFree", "Buffers", "Cached"): |
483 |
sum_free += int(val.split()[0]) / 1024 |
484 |
elif key == "Active": |
485 |
result["memory_dom0"] = int(val.split()[0]) / 1024 |
486 |
except (ValueError, TypeError), err: |
487 |
raise errors.HypervisorError("Failed to compute memory usage: %s" % |
488 |
(err,)) |
489 |
result["memory_free"] = sum_free
|
490 |
|
491 |
cpu_total = 0
|
492 |
try:
|
493 |
fh = open("/proc/cpuinfo") |
494 |
try:
|
495 |
cpu_total = len(re.findall("(?m)^processor\s*:\s*[0-9]+\s*$", |
496 |
fh.read())) |
497 |
finally:
|
498 |
fh.close() |
499 |
except EnvironmentError, err: |
500 |
raise errors.HypervisorError("Failed to list node info: %s" % (err,)) |
501 |
result["cpu_total"] = cpu_total
|
502 |
# FIXME: export correct data here
|
503 |
result["cpu_nodes"] = 1 |
504 |
result["cpu_sockets"] = 1 |
505 |
|
506 |
return result
|
507 |
|
508 |
@classmethod
|
509 |
def LinuxPowercycle(cls): |
510 |
"""Linux-specific powercycle method.
|
511 |
|
512 |
"""
|
513 |
try:
|
514 |
fd = os.open("/proc/sysrq-trigger", os.O_WRONLY)
|
515 |
try:
|
516 |
os.write(fd, "b")
|
517 |
finally:
|
518 |
fd.close() |
519 |
except OSError: |
520 |
logging.exception("Can't open the sysrq-trigger file")
|
521 |
result = utils.RunCmd(["reboot", "-n", "-f"]) |
522 |
if not result: |
523 |
logging.error("Can't run shutdown: %s", result.output)
|