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