Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_base.py @ f28ec899

History | View | Annotate | Download (12.7 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 CleanupInstance(self, instance_name):
134
    """Cleanup after a stopped instance
135

136
    This is an optional method, used by hypervisors that need to cleanup after
137
    an instance has been stopped.
138

139
    @type instance_name: string
140
    @param instance_name: instance name to cleanup after
141

142
    """
143
    pass
144

    
145
  def RebootInstance(self, instance):
146
    """Reboot an instance."""
147
    raise NotImplementedError
148

    
149
  def ListInstances(self):
150
    """Get the list of running instances."""
151
    raise NotImplementedError
152

    
153
  def GetInstanceInfo(self, instance_name):
154
    """Get instance properties.
155

156
    @type instance_name: string
157
    @param instance_name: the instance name
158

159
    @return: tuple (name, id, memory, vcpus, state, times)
160

161
    """
162
    raise NotImplementedError
163

    
164
  def GetAllInstancesInfo(self):
165
    """Get properties of all instances.
166

167
    @return: list of tuples (name, id, memory, vcpus, stat, times)
168

169
    """
170
    raise NotImplementedError
171

    
172
  def GetNodeInfo(self):
173
    """Return information about the node.
174

175
    @return: a dict with the following keys (values in MiB):
176
          - memory_total: the total memory size on the node
177
          - memory_free: the available memory on the node for instances
178
          - memory_dom0: the memory used by the node itself, if available
179

180
    """
181
    raise NotImplementedError
182

    
183
  @classmethod
184
  def GetShellCommandForConsole(cls, instance, hvparams, beparams):
185
    """Return a command for connecting to the console of an instance.
186

187
    """
188
    raise NotImplementedError
189

    
190
  @classmethod
191
  def GetAncillaryFiles(cls):
192
    """Return a list of ancillary files to be copied to all nodes as ancillary
193
    configuration files.
194

195
    @rtype: list of strings
196
    @return: list of absolute paths of files to ship cluster-wide
197

198
    """
199
    # By default we return a member variable, so that if an hypervisor has just
200
    # a static list of files it doesn't have to override this function.
201
    return cls.ANCILLARY_FILES
202

    
203
  def Verify(self):
204
    """Verify the hypervisor.
205

206
    """
207
    raise NotImplementedError
208

    
209
  def MigrationInfo(self, instance): # pylint: disable-msg=R0201,W0613
210
    """Get instance information to perform a migration.
211

212
    By default assume no information is needed.
213

214
    @type instance: L{objects.Instance}
215
    @param instance: instance to be migrated
216
    @rtype: string/data (opaque)
217
    @return: instance migration information - serialized form
218

219
    """
220
    return ''
221

    
222
  def AcceptInstance(self, instance, info, target):
223
    """Prepare to accept an instance.
224

225
    By default assume no preparation is needed.
226

227
    @type instance: L{objects.Instance}
228
    @param instance: instance to be accepted
229
    @type info: string/data (opaque)
230
    @param info: migration information, from the source node
231
    @type target: string
232
    @param target: target host (usually ip), on this node
233

234
    """
235
    pass
236

    
237
  def FinalizeMigration(self, instance, info, success):
238
    """Finalized an instance migration.
239

240
    Should finalize or revert any preparation done to accept the instance.
241
    Since by default we do no preparation, we also don't have anything to do
242

243
    @type instance: L{objects.Instance}
244
    @param instance: instance whose migration is being aborted
245
    @type info: string/data (opaque)
246
    @param info: migration information, from the source node
247
    @type success: boolean
248
    @param success: whether the migration was a success or a failure
249

250
    """
251
    pass
252

    
253
  def MigrateInstance(self, instance, target, live):
254
    """Migrate an instance.
255

256
    @type instance: L{objects.Instance}
257
    @param instance: the instance to be migrated
258
    @type target: string
259
    @param target: hostname (usually ip) of the target node
260
    @type live: boolean
261
    @param live: whether to do a live or non-live migration
262

263
    """
264
    raise NotImplementedError
265

    
266
  @classmethod
267
  def CheckParameterSyntax(cls, hvparams):
268
    """Check the given parameters for validity.
269

270
    This should check the passed set of parameters for
271
    validity. Classes should extend, not replace, this function.
272

273
    @type hvparams:  dict
274
    @param hvparams: dictionary with parameter names/value
275
    @raise errors.HypervisorError: when a parameter is not valid
276

277
    """
278
    for key in hvparams:
279
      if key not in cls.PARAMETERS:
280
        raise errors.HypervisorError("Parameter '%s' is not supported" % key)
281

    
282
    # cheap tests that run on the master, should not access the world
283
    for name, (required, check_fn, errstr, _, _) in cls.PARAMETERS.items():
284
      if name not in hvparams:
285
        raise errors.HypervisorError("Parameter '%s' is missing" % name)
286
      value = hvparams[name]
287
      if not required and not value:
288
        continue
289
      if not value:
290
        raise errors.HypervisorError("Parameter '%s' is required but"
291
                                     " is currently not defined" % (name, ))
292
      if check_fn is not None and not check_fn(value):
293
        raise errors.HypervisorError("Parameter '%s' fails syntax"
294
                                     " check: %s (current value: '%s')" %
295
                                     (name, errstr, value))
296

    
297
  @classmethod
298
  def ValidateParameters(cls, hvparams):
299
    """Check the given parameters for validity.
300

301
    This should check the passed set of parameters for
302
    validity. Classes should extend, not replace, this function.
303

304
    @type hvparams:  dict
305
    @param hvparams: dictionary with parameter names/value
306
    @raise errors.HypervisorError: when a parameter is not valid
307

308
    """
309
    for name, (required, _, _, check_fn, errstr) in cls.PARAMETERS.items():
310
      value = hvparams[name]
311
      if not required and not value:
312
        continue
313
      if check_fn is not None and not check_fn(value):
314
        raise errors.HypervisorError("Parameter '%s' fails"
315
                                     " validation: %s (current value: '%s')" %
316
                                     (name, errstr, value))
317

    
318
  @classmethod
319
  def PowercycleNode(cls):
320
    """Hard powercycle a node using hypervisor specific methods.
321

322
    This method should hard powercycle the node, using whatever
323
    methods the hypervisor provides. Note that this means that all
324
    instances running on the node must be stopped too.
325

326
    """
327
    raise NotImplementedError
328

    
329
  @staticmethod
330
  def GetLinuxNodeInfo():
331
    """For linux systems, return actual OS information.
332

333
    This is an abstraction for all non-hypervisor-based classes, where
334
    the node actually sees all the memory and CPUs via the /proc
335
    interface and standard commands. The other case if for example
336
    xen, where you only see the hardware resources via xen-specific
337
    tools.
338

339
    @return: a dict with the following keys (values in MiB):
340
          - memory_total: the total memory size on the node
341
          - memory_free: the available memory on the node for instances
342
          - memory_dom0: the memory used by the node itself, if available
343

344
    """
345
    try:
346
      data = utils.ReadFile("/proc/meminfo").splitlines()
347
    except EnvironmentError, err:
348
      raise errors.HypervisorError("Failed to list node info: %s" % (err,))
349

    
350
    result = {}
351
    sum_free = 0
352
    try:
353
      for line in data:
354
        splitfields = line.split(":", 1)
355

    
356
        if len(splitfields) > 1:
357
          key = splitfields[0].strip()
358
          val = splitfields[1].strip()
359
          if key == 'MemTotal':
360
            result['memory_total'] = int(val.split()[0])/1024
361
          elif key in ('MemFree', 'Buffers', 'Cached'):
362
            sum_free += int(val.split()[0])/1024
363
          elif key == 'Active':
364
            result['memory_dom0'] = int(val.split()[0])/1024
365
    except (ValueError, TypeError), err:
366
      raise errors.HypervisorError("Failed to compute memory usage: %s" %
367
                                   (err,))
368
    result['memory_free'] = sum_free
369

    
370
    cpu_total = 0
371
    try:
372
      fh = open("/proc/cpuinfo")
373
      try:
374
        cpu_total = len(re.findall("(?m)^processor\s*:\s*[0-9]+\s*$",
375
                                   fh.read()))
376
      finally:
377
        fh.close()
378
    except EnvironmentError, err:
379
      raise errors.HypervisorError("Failed to list node info: %s" % (err,))
380
    result['cpu_total'] = cpu_total
381
    # FIXME: export correct data here
382
    result['cpu_nodes'] = 1
383
    result['cpu_sockets'] = 1
384

    
385
    return result
386

    
387
  @classmethod
388
  def LinuxPowercycle(cls):
389
    """Linux-specific powercycle method.
390

391
    """
392
    try:
393
      fd = os.open("/proc/sysrq-trigger", os.O_WRONLY)
394
      try:
395
        os.write(fd, "b")
396
      finally:
397
        fd.close()
398
    except OSError:
399
      logging.exception("Can't open the sysrq-trigger file")
400
      result = utils.RunCmd(["reboot", "-n", "-f"])
401
      if not result:
402
        logging.error("Can't run shutdown: %s", result.output)