Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_base.py @ 0200a1af

History | View | Annotate | Download (17.6 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2012, 2013 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
# Check that an integer is non negative
106
_NONNEGATIVE_INT_CHECK = (lambda x: x >= 0, "cannot be negative", None, None)
107

    
108
# nice wrappers for users
109
REQ_FILE_CHECK = (True, ) + _FILE_CHECK
110
OPT_FILE_CHECK = (False, ) + _FILE_CHECK
111
REQ_DIR_CHECK = (True, ) + _DIR_CHECK
112
OPT_DIR_CHECK = (False, ) + _DIR_CHECK
113
REQ_NET_PORT_CHECK = (True, ) + _NET_PORT_CHECK
114
OPT_NET_PORT_CHECK = (False, ) + _NET_PORT_CHECK
115
REQ_CPU_MASK_CHECK = (True, ) + _CPU_MASK_CHECK
116
OPT_CPU_MASK_CHECK = (False, ) + _CPU_MASK_CHECK
117
REQ_MULTI_CPU_MASK_CHECK = (True, ) + _MULTI_CPU_MASK_CHECK
118
OPT_MULTI_CPU_MASK_CHECK = (False, ) + _MULTI_CPU_MASK_CHECK
119
REQ_NONNEGATIVE_INT_CHECK = (True, ) + _NONNEGATIVE_INT_CHECK
120
OPT_NONNEGATIVE_INT_CHECK = (False, ) + _NONNEGATIVE_INT_CHECK
121

    
122
# no checks at all
123
NO_CHECK = (False, None, None, None, None)
124

    
125
# required, but no other checks
126
REQUIRED_CHECK = (True, None, None, None, None)
127

    
128
# migration type
129
MIGRATION_MODE_CHECK = (True, lambda x: x in constants.HT_MIGRATION_MODES,
130
                        "invalid migration mode", None, None)
131

    
132

    
133
def ParamInSet(required, my_set):
134
  """Builds parameter checker for set membership.
135

136
  @type required: boolean
137
  @param required: whether this is a required parameter
138
  @type my_set: tuple, list or set
139
  @param my_set: allowed values set
140

141
  """
142
  fn = lambda x: x in my_set
143
  err = ("The value must be one of: %s" % utils.CommaJoin(my_set))
144
  return (required, fn, err, None, None)
145

    
146

    
147
class BaseHypervisor(object):
148
  """Abstract virtualisation technology interface
149

150
  The goal is that all aspects of the virtualisation technology are
151
  abstracted away from the rest of code.
152

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

166
  """
167
  PARAMETERS = {}
168
  ANCILLARY_FILES = []
169
  ANCILLARY_FILES_OPT = []
170
  CAN_MIGRATE = False
171

    
172
  def StartInstance(self, instance, block_devices, startup_paused):
173
    """Start an instance."""
174
    raise NotImplementedError
175

    
176
  def StopInstance(self, instance, force=False, retry=False, name=None):
177
    """Stop an instance
178

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

190
    """
191
    raise NotImplementedError
192

    
193
  def CleanupInstance(self, instance_name):
194
    """Cleanup after a stopped instance
195

196
    This is an optional method, used by hypervisors that need to cleanup after
197
    an instance has been stopped.
198

199
    @type instance_name: string
200
    @param instance_name: instance name to cleanup after
201

202
    """
203
    pass
204

    
205
  def RebootInstance(self, instance):
206
    """Reboot an instance."""
207
    raise NotImplementedError
208

    
209
  def ListInstances(self, hvparams=None):
210
    """Get the list of running instances."""
211
    raise NotImplementedError
212

    
213
  def GetInstanceInfo(self, instance_name, hvparams=None):
214
    """Get instance properties.
215

216
    @type instance_name: string
217
    @param instance_name: the instance name
218
    @type hvparams: dict of strings
219
    @param hvparams: hvparams to be used with this instance
220

221
    @return: tuple (name, id, memory, vcpus, state, times)
222

223
    """
224
    raise NotImplementedError
225

    
226
  def GetAllInstancesInfo(self, hvparams=None):
227
    """Get properties of all instances.
228

229
    @type hvparams: dict of strings
230
    @param hvparams: hypervisor parameter
231
    @return: list of tuples (name, id, memory, vcpus, stat, times)
232

233
    """
234
    raise NotImplementedError
235

    
236
  def GetNodeInfo(self, hvparams=None):
237
    """Return information about the node.
238

239
    @type hvparams: dict of strings
240
    @param hvparams: hypervisor parameters
241

242
    @return: a dict with the following keys (values in MiB):
243
          - memory_total: the total memory size on the node
244
          - memory_free: the available memory on the node for instances
245
          - memory_dom0: the memory used by the node itself, if available
246

247
    """
248
    raise NotImplementedError
249

    
250
  @classmethod
251
  def GetInstanceConsole(cls, instance, hvparams, beparams):
252
    """Return information for connecting to the console of an instance.
253

254
    """
255
    raise NotImplementedError
256

    
257
  @classmethod
258
  def GetAncillaryFiles(cls):
259
    """Return a list of ancillary files to be copied to all nodes as ancillary
260
    configuration files.
261

262
    @rtype: (list of absolute paths, list of absolute paths)
263
    @return: (all files, optional files)
264

265
    """
266
    # By default we return a member variable, so that if an hypervisor has just
267
    # a static list of files it doesn't have to override this function.
268
    assert set(cls.ANCILLARY_FILES).issuperset(cls.ANCILLARY_FILES_OPT), \
269
      "Optional ancillary files must be a subset of ancillary files"
270

    
271
    return (cls.ANCILLARY_FILES, cls.ANCILLARY_FILES_OPT)
272

    
273
  def Verify(self, hvparams=None):
274
    """Verify the hypervisor.
275

276
    @type hvparams: dict of strings
277
    @param hvparams: hypervisor parameters to be verified against
278

279
    @return: Problem description if something is wrong, C{None} otherwise
280

281
    """
282
    raise NotImplementedError
283

    
284
  def MigrationInfo(self, instance): # pylint: disable=R0201,W0613
285
    """Get instance information to perform a migration.
286

287
    By default assume no information is needed.
288

289
    @type instance: L{objects.Instance}
290
    @param instance: instance to be migrated
291
    @rtype: string/data (opaque)
292
    @return: instance migration information - serialized form
293

294
    """
295
    return ""
296

    
297
  def AcceptInstance(self, instance, info, target):
298
    """Prepare to accept an instance.
299

300
    By default assume no preparation is needed.
301

302
    @type instance: L{objects.Instance}
303
    @param instance: instance to be accepted
304
    @type info: string/data (opaque)
305
    @param info: migration information, from the source node
306
    @type target: string
307
    @param target: target host (usually ip), on this node
308

309
    """
310
    pass
311

    
312
  def BalloonInstanceMemory(self, instance, mem):
313
    """Balloon an instance memory to a certain value.
314

315
    @type instance: L{objects.Instance}
316
    @param instance: instance to be accepted
317
    @type mem: int
318
    @param mem: actual memory size to use for instance runtime
319

320
    """
321
    raise NotImplementedError
322

    
323
  def FinalizeMigrationDst(self, instance, info, success):
324
    """Finalize the instance migration on the target node.
325

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

329
    @type instance: L{objects.Instance}
330
    @param instance: instance whose migration is being finalized
331
    @type info: string/data (opaque)
332
    @param info: migration information, from the source node
333
    @type success: boolean
334
    @param success: whether the migration was a success or a failure
335

336
    """
337
    pass
338

    
339
  def MigrateInstance(self, instance, target, live):
340
    """Migrate an instance.
341

342
    @type instance: L{objects.Instance}
343
    @param instance: the instance to be migrated
344
    @type target: string
345
    @param target: hostname (usually ip) of the target node
346
    @type live: boolean
347
    @param live: whether to do a live or non-live migration
348

349
    """
350
    raise NotImplementedError
351

    
352
  def FinalizeMigrationSource(self, instance, success, live):
353
    """Finalize the instance migration on the source node.
354

355
    @type instance: L{objects.Instance}
356
    @param instance: the instance that was migrated
357
    @type success: bool
358
    @param success: whether the migration succeeded or not
359
    @type live: bool
360
    @param live: whether the user requested a live migration or not
361

362
    """
363
    pass
364

    
365
  def GetMigrationStatus(self, instance):
366
    """Get the migration status
367

368
    @type instance: L{objects.Instance}
369
    @param instance: the instance that is being migrated
370
    @rtype: L{objects.MigrationStatus}
371
    @return: the status of the current migration (one of
372
             L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
373
             progress info that can be retrieved from the hypervisor
374

375
    """
376
    raise NotImplementedError
377

    
378
  def _InstanceStartupMemory(self, instance, hvparams=None):
379
    """Get the correct startup memory for an instance
380

381
    This function calculates how much memory an instance should be started
382
    with, making sure it's a value between the minimum and the maximum memory,
383
    but also trying to use no more than the current free memory on the node.
384

385
    @type instance: L{objects.Instance}
386
    @param instance: the instance that is being started
387
    @rtype: integer
388
    @return: memory the instance should be started with
389

390
    """
391
    free_memory = self.GetNodeInfo(hvparams=hvparams)["memory_free"]
392
    max_start_mem = min(instance.beparams[constants.BE_MAXMEM], free_memory)
393
    start_mem = max(instance.beparams[constants.BE_MINMEM], max_start_mem)
394
    return start_mem
395

    
396
  @classmethod
397
  def CheckParameterSyntax(cls, hvparams):
398
    """Check the given parameters for validity.
399

400
    This should check the passed set of parameters for
401
    validity. Classes should extend, not replace, this function.
402

403
    @type hvparams:  dict
404
    @param hvparams: dictionary with parameter names/value
405
    @raise errors.HypervisorError: when a parameter is not valid
406

407
    """
408
    for key in hvparams:
409
      if key not in cls.PARAMETERS:
410
        raise errors.HypervisorError("Parameter '%s' is not supported" % key)
411

    
412
    # cheap tests that run on the master, should not access the world
413
    for name, (required, check_fn, errstr, _, _) in cls.PARAMETERS.items():
414
      if name not in hvparams:
415
        raise errors.HypervisorError("Parameter '%s' is missing" % name)
416
      value = hvparams[name]
417
      if not required and not value:
418
        continue
419
      if not value:
420
        raise errors.HypervisorError("Parameter '%s' is required but"
421
                                     " is currently not defined" % (name, ))
422
      if check_fn is not None and not check_fn(value):
423
        raise errors.HypervisorError("Parameter '%s' fails syntax"
424
                                     " check: %s (current value: '%s')" %
425
                                     (name, errstr, value))
426

    
427
  @classmethod
428
  def ValidateParameters(cls, hvparams):
429
    """Check the given parameters for validity.
430

431
    This should check the passed set of parameters for
432
    validity. Classes should extend, not replace, this function.
433

434
    @type hvparams:  dict
435
    @param hvparams: dictionary with parameter names/value
436
    @raise errors.HypervisorError: when a parameter is not valid
437

438
    """
439
    for name, (required, _, _, check_fn, errstr) in cls.PARAMETERS.items():
440
      value = hvparams[name]
441
      if not required and not value:
442
        continue
443
      if check_fn is not None and not check_fn(value):
444
        raise errors.HypervisorError("Parameter '%s' fails"
445
                                     " validation: %s (current value: '%s')" %
446
                                     (name, errstr, value))
447

    
448
  @classmethod
449
  def PowercycleNode(cls):
450
    """Hard powercycle a node using hypervisor specific methods.
451

452
    This method should hard powercycle the node, using whatever
453
    methods the hypervisor provides. Note that this means that all
454
    instances running on the node must be stopped too.
455

456
    """
457
    raise NotImplementedError
458

    
459
  @staticmethod
460
  def GetLinuxNodeInfo():
461
    """For linux systems, return actual OS information.
462

463
    This is an abstraction for all non-hypervisor-based classes, where
464
    the node actually sees all the memory and CPUs via the /proc
465
    interface and standard commands. The other case if for example
466
    xen, where you only see the hardware resources via xen-specific
467
    tools.
468

469
    @return: a dict with the following keys (values in MiB):
470
          - memory_total: the total memory size on the node
471
          - memory_free: the available memory on the node for instances
472
          - memory_dom0: the memory used by the node itself, if available
473

474
    """
475
    try:
476
      data = utils.ReadFile("/proc/meminfo").splitlines()
477
    except EnvironmentError, err:
478
      raise errors.HypervisorError("Failed to list node info: %s" % (err,))
479

    
480
    result = {}
481
    sum_free = 0
482
    try:
483
      for line in data:
484
        splitfields = line.split(":", 1)
485

    
486
        if len(splitfields) > 1:
487
          key = splitfields[0].strip()
488
          val = splitfields[1].strip()
489
          if key == "MemTotal":
490
            result["memory_total"] = int(val.split()[0]) / 1024
491
          elif key in ("MemFree", "Buffers", "Cached"):
492
            sum_free += int(val.split()[0]) / 1024
493
          elif key == "Active":
494
            result["memory_dom0"] = int(val.split()[0]) / 1024
495
    except (ValueError, TypeError), err:
496
      raise errors.HypervisorError("Failed to compute memory usage: %s" %
497
                                   (err,))
498
    result["memory_free"] = sum_free
499

    
500
    cpu_total = 0
501
    try:
502
      fh = open("/proc/cpuinfo")
503
      try:
504
        cpu_total = len(re.findall("(?m)^processor\s*:\s*[0-9]+\s*$",
505
                                   fh.read()))
506
      finally:
507
        fh.close()
508
    except EnvironmentError, err:
509
      raise errors.HypervisorError("Failed to list node info: %s" % (err,))
510
    result["cpu_total"] = cpu_total
511
    # FIXME: export correct data here
512
    result["cpu_nodes"] = 1
513
    result["cpu_sockets"] = 1
514

    
515
    return result
516

    
517
  @classmethod
518
  def LinuxPowercycle(cls):
519
    """Linux-specific powercycle method.
520

521
    """
522
    try:
523
      fd = os.open("/proc/sysrq-trigger", os.O_WRONLY)
524
      try:
525
        os.write(fd, "b")
526
      finally:
527
        fd.close()
528
    except OSError:
529
      logging.exception("Can't open the sysrq-trigger file")
530
      result = utils.RunCmd(["reboot", "-n", "-f"])
531
      if not result:
532
        logging.error("Can't run shutdown: %s", result.output)
533

    
534
  @staticmethod
535
  def _FormatVerifyResults(msgs):
536
    """Formats the verification results, given a list of errors.
537

538
    @param msgs: list of errors, possibly empty
539
    @return: overall problem description if something is wrong,
540
        C{None} otherwise
541

542
    """
543
    if msgs:
544
      return "; ".join(msgs)
545
    else:
546
      return None