Move to data-based hvparam checks instead of code
[ganeti-local] / lib / hypervisor / hv_base.py
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
43
44 from ganeti import errors
45 from ganeti import utils
46
47
48 # Read the BaseHypervisor.PARAMETERS docstring for the syntax of the
49 # _CHECK values
50
51 # must be afile
52 _FILE_CHECK = (os.path.isabs, "must be an absolute path",
53               os.path.isfile, "not found or not a file")
54
55 # must be a directory
56 _DIR_CHECK = (os.path.isabs, "must be an absolute path",
57              os.path.isdir, "not found or not a directory")
58
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
64
65 # no checks at all
66 NO_CHECK = (False, None, None, None, None)
67
68 # required, but no other checks
69 REQUIRED_CHECK = (True, None, None, None, None)
70
71 def ParamInSet(required, my_set):
72   """Builds parameter checker for set membership.
73
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
78
79   """
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)
83
84
85 class BaseHypervisor(object):
86   """Abstract virtualisation technology interface
87
88   The goal is that all aspects of the virtualisation technology are
89   abstracted away from the rest of code.
90
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
100
101   """
102   PARAMETERS = {}
103
104   def __init__(self):
105     pass
106
107   def StartInstance(self, instance, block_devices):
108     """Start an instance."""
109     raise NotImplementedError
110
111   def StopInstance(self, instance, force=False):
112     """Stop an instance."""
113     raise NotImplementedError
114
115   def RebootInstance(self, instance):
116     """Reboot an instance."""
117     raise NotImplementedError
118
119   def ListInstances(self):
120     """Get the list of running instances."""
121     raise NotImplementedError
122
123   def GetInstanceInfo(self, instance_name):
124     """Get instance properties.
125
126     @type instance_name: string
127     @param instance_name: the instance name
128
129     @return: tuple (name, id, memory, vcpus, state, times)
130
131     """
132     raise NotImplementedError
133
134   def GetAllInstancesInfo(self):
135     """Get properties of all instances.
136
137     @return: list of tuples (name, id, memory, vcpus, stat, times)
138
139     """
140     raise NotImplementedError
141
142   def GetNodeInfo(self):
143     """Return information about the node.
144
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
149
150     """
151     raise NotImplementedError
152
153   @classmethod
154   def GetShellCommandForConsole(cls, instance, hvparams, beparams):
155     """Return a command for connecting to the console of an instance.
156
157     """
158     raise NotImplementedError
159
160   def Verify(self):
161     """Verify the hypervisor.
162
163     """
164     raise NotImplementedError
165
166   def MigrationInfo(self, instance):
167     """Get instance information to perform a migration.
168
169     By default assume no information is needed.
170
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
175
176     """
177     return ''
178
179   def AcceptInstance(self, instance, info, target):
180     """Prepare to accept an instance.
181
182     By default assume no preparation is needed.
183
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
188     @type target: string
189     @param target: target host (usually ip), on this node
190
191     """
192     pass
193
194   def FinalizeMigration(self, instance, info, success):
195     """Finalized an instance migration.
196
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
199
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
206
207     """
208     pass
209
210   def MigrateInstance(self, name, target, live):
211     """Migrate an instance.
212
213     @type name: string
214     @param name: name of the instance to be migrated
215     @type target: string
216     @param target: hostname (usually ip) of the target node
217     @type live: boolean
218     @param live: whether to do a live or non-live migration
219
220     """
221     raise NotImplementedError
222
223   @classmethod
224   def CheckParameterSyntax(cls, hvparams):
225     """Check the given parameters for validity.
226
227     This should check the passed set of parameters for
228     validity. Classes should extend, not replace, this function.
229
230     @type hvparams:  dict
231     @param hvparams: dictionary with parameter names/value
232     @raise errors.HypervisorError: when a parameter is not valid
233
234     """
235     for key in hvparams:
236       if key not in cls.PARAMETERS:
237         raise errors.HypervisorError("Parameter '%s' is not supported" % key)
238
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:
245         continue
246       if 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))
253
254   @classmethod
255   def ValidateParameters(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 name, (required, _, _, check_fn, errstr) in cls.PARAMETERS.items():
267       value = hvparams[name]
268       if not required and not value:
269         continue
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))
274
275   def GetLinuxNodeInfo(self):
276     """For linux systems, return actual OS information.
277
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
282     tools.
283
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
288
289     """
290     try:
291       fh = file("/proc/meminfo")
292       try:
293         data = fh.readlines()
294       finally:
295         fh.close()
296     except EnvironmentError, err:
297       raise errors.HypervisorError("Failed to list node info: %s" % (err,))
298
299     result = {}
300     sum_free = 0
301     try:
302       for line in data:
303         splitfields = line.split(":", 1)
304
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" %
316                                    (err,))
317     result['memory_free'] = sum_free
318
319     cpu_total = 0
320     try:
321       fh = open("/proc/cpuinfo")
322       try:
323         cpu_total = len(re.findall("(?m)^processor\s*:\s*[0-9]+\s*$",
324                                    fh.read()))
325       finally:
326         fh.close()
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
333
334     return result