Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_base.py @ 6a1434d7

History | View | Annotate | Download (15.3 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010 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
from ganeti import constants
48

    
49

    
50
def _IsCpuMaskWellFormed(cpu_mask):
51
  """Verifies if the given single CPU mask is valid
52

53
  The single CPU mask should be in the form "a,b,c,d", where each
54
  letter is a positive number or range.
55

56
  """
57
  try:
58
    cpu_list = utils.ParseCpuMask(cpu_mask)
59
  except errors.ParseError, _:
60
    return False
61
  return isinstance(cpu_list, list) and len(cpu_list) > 0
62

    
63

    
64
def _IsMultiCpuMaskWellFormed(cpu_mask):
65
  """Verifies if the given multiple CPU mask is valid
66

67
  A valid multiple CPU mask is in the form "a:b:c:d", where each
68
  letter is a single CPU mask.
69

70
  """
71
  try:
72
    utils.ParseMultiCpuMask(cpu_mask)
73
  except errors.ParseError, _:
74
    return False
75

    
76
  return True
77

    
78

    
79
# Read the BaseHypervisor.PARAMETERS docstring for the syntax of the
80
# _CHECK values
81

    
82
# must be afile
83
_FILE_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
84
              os.path.isfile, "not found or not a file")
85

    
86
# must be a directory
87
_DIR_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
88
             os.path.isdir, "not found or not a directory")
89

    
90
# CPU mask must be well-formed
91
# TODO: implement node level check for the CPU mask
92
_CPU_MASK_CHECK = (_IsCpuMaskWellFormed,
93
                   "CPU mask definition is not well-formed",
94
                   None, None)
95

    
96
# Multiple CPU mask must be well-formed
97
_MULTI_CPU_MASK_CHECK = (_IsMultiCpuMaskWellFormed,
98
                         "Multiple CPU mask definition is not well-formed",
99
                         None, None)
100

    
101
# Check for validity of port number
102
_NET_PORT_CHECK = (lambda x: 0 < x < 65535, "invalid port number",
103
                   None, None)
104

    
105
# nice wrappers for users
106
REQ_FILE_CHECK = (True, ) + _FILE_CHECK
107
OPT_FILE_CHECK = (False, ) + _FILE_CHECK
108
REQ_DIR_CHECK = (True, ) + _DIR_CHECK
109
OPT_DIR_CHECK = (False, ) + _DIR_CHECK
110
REQ_NET_PORT_CHECK = (True, ) + _NET_PORT_CHECK
111
OPT_NET_PORT_CHECK = (False, ) + _NET_PORT_CHECK
112
REQ_CPU_MASK_CHECK = (True, ) + _CPU_MASK_CHECK
113
OPT_CPU_MASK_CHECK = (False, ) + _CPU_MASK_CHECK
114
REQ_MULTI_CPU_MASK_CHECK = (True, ) + _MULTI_CPU_MASK_CHECK
115
OPT_MULTI_CPU_MASK_CHECK = (False, ) + _MULTI_CPU_MASK_CHECK
116

    
117
# no checks at all
118
NO_CHECK = (False, None, None, None, None)
119

    
120
# required, but no other checks
121
REQUIRED_CHECK = (True, None, None, None, None)
122

    
123
# migration type
124
MIGRATION_MODE_CHECK = (True, lambda x: x in constants.HT_MIGRATION_MODES,
125
                        "invalid migration mode", None, None)
126

    
127

    
128
def ParamInSet(required, my_set):
129
  """Builds parameter checker for set membership.
130

131
  @type required: boolean
132
  @param required: whether this is a required parameter
133
  @type my_set: tuple, list or set
134
  @param my_set: allowed values set
135

136
  """
137
  fn = lambda x: x in my_set
138
  err = ("The value must be one of: %s" % utils.CommaJoin(my_set))
139
  return (required, fn, err, None, None)
140

    
141

    
142
class BaseHypervisor(object):
143
  """Abstract virtualisation technology interface
144

145
  The goal is that all aspects of the virtualisation technology are
146
  abstracted away from the rest of code.
147

148
  @cvar PARAMETERS: a dict of parameter name: check type; the check type is
149
      a five-tuple containing:
150
          - the required flag (boolean)
151
          - a function to check for syntax, that will be used in
152
            L{CheckParameterSyntax}, in the master daemon process
153
          - an error message for the above function
154
          - a function to check for parameter validity on the remote node,
155
            in the L{ValidateParameters} function
156
          - an error message for the above function
157
  @type CAN_MIGRATE: boolean
158
  @cvar CAN_MIGRATE: whether this hypervisor can do migration (either
159
      live or non-live)
160

161
  """
162
  PARAMETERS = {}
163
  ANCILLARY_FILES = []
164
  CAN_MIGRATE = False
165

    
166
  def __init__(self):
167
    pass
168

    
169
  def StartInstance(self, instance, block_devices, startup_paused):
170
    """Start an instance."""
171
    raise NotImplementedError
172

    
173
  def StopInstance(self, instance, force=False, retry=False, name=None):
174
    """Stop an instance
175

176
    @type instance: L{objects.Instance}
177
    @param instance: instance to stop
178
    @type force: boolean
179
    @param force: whether to do a "hard" stop (destroy)
180
    @type retry: boolean
181
    @param retry: whether this is just a retry call
182
    @type name: string or None
183
    @param name: if this parameter is passed, the the instance object
184
        should not be used (will be passed as None), and the shutdown
185
        must be done by name only
186

187
    """
188
    raise NotImplementedError
189

    
190
  def CleanupInstance(self, instance_name):
191
    """Cleanup after a stopped instance
192

193
    This is an optional method, used by hypervisors that need to cleanup after
194
    an instance has been stopped.
195

196
    @type instance_name: string
197
    @param instance_name: instance name to cleanup after
198

199
    """
200
    pass
201

    
202
  def RebootInstance(self, instance):
203
    """Reboot an instance."""
204
    raise NotImplementedError
205

    
206
  def ListInstances(self):
207
    """Get the list of running instances."""
208
    raise NotImplementedError
209

    
210
  def GetInstanceInfo(self, instance_name):
211
    """Get instance properties.
212

213
    @type instance_name: string
214
    @param instance_name: the instance name
215

216
    @return: tuple (name, id, memory, vcpus, state, times)
217

218
    """
219
    raise NotImplementedError
220

    
221
  def GetAllInstancesInfo(self):
222
    """Get properties of all instances.
223

224
    @return: list of tuples (name, id, memory, vcpus, stat, times)
225

226
    """
227
    raise NotImplementedError
228

    
229
  def GetNodeInfo(self):
230
    """Return information about the node.
231

232
    @return: a dict with the following keys (values in MiB):
233
          - memory_total: the total memory size on the node
234
          - memory_free: the available memory on the node for instances
235
          - memory_dom0: the memory used by the node itself, if available
236

237
    """
238
    raise NotImplementedError
239

    
240
  @classmethod
241
  def GetInstanceConsole(cls, instance, hvparams, beparams):
242
    """Return information for connecting to the console of an instance.
243

244
    """
245
    raise NotImplementedError
246

    
247
  @classmethod
248
  def GetAncillaryFiles(cls):
249
    """Return a list of ancillary files to be copied to all nodes as ancillary
250
    configuration files.
251

252
    @rtype: list of strings
253
    @return: list of absolute paths of files to ship cluster-wide
254

255
    """
256
    # By default we return a member variable, so that if an hypervisor has just
257
    # a static list of files it doesn't have to override this function.
258
    return cls.ANCILLARY_FILES
259

    
260
  def Verify(self):
261
    """Verify the hypervisor.
262

263
    """
264
    raise NotImplementedError
265

    
266
  def MigrationInfo(self, instance): # pylint: disable=R0201,W0613
267
    """Get instance information to perform a migration.
268

269
    By default assume no information is needed.
270

271
    @type instance: L{objects.Instance}
272
    @param instance: instance to be migrated
273
    @rtype: string/data (opaque)
274
    @return: instance migration information - serialized form
275

276
    """
277
    return ""
278

    
279
  def AcceptInstance(self, instance, info, target):
280
    """Prepare to accept an instance.
281

282
    By default assume no preparation is needed.
283

284
    @type instance: L{objects.Instance}
285
    @param instance: instance to be accepted
286
    @type info: string/data (opaque)
287
    @param info: migration information, from the source node
288
    @type target: string
289
    @param target: target host (usually ip), on this node
290

291
    """
292
    pass
293

    
294
  def FinalizeMigrationDst(self, instance, info, success):
295
    """Finalize the instance migration on the target node.
296

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

300
    @type instance: L{objects.Instance}
301
    @param instance: instance whose migration is being finalized
302
    @type info: string/data (opaque)
303
    @param info: migration information, from the source node
304
    @type success: boolean
305
    @param success: whether the migration was a success or a failure
306

307
    """
308
    pass
309

    
310
  def MigrateInstance(self, instance, target, live):
311
    """Migrate an instance.
312

313
    @type instance: L{objects.Instance}
314
    @param instance: the instance to be migrated
315
    @type target: string
316
    @param target: hostname (usually ip) of the target node
317
    @type live: boolean
318
    @param live: whether to do a live or non-live migration
319

320
    """
321
    raise NotImplementedError
322

    
323
  def FinalizeMigrationSource(self, instance, success, live):
324
    """Finalize the instance migration on the source node.
325

326
    @type instance: L{objects.Instance}
327
    @param instance: the instance that was migrated
328
    @type success: bool
329
    @param success: whether the migration succeeded or not
330
    @type live: bool
331
    @param live: whether the user requested a live migration or not
332

333
    """
334
    pass
335

    
336
  def GetMigrationStatus(self, instance):
337
    """Get the migration status
338

339
    @type instance: L{objects.Instance}
340
    @param instance: the instance that is being migrated
341
    @rtype: L{objects.MigrationStatus}
342
    @return: the status of the current migration (one of
343
             L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
344
             progress info that can be retrieved from the hypervisor
345

346
    """
347
    raise NotImplementedError
348

    
349
  @classmethod
350
  def CheckParameterSyntax(cls, hvparams):
351
    """Check the given parameters for validity.
352

353
    This should check the passed set of parameters for
354
    validity. Classes should extend, not replace, this function.
355

356
    @type hvparams:  dict
357
    @param hvparams: dictionary with parameter names/value
358
    @raise errors.HypervisorError: when a parameter is not valid
359

360
    """
361
    for key in hvparams:
362
      if key not in cls.PARAMETERS:
363
        raise errors.HypervisorError("Parameter '%s' is not supported" % key)
364

    
365
    # cheap tests that run on the master, should not access the world
366
    for name, (required, check_fn, errstr, _, _) in cls.PARAMETERS.items():
367
      if name not in hvparams:
368
        raise errors.HypervisorError("Parameter '%s' is missing" % name)
369
      value = hvparams[name]
370
      if not required and not value:
371
        continue
372
      if not value:
373
        raise errors.HypervisorError("Parameter '%s' is required but"
374
                                     " is currently not defined" % (name, ))
375
      if check_fn is not None and not check_fn(value):
376
        raise errors.HypervisorError("Parameter '%s' fails syntax"
377
                                     " check: %s (current value: '%s')" %
378
                                     (name, errstr, value))
379

    
380
  @classmethod
381
  def ValidateParameters(cls, hvparams):
382
    """Check the given parameters for validity.
383

384
    This should check the passed set of parameters for
385
    validity. Classes should extend, not replace, this function.
386

387
    @type hvparams:  dict
388
    @param hvparams: dictionary with parameter names/value
389
    @raise errors.HypervisorError: when a parameter is not valid
390

391
    """
392
    for name, (required, _, _, check_fn, errstr) in cls.PARAMETERS.items():
393
      value = hvparams[name]
394
      if not required and not value:
395
        continue
396
      if check_fn is not None and not check_fn(value):
397
        raise errors.HypervisorError("Parameter '%s' fails"
398
                                     " validation: %s (current value: '%s')" %
399
                                     (name, errstr, value))
400

    
401
  @classmethod
402
  def PowercycleNode(cls):
403
    """Hard powercycle a node using hypervisor specific methods.
404

405
    This method should hard powercycle the node, using whatever
406
    methods the hypervisor provides. Note that this means that all
407
    instances running on the node must be stopped too.
408

409
    """
410
    raise NotImplementedError
411

    
412
  @staticmethod
413
  def GetLinuxNodeInfo():
414
    """For linux systems, return actual OS information.
415

416
    This is an abstraction for all non-hypervisor-based classes, where
417
    the node actually sees all the memory and CPUs via the /proc
418
    interface and standard commands. The other case if for example
419
    xen, where you only see the hardware resources via xen-specific
420
    tools.
421

422
    @return: a dict with the following keys (values in MiB):
423
          - memory_total: the total memory size on the node
424
          - memory_free: the available memory on the node for instances
425
          - memory_dom0: the memory used by the node itself, if available
426

427
    """
428
    try:
429
      data = utils.ReadFile("/proc/meminfo").splitlines()
430
    except EnvironmentError, err:
431
      raise errors.HypervisorError("Failed to list node info: %s" % (err,))
432

    
433
    result = {}
434
    sum_free = 0
435
    try:
436
      for line in data:
437
        splitfields = line.split(":", 1)
438

    
439
        if len(splitfields) > 1:
440
          key = splitfields[0].strip()
441
          val = splitfields[1].strip()
442
          if key == "MemTotal":
443
            result["memory_total"] = int(val.split()[0]) / 1024
444
          elif key in ("MemFree", "Buffers", "Cached"):
445
            sum_free += int(val.split()[0]) / 1024
446
          elif key == "Active":
447
            result["memory_dom0"] = int(val.split()[0]) / 1024
448
    except (ValueError, TypeError), err:
449
      raise errors.HypervisorError("Failed to compute memory usage: %s" %
450
                                   (err,))
451
    result["memory_free"] = sum_free
452

    
453
    cpu_total = 0
454
    try:
455
      fh = open("/proc/cpuinfo")
456
      try:
457
        cpu_total = len(re.findall("(?m)^processor\s*:\s*[0-9]+\s*$",
458
                                   fh.read()))
459
      finally:
460
        fh.close()
461
    except EnvironmentError, err:
462
      raise errors.HypervisorError("Failed to list node info: %s" % (err,))
463
    result["cpu_total"] = cpu_total
464
    # FIXME: export correct data here
465
    result["cpu_nodes"] = 1
466
    result["cpu_sockets"] = 1
467

    
468
    return result
469

    
470
  @classmethod
471
  def LinuxPowercycle(cls):
472
    """Linux-specific powercycle method.
473

474
    """
475
    try:
476
      fd = os.open("/proc/sysrq-trigger", os.O_WRONLY)
477
      try:
478
        os.write(fd, "b")
479
      finally:
480
        fd.close()
481
    except OSError:
482
      logging.exception("Can't open the sysrq-trigger file")
483
      result = utils.RunCmd(["reboot", "-n", "-f"])
484
      if not result:
485
        logging.error("Can't run shutdown: %s", result.output)