4 # Copyright (C) 2006, 2007, 2008 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
44 from ganeti import errors
45 from ganeti import utils
48 # Read the BaseHypervisor.PARAMETERS docstring for the syntax of the
52 _FILE_CHECK = (os.path.isabs, "must be an absolute path",
53 os.path.isfile, "not found or not a file")
56 _DIR_CHECK = (os.path.isabs, "must be an absolute path",
57 os.path.isdir, "not found or not a directory")
59 # nice wrappers for users
60 REQ_FILE_CHECK = (True, ) + _FILE_CHECK
61 OPT_FILE_CHECK = (False, ) + _FILE_CHECK
62 REQ_DIR_CHECK = (True, ) + _DIR_CHECK
63 OPT_DIR_CHECK = (False, ) + _DIR_CHECK
66 NO_CHECK = (False, None, None, None, None)
68 # required, but no other checks
69 REQUIRED_CHECK = (True, None, None, None, None)
71 def ParamInSet(required, my_set):
72 """Builds parameter checker for set membership.
74 @type required: boolean
75 @param required: whether this is a required parameter
76 @type my_set: tuple, list or set
77 @param my_set: allowed values set
80 fn = lambda x: x in my_set
81 err = ("The value must be one of: %s" % utils.CommaJoin(my_set))
82 return (required, fn, err, None, None)
85 class BaseHypervisor(object):
86 """Abstract virtualisation technology interface
88 The goal is that all aspects of the virtualisation technology are
89 abstracted away from the rest of code.
91 @cvar PARAMETERS: a dict of parameter name: check type; the check type is
92 a five-tuple containing:
93 - the required flag (boolean)
94 - a function to check for syntax, that will be used in
95 L{CheckParameterSyntax}, in the master daemon process
96 - an error message for the above function
97 - a function to check for parameter validity on the remote node,
98 in the L{ValidateParameters} function
99 - an error message for the above function
107 def StartInstance(self, instance, block_devices):
108 """Start an instance."""
109 raise NotImplementedError
111 def StopInstance(self, instance, force=False):
112 """Stop an instance."""
113 raise NotImplementedError
115 def RebootInstance(self, instance):
116 """Reboot an instance."""
117 raise NotImplementedError
119 def ListInstances(self):
120 """Get the list of running instances."""
121 raise NotImplementedError
123 def GetInstanceInfo(self, instance_name):
124 """Get instance properties.
126 @type instance_name: string
127 @param instance_name: the instance name
129 @return: tuple (name, id, memory, vcpus, state, times)
132 raise NotImplementedError
134 def GetAllInstancesInfo(self):
135 """Get properties of all instances.
137 @return: list of tuples (name, id, memory, vcpus, stat, times)
140 raise NotImplementedError
142 def GetNodeInfo(self):
143 """Return information about the node.
145 @return: a dict with the following keys (values in MiB):
146 - memory_total: the total memory size on the node
147 - memory_free: the available memory on the node for instances
148 - memory_dom0: the memory used by the node itself, if available
151 raise NotImplementedError
154 def GetShellCommandForConsole(cls, instance, hvparams, beparams):
155 """Return a command for connecting to the console of an instance.
158 raise NotImplementedError
161 """Verify the hypervisor.
164 raise NotImplementedError
166 def MigrationInfo(self, instance):
167 """Get instance information to perform a migration.
169 By default assume no information is needed.
171 @type instance: L{objects.Instance}
172 @param instance: instance to be migrated
173 @rtype: string/data (opaque)
174 @return: instance migration information - serialized form
179 def AcceptInstance(self, instance, info, target):
180 """Prepare to accept an instance.
182 By default assume no preparation is needed.
184 @type instance: L{objects.Instance}
185 @param instance: instance to be accepted
186 @type info: string/data (opaque)
187 @param info: migration information, from the source node
189 @param target: target host (usually ip), on this node
194 def FinalizeMigration(self, instance, info, success):
195 """Finalized an instance migration.
197 Should finalize or revert any preparation done to accept the instance.
198 Since by default we do no preparation, we also don't have anything to do
200 @type instance: L{objects.Instance}
201 @param instance: instance whose migration is being aborted
202 @type info: string/data (opaque)
203 @param info: migration information, from the source node
204 @type success: boolean
205 @param success: whether the migration was a success or a failure
210 def MigrateInstance(self, name, target, live):
211 """Migrate an instance.
214 @param name: name of the instance to be migrated
216 @param target: hostname (usually ip) of the target node
218 @param live: whether to do a live or non-live migration
221 raise NotImplementedError
224 def CheckParameterSyntax(cls, hvparams):
225 """Check the given parameters for validity.
227 This should check the passed set of parameters for
228 validity. Classes should extend, not replace, this function.
231 @param hvparams: dictionary with parameter names/value
232 @raise errors.HypervisorError: when a parameter is not valid
236 if key not in cls.PARAMETERS:
237 raise errors.HypervisorError("Parameter '%s' is not supported" % key)
239 # cheap tests that run on the master, should not access the world
240 for name, (required, check_fn, errstr, _, _) in cls.PARAMETERS.items():
241 if name not in hvparams:
242 raise errors.HypervisorError("Parameter '%s' is missing" % name)
243 value = hvparams[name]
244 if not required and not value:
247 raise errors.HypervisorError("Parameter '%s' is required but"
248 " is currently not defined" % (name, ))
249 if check_fn is not None and not check_fn(value):
250 raise errors.HypervisorError("Parameter '%s' fails syntax"
251 " check: %s (current value: '%s')" %
252 (name, errstr, value))
255 def ValidateParameters(cls, hvparams):
256 """Check the given parameters for validity.
258 This should check the passed set of parameters for
259 validity. Classes should extend, not replace, this function.
262 @param hvparams: dictionary with parameter names/value
263 @raise errors.HypervisorError: when a parameter is not valid
266 for name, (required, _, _, check_fn, errstr) in cls.PARAMETERS.items():
267 value = hvparams[name]
268 if not required and not value:
270 if check_fn is not None and not check_fn(value):
271 raise errors.HypervisorError("Parameter '%s' fails"
272 " validation: %s (current value: '%s')" %
273 (name, errstr, value))
275 def GetLinuxNodeInfo(self):
276 """For linux systems, return actual OS information.
278 This is an abstraction for all non-hypervisor-based classes, where
279 the node actually sees all the memory and CPUs via the /proc
280 interface and standard commands. The other case if for example
281 xen, where you only see the hardware resources via xen-specific
284 @return: a dict with the following keys (values in MiB):
285 - memory_total: the total memory size on the node
286 - memory_free: the available memory on the node for instances
287 - memory_dom0: the memory used by the node itself, if available
291 fh = file("/proc/meminfo")
293 data = fh.readlines()
296 except EnvironmentError, err:
297 raise errors.HypervisorError("Failed to list node info: %s" % (err,))
303 splitfields = line.split(":", 1)
305 if len(splitfields) > 1:
306 key = splitfields[0].strip()
307 val = splitfields[1].strip()
308 if key == 'MemTotal':
309 result['memory_total'] = int(val.split()[0])/1024
310 elif key in ('MemFree', 'Buffers', 'Cached'):
311 sum_free += int(val.split()[0])/1024
312 elif key == 'Active':
313 result['memory_dom0'] = int(val.split()[0])/1024
314 except (ValueError, TypeError), err:
315 raise errors.HypervisorError("Failed to compute memory usage: %s" %
317 result['memory_free'] = sum_free
321 fh = open("/proc/cpuinfo")
323 cpu_total = len(re.findall("(?m)^processor\s*:\s*[0-9]+\s*$",
327 except EnvironmentError, err:
328 raise errors.HypervisorError("Failed to list node info: %s" % (err,))
329 result['cpu_total'] = cpu_total
330 # FIXME: export correct data here
331 result['cpu_nodes'] = 1
332 result['cpu_sockets'] = 1