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