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