4 # Copyright (C) 2006, 2007, 2008, 2009, 2010 Google Inc.
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.
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.
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
22 """Base class for all hypervisors
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}.
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
45 from ganeti import errors
46 from ganeti import utils
47 from ganeti import constants
50 def _IsCpuMaskWellFormed(cpu_mask):
52 cpu_list = utils.ParseCpuMask(cpu_mask)
53 except errors.ParseError, _:
55 return isinstance(cpu_list, list) and len(cpu_list) > 0
58 # Read the BaseHypervisor.PARAMETERS docstring for the syntax of the
62 _FILE_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
63 os.path.isfile, "not found or not a file")
66 _DIR_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
67 os.path.isdir, "not found or not a directory")
69 # CPU mask must be well-formed
70 # TODO: implement node level check for the CPU mask
71 _CPU_MASK_CHECK = (_IsCpuMaskWellFormed,
72 "CPU mask definition is not well-formed",
75 # Check for validity of port number
76 _NET_PORT_CHECK = (lambda x: 0 < x < 65535, "invalid port number",
79 # nice wrappers for users
80 REQ_FILE_CHECK = (True, ) + _FILE_CHECK
81 OPT_FILE_CHECK = (False, ) + _FILE_CHECK
82 REQ_DIR_CHECK = (True, ) + _DIR_CHECK
83 OPT_DIR_CHECK = (False, ) + _DIR_CHECK
84 REQ_NET_PORT_CHECK = (True, ) + _NET_PORT_CHECK
85 OPT_NET_PORT_CHECK = (False, ) + _NET_PORT_CHECK
86 REQ_CPU_MASK_CHECK = (True, ) + _CPU_MASK_CHECK
87 OPT_CPU_MASK_CHECK = (False, ) + _CPU_MASK_CHECK
90 NO_CHECK = (False, None, None, None, None)
92 # required, but no other checks
93 REQUIRED_CHECK = (True, None, None, None, None)
96 MIGRATION_MODE_CHECK = (True, lambda x: x in constants.HT_MIGRATION_MODES,
97 "invalid migration mode", None, None)
100 def ParamInSet(required, my_set):
101 """Builds parameter checker for set membership.
103 @type required: boolean
104 @param required: whether this is a required parameter
105 @type my_set: tuple, list or set
106 @param my_set: allowed values set
109 fn = lambda x: x in my_set
110 err = ("The value must be one of: %s" % utils.CommaJoin(my_set))
111 return (required, fn, err, None, None)
114 class BaseHypervisor(object):
115 """Abstract virtualisation technology interface
117 The goal is that all aspects of the virtualisation technology are
118 abstracted away from the rest of code.
120 @cvar PARAMETERS: a dict of parameter name: check type; the check type is
121 a five-tuple containing:
122 - the required flag (boolean)
123 - a function to check for syntax, that will be used in
124 L{CheckParameterSyntax}, in the master daemon process
125 - an error message for the above function
126 - a function to check for parameter validity on the remote node,
127 in the L{ValidateParameters} function
128 - an error message for the above function
129 @type CAN_MIGRATE: boolean
130 @cvar CAN_MIGRATE: whether this hypervisor can do migration (either
136 ANCILLARY_FILES_OPT = []
142 def StartInstance(self, instance, block_devices, startup_paused):
143 """Start an instance."""
144 raise NotImplementedError
146 def StopInstance(self, instance, force=False, retry=False, name=None):
149 @type instance: L{objects.Instance}
150 @param instance: instance to stop
152 @param force: whether to do a "hard" stop (destroy)
154 @param retry: whether this is just a retry call
155 @type name: string or None
156 @param name: if this parameter is passed, the the instance object
157 should not be used (will be passed as None), and the shutdown
158 must be done by name only
161 raise NotImplementedError
163 def CleanupInstance(self, instance_name):
164 """Cleanup after a stopped instance
166 This is an optional method, used by hypervisors that need to cleanup after
167 an instance has been stopped.
169 @type instance_name: string
170 @param instance_name: instance name to cleanup after
175 def RebootInstance(self, instance):
176 """Reboot an instance."""
177 raise NotImplementedError
179 def ListInstances(self):
180 """Get the list of running instances."""
181 raise NotImplementedError
183 def GetInstanceInfo(self, instance_name):
184 """Get instance properties.
186 @type instance_name: string
187 @param instance_name: the instance name
189 @return: tuple (name, id, memory, vcpus, state, times)
192 raise NotImplementedError
194 def GetAllInstancesInfo(self):
195 """Get properties of all instances.
197 @return: list of tuples (name, id, memory, vcpus, stat, times)
200 raise NotImplementedError
202 def GetNodeInfo(self):
203 """Return information about the node.
205 @return: a dict with the following keys (values in MiB):
206 - memory_total: the total memory size on the node
207 - memory_free: the available memory on the node for instances
208 - memory_dom0: the memory used by the node itself, if available
211 raise NotImplementedError
214 def GetInstanceConsole(cls, instance, hvparams, beparams):
215 """Return information for connecting to the console of an instance.
218 raise NotImplementedError
221 def GetAncillaryFiles(cls):
222 """Return a list of ancillary files to be copied to all nodes as ancillary
225 @rtype: (list of absolute paths, list of absolute paths)
226 @return: (all files, optional files)
229 # By default we return a member variable, so that if an hypervisor has just
230 # a static list of files it doesn't have to override this function.
231 assert set(cls.ANCILLARY_FILES).issuperset(cls.ANCILLARY_FILES_OPT), \
232 "Optional ancillary files must be a subset of ancillary files"
234 return (cls.ANCILLARY_FILES, cls.ANCILLARY_FILES_OPT)
237 """Verify the hypervisor.
240 raise NotImplementedError
242 def MigrationInfo(self, instance): # pylint: disable=R0201,W0613
243 """Get instance information to perform a migration.
245 By default assume no information is needed.
247 @type instance: L{objects.Instance}
248 @param instance: instance to be migrated
249 @rtype: string/data (opaque)
250 @return: instance migration information - serialized form
255 def AcceptInstance(self, instance, info, target):
256 """Prepare to accept an instance.
258 By default assume no preparation is needed.
260 @type instance: L{objects.Instance}
261 @param instance: instance to be accepted
262 @type info: string/data (opaque)
263 @param info: migration information, from the source node
265 @param target: target host (usually ip), on this node
270 def FinalizeMigration(self, instance, info, success):
271 """Finalized an instance migration.
273 Should finalize or revert any preparation done to accept the instance.
274 Since by default we do no preparation, we also don't have anything to do
276 @type instance: L{objects.Instance}
277 @param instance: instance whose migration is being finalized
278 @type info: string/data (opaque)
279 @param info: migration information, from the source node
280 @type success: boolean
281 @param success: whether the migration was a success or a failure
286 def MigrateInstance(self, instance, target, live):
287 """Migrate an instance.
289 @type instance: L{objects.Instance}
290 @param instance: the instance to be migrated
292 @param target: hostname (usually ip) of the target node
294 @param live: whether to do a live or non-live migration
297 raise NotImplementedError
300 def CheckParameterSyntax(cls, hvparams):
301 """Check the given parameters for validity.
303 This should check the passed set of parameters for
304 validity. Classes should extend, not replace, this function.
307 @param hvparams: dictionary with parameter names/value
308 @raise errors.HypervisorError: when a parameter is not valid
312 if key not in cls.PARAMETERS:
313 raise errors.HypervisorError("Parameter '%s' is not supported" % key)
315 # cheap tests that run on the master, should not access the world
316 for name, (required, check_fn, errstr, _, _) in cls.PARAMETERS.items():
317 if name not in hvparams:
318 raise errors.HypervisorError("Parameter '%s' is missing" % name)
319 value = hvparams[name]
320 if not required and not value:
323 raise errors.HypervisorError("Parameter '%s' is required but"
324 " is currently not defined" % (name, ))
325 if check_fn is not None and not check_fn(value):
326 raise errors.HypervisorError("Parameter '%s' fails syntax"
327 " check: %s (current value: '%s')" %
328 (name, errstr, value))
331 def ValidateParameters(cls, hvparams):
332 """Check the given parameters for validity.
334 This should check the passed set of parameters for
335 validity. Classes should extend, not replace, this function.
338 @param hvparams: dictionary with parameter names/value
339 @raise errors.HypervisorError: when a parameter is not valid
342 for name, (required, _, _, check_fn, errstr) in cls.PARAMETERS.items():
343 value = hvparams[name]
344 if not required and not value:
346 if check_fn is not None and not check_fn(value):
347 raise errors.HypervisorError("Parameter '%s' fails"
348 " validation: %s (current value: '%s')" %
349 (name, errstr, value))
352 def PowercycleNode(cls):
353 """Hard powercycle a node using hypervisor specific methods.
355 This method should hard powercycle the node, using whatever
356 methods the hypervisor provides. Note that this means that all
357 instances running on the node must be stopped too.
360 raise NotImplementedError
363 def GetLinuxNodeInfo():
364 """For linux systems, return actual OS information.
366 This is an abstraction for all non-hypervisor-based classes, where
367 the node actually sees all the memory and CPUs via the /proc
368 interface and standard commands. The other case if for example
369 xen, where you only see the hardware resources via xen-specific
372 @return: a dict with the following keys (values in MiB):
373 - memory_total: the total memory size on the node
374 - memory_free: the available memory on the node for instances
375 - memory_dom0: the memory used by the node itself, if available
379 data = utils.ReadFile("/proc/meminfo").splitlines()
380 except EnvironmentError, err:
381 raise errors.HypervisorError("Failed to list node info: %s" % (err,))
387 splitfields = line.split(":", 1)
389 if len(splitfields) > 1:
390 key = splitfields[0].strip()
391 val = splitfields[1].strip()
392 if key == "MemTotal":
393 result["memory_total"] = int(val.split()[0]) / 1024
394 elif key in ("MemFree", "Buffers", "Cached"):
395 sum_free += int(val.split()[0]) / 1024
396 elif key == "Active":
397 result["memory_dom0"] = int(val.split()[0]) / 1024
398 except (ValueError, TypeError), err:
399 raise errors.HypervisorError("Failed to compute memory usage: %s" %
401 result["memory_free"] = sum_free
405 fh = open("/proc/cpuinfo")
407 cpu_total = len(re.findall("(?m)^processor\s*:\s*[0-9]+\s*$",
411 except EnvironmentError, err:
412 raise errors.HypervisorError("Failed to list node info: %s" % (err,))
413 result["cpu_total"] = cpu_total
414 # FIXME: export correct data here
415 result["cpu_nodes"] = 1
416 result["cpu_sockets"] = 1
421 def LinuxPowercycle(cls):
422 """Linux-specific powercycle method.
426 fd = os.open("/proc/sysrq-trigger", os.O_WRONLY)
432 logging.exception("Can't open the sysrq-trigger file")
433 result = utils.RunCmd(["reboot", "-n", "-f"])
435 logging.error("Can't run shutdown: %s", result.output)