Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_base.py @ c42be2c0

History | View | Annotate | Download (20.3 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 HvInstanceState(object):
148
  RUNNING = 0
149
  SHUTDOWN = 1
150

    
151
  @staticmethod
152
  def IsRunning(s):
153
    return s == HvInstanceState.RUNNING
154

    
155
  @staticmethod
156
  def IsShutdown(s):
157
    return s == HvInstanceState.SHUTDOWN
158

    
159

    
160
class BaseHypervisor(object):
161
  """Abstract virtualisation technology interface
162

163
  The goal is that all aspects of the virtualisation technology are
164
  abstracted away from the rest of code.
165

166
  @cvar PARAMETERS: a dict of parameter name: check type; the check type is
167
      a five-tuple containing:
168
          - the required flag (boolean)
169
          - a function to check for syntax, that will be used in
170
            L{CheckParameterSyntax}, in the master daemon process
171
          - an error message for the above function
172
          - a function to check for parameter validity on the remote node,
173
            in the L{ValidateParameters} function
174
          - an error message for the above function
175
  @type CAN_MIGRATE: boolean
176
  @cvar CAN_MIGRATE: whether this hypervisor can do migration (either
177
      live or non-live)
178

179
  """
180
  PARAMETERS = {}
181
  ANCILLARY_FILES = []
182
  ANCILLARY_FILES_OPT = []
183
  CAN_MIGRATE = False
184

    
185
  def StartInstance(self, instance, block_devices, startup_paused):
186
    """Start an instance."""
187
    raise NotImplementedError
188

    
189
  def StopInstance(self, instance, force=False, retry=False, name=None):
190
    """Stop an instance
191

192
    @type instance: L{objects.Instance}
193
    @param instance: instance to stop
194
    @type force: boolean
195
    @param force: whether to do a "hard" stop (destroy)
196
    @type retry: boolean
197
    @param retry: whether this is just a retry call
198
    @type name: string or None
199
    @param name: if this parameter is passed, the the instance object
200
        should not be used (will be passed as None), and the shutdown
201
        must be done by name only
202

203
    """
204
    raise NotImplementedError
205

    
206
  def CleanupInstance(self, instance_name):
207
    """Cleanup after a stopped instance
208

209
    This is an optional method, used by hypervisors that need to cleanup after
210
    an instance has been stopped.
211

212
    @type instance_name: string
213
    @param instance_name: instance name to cleanup after
214

215
    """
216
    pass
217

    
218
  def RebootInstance(self, instance):
219
    """Reboot an instance."""
220
    raise NotImplementedError
221

    
222
  def ListInstances(self, hvparams=None):
223
    """Get the list of running instances."""
224
    raise NotImplementedError
225

    
226
  def GetInstanceInfo(self, instance_name, hvparams=None):
227
    """Get instance properties.
228

229
    @type instance_name: string
230
    @param instance_name: the instance name
231
    @type hvparams: dict of strings
232
    @param hvparams: hvparams to be used with this instance
233

234
    @rtype: (string, string, int, int, HvInstanceState, int)
235
    @return: tuple (name, id, memory, vcpus, state, times)
236

237
    """
238
    raise NotImplementedError
239

    
240
  def GetAllInstancesInfo(self, hvparams=None):
241
    """Get properties of all instances.
242

243
    @type hvparams: dict of strings
244
    @param hvparams: hypervisor parameter
245

246
    @rtype: (string, string, int, int, HvInstanceState, int)
247
    @return: list of tuples (name, id, memory, vcpus, state, times)
248

249
    """
250
    raise NotImplementedError
251

    
252
  def GetNodeInfo(self, hvparams=None):
253
    """Return information about the node.
254

255
    @type hvparams: dict of strings
256
    @param hvparams: hypervisor parameters
257

258
    @return: a dict with at least the following keys (memory values in MiB):
259
          - memory_total: the total memory size on the node
260
          - memory_free: the available memory on the node for instances
261
          - memory_dom0: the memory used by the node itself, if available
262
          - cpu_total: total number of CPUs
263
          - cpu_dom0: number of CPUs used by the node OS
264
          - cpu_nodes: number of NUMA domains
265
          - cpu_sockets: number of physical CPU sockets
266

267
    """
268
    raise NotImplementedError
269

    
270
  @classmethod
271
  def GetInstanceConsole(cls, instance, primary_node, node_group,
272
                         hvparams, beparams):
273
    """Return information for connecting to the console of an instance.
274

275
    """
276
    raise NotImplementedError
277

    
278
  @classmethod
279
  def GetAncillaryFiles(cls):
280
    """Return a list of ancillary files to be copied to all nodes as ancillary
281
    configuration files.
282

283
    @rtype: (list of absolute paths, list of absolute paths)
284
    @return: (all files, optional files)
285

286
    """
287
    # By default we return a member variable, so that if an hypervisor has just
288
    # a static list of files it doesn't have to override this function.
289
    assert set(cls.ANCILLARY_FILES).issuperset(cls.ANCILLARY_FILES_OPT), \
290
      "Optional ancillary files must be a subset of ancillary files"
291

    
292
    return (cls.ANCILLARY_FILES, cls.ANCILLARY_FILES_OPT)
293

    
294
  def Verify(self, hvparams=None):
295
    """Verify the hypervisor.
296

297
    @type hvparams: dict of strings
298
    @param hvparams: hypervisor parameters to be verified against
299

300
    @return: Problem description if something is wrong, C{None} otherwise
301

302
    """
303
    raise NotImplementedError
304

    
305
  def MigrationInfo(self, instance): # pylint: disable=R0201,W0613
306
    """Get instance information to perform a migration.
307

308
    By default assume no information is needed.
309

310
    @type instance: L{objects.Instance}
311
    @param instance: instance to be migrated
312
    @rtype: string/data (opaque)
313
    @return: instance migration information - serialized form
314

315
    """
316
    return ""
317

    
318
  def AcceptInstance(self, instance, info, target):
319
    """Prepare to accept an instance.
320

321
    By default assume no preparation is needed.
322

323
    @type instance: L{objects.Instance}
324
    @param instance: instance to be accepted
325
    @type info: string/data (opaque)
326
    @param info: migration information, from the source node
327
    @type target: string
328
    @param target: target host (usually ip), on this node
329

330
    """
331
    pass
332

    
333
  def BalloonInstanceMemory(self, instance, mem):
334
    """Balloon an instance memory to a certain value.
335

336
    @type instance: L{objects.Instance}
337
    @param instance: instance to be accepted
338
    @type mem: int
339
    @param mem: actual memory size to use for instance runtime
340

341
    """
342
    raise NotImplementedError
343

    
344
  def FinalizeMigrationDst(self, instance, info, success):
345
    """Finalize the instance migration on the target node.
346

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

350
    @type instance: L{objects.Instance}
351
    @param instance: instance whose migration is being finalized
352
    @type info: string/data (opaque)
353
    @param info: migration information, from the source node
354
    @type success: boolean
355
    @param success: whether the migration was a success or a failure
356

357
    """
358
    pass
359

    
360
  def MigrateInstance(self, cluster_name, instance, target, live):
361
    """Migrate an instance.
362

363
    @type cluster_name: string
364
    @param cluster_name: name of the cluster
365
    @type instance: L{objects.Instance}
366
    @param instance: the instance to be migrated
367
    @type target: string
368
    @param target: hostname (usually ip) of the target node
369
    @type live: boolean
370
    @param live: whether to do a live or non-live migration
371

372
    """
373
    raise NotImplementedError
374

    
375
  def FinalizeMigrationSource(self, instance, success, live):
376
    """Finalize the instance migration on the source node.
377

378
    @type instance: L{objects.Instance}
379
    @param instance: the instance that was migrated
380
    @type success: bool
381
    @param success: whether the migration succeeded or not
382
    @type live: bool
383
    @param live: whether the user requested a live migration or not
384

385
    """
386
    pass
387

    
388
  def GetMigrationStatus(self, instance):
389
    """Get the migration status
390

391
    @type instance: L{objects.Instance}
392
    @param instance: the instance that is being migrated
393
    @rtype: L{objects.MigrationStatus}
394
    @return: the status of the current migration (one of
395
             L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
396
             progress info that can be retrieved from the hypervisor
397

398
    """
399
    raise NotImplementedError
400

    
401
  def _InstanceStartupMemory(self, instance, hvparams=None):
402
    """Get the correct startup memory for an instance
403

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

408
    @type instance: L{objects.Instance}
409
    @param instance: the instance that is being started
410
    @rtype: integer
411
    @return: memory the instance should be started with
412

413
    """
414
    free_memory = self.GetNodeInfo(hvparams=hvparams)["memory_free"]
415
    max_start_mem = min(instance.beparams[constants.BE_MAXMEM], free_memory)
416
    start_mem = max(instance.beparams[constants.BE_MINMEM], max_start_mem)
417
    return start_mem
418

    
419
  @classmethod
420
  def CheckParameterSyntax(cls, hvparams):
421
    """Check the given parameters for validity.
422

423
    This should check the passed set of parameters for
424
    validity. Classes should extend, not replace, this function.
425

426
    @type hvparams:  dict
427
    @param hvparams: dictionary with parameter names/value
428
    @raise errors.HypervisorError: when a parameter is not valid
429

430
    """
431
    for key in hvparams:
432
      if key not in cls.PARAMETERS:
433
        raise errors.HypervisorError("Parameter '%s' is not supported" % key)
434

    
435
    # cheap tests that run on the master, should not access the world
436
    for name, (required, check_fn, errstr, _, _) in cls.PARAMETERS.items():
437
      if name not in hvparams:
438
        raise errors.HypervisorError("Parameter '%s' is missing" % name)
439
      value = hvparams[name]
440
      if not required and not value:
441
        continue
442
      if not value:
443
        raise errors.HypervisorError("Parameter '%s' is required but"
444
                                     " is currently not defined" % (name, ))
445
      if check_fn is not None and not check_fn(value):
446
        raise errors.HypervisorError("Parameter '%s' fails syntax"
447
                                     " check: %s (current value: '%s')" %
448
                                     (name, errstr, value))
449

    
450
  @classmethod
451
  def ValidateParameters(cls, hvparams):
452
    """Check the given parameters for validity.
453

454
    This should check the passed set of parameters for
455
    validity. Classes should extend, not replace, this function.
456

457
    @type hvparams:  dict
458
    @param hvparams: dictionary with parameter names/value
459
    @raise errors.HypervisorError: when a parameter is not valid
460

461
    """
462
    for name, (required, _, _, check_fn, errstr) in cls.PARAMETERS.items():
463
      value = hvparams[name]
464
      if not required and not value:
465
        continue
466
      if check_fn is not None and not check_fn(value):
467
        raise errors.HypervisorError("Parameter '%s' fails"
468
                                     " validation: %s (current value: '%s')" %
469
                                     (name, errstr, value))
470

    
471
  @classmethod
472
  def PowercycleNode(cls, hvparams=None):
473
    """Hard powercycle a node using hypervisor specific methods.
474

475
    This method should hard powercycle the node, using whatever
476
    methods the hypervisor provides. Note that this means that all
477
    instances running on the node must be stopped too.
478

479
    @type hvparams: dict of strings
480
    @param hvparams: hypervisor params to be used on this node
481

482
    """
483
    raise NotImplementedError
484

    
485
  @staticmethod
486
  def GetLinuxNodeInfo(meminfo="/proc/meminfo", cpuinfo="/proc/cpuinfo"):
487
    """For linux systems, return actual OS information.
488

489
    This is an abstraction for all non-hypervisor-based classes, where
490
    the node actually sees all the memory and CPUs via the /proc
491
    interface and standard commands. The other case if for example
492
    xen, where you only see the hardware resources via xen-specific
493
    tools.
494

495
    @param meminfo: name of the file containing meminfo
496
    @type meminfo: string
497
    @param cpuinfo: name of the file containing cpuinfo
498
    @type cpuinfo: string
499
    @return: a dict with the following keys (values in MiB):
500
          - memory_total: the total memory size on the node
501
          - memory_free: the available memory on the node for instances
502
          - memory_dom0: the memory used by the node itself, if available
503
          - cpu_total: total number of CPUs
504
          - cpu_dom0: number of CPUs used by the node OS
505
          - cpu_nodes: number of NUMA domains
506
          - cpu_sockets: number of physical CPU sockets
507

508
    """
509
    try:
510
      data = utils.ReadFile(meminfo).splitlines()
511
    except EnvironmentError, err:
512
      raise errors.HypervisorError("Failed to list node info: %s" % (err,))
513

    
514
    result = {}
515
    sum_free = 0
516
    try:
517
      for line in data:
518
        splitfields = line.split(":", 1)
519

    
520
        if len(splitfields) > 1:
521
          key = splitfields[0].strip()
522
          val = splitfields[1].strip()
523
          if key == "MemTotal":
524
            result["memory_total"] = int(val.split()[0]) / 1024
525
          elif key in ("MemFree", "Buffers", "Cached"):
526
            sum_free += int(val.split()[0]) / 1024
527
          elif key == "Active":
528
            result["memory_dom0"] = int(val.split()[0]) / 1024
529
    except (ValueError, TypeError), err:
530
      raise errors.HypervisorError("Failed to compute memory usage: %s" %
531
                                   (err,))
532
    result["memory_free"] = sum_free
533

    
534
    cpu_total = 0
535
    try:
536
      fh = open(cpuinfo)
537
      try:
538
        cpu_total = len(re.findall(r"(?m)^processor\s*:\s*[0-9]+\s*$",
539
                                   fh.read()))
540
      finally:
541
        fh.close()
542
    except EnvironmentError, err:
543
      raise errors.HypervisorError("Failed to list node info: %s" % (err,))
544
    result["cpu_total"] = cpu_total
545
    # We assume that the node OS can access all the CPUs
546
    result["cpu_dom0"] = cpu_total
547
    # FIXME: export correct data here
548
    result["cpu_nodes"] = 1
549
    result["cpu_sockets"] = 1
550

    
551
    return result
552

    
553
  @classmethod
554
  def LinuxPowercycle(cls):
555
    """Linux-specific powercycle method.
556

557
    """
558
    try:
559
      fd = os.open("/proc/sysrq-trigger", os.O_WRONLY)
560
      try:
561
        os.write(fd, "b")
562
      finally:
563
        fd.close()
564
    except OSError:
565
      logging.exception("Can't open the sysrq-trigger file")
566
      result = utils.RunCmd(["reboot", "-n", "-f"])
567
      if not result:
568
        logging.error("Can't run shutdown: %s", result.output)
569

    
570
  @staticmethod
571
  def _FormatVerifyResults(msgs):
572
    """Formats the verification results, given a list of errors.
573

574
    @param msgs: list of errors, possibly empty
575
    @return: overall problem description if something is wrong,
576
        C{None} otherwise
577

578
    """
579
    if msgs:
580
      return "; ".join(msgs)
581
    else:
582
      return None
583

    
584
  # pylint: disable=R0201,W0613
585
  def HotAddDevice(self, instance, dev_type, device, extra, seq):
586
    """Hot-add a device.
587

588
    """
589
    raise errors.HotplugError("Hotplug is not supported by this hypervisor")
590

    
591
  # pylint: disable=R0201,W0613
592
  def HotDelDevice(self, instance, dev_type, device, extra, seq):
593
    """Hot-del a device.
594

595
    """
596
    raise errors.HotplugError("Hotplug is not supported by this hypervisor")
597

    
598
  # pylint: disable=R0201,W0613
599
  def HotModDevice(self, instance, dev_type, device, extra, seq):
600
    """Hot-mod a device.
601

602
    """
603
    raise errors.HotplugError("Hotplug is not supported by this hypervisor")
604

    
605
  # pylint: disable=R0201,W0613
606
  def VerifyHotplugSupport(self, instance, action, dev_type):
607
    """Verifies that hotplug is supported.
608

609
    Given the target device and hotplug action checks if hotplug is
610
    actually supported.
611

612
    @type instance: L{objects.Instance}
613
    @param instance: the instance object
614
    @type action: string
615
    @param action: one of the supported hotplug commands
616
    @type dev_type: string
617
    @param dev_type: one of the supported device types to hotplug
618
    @raise errors.HotplugError: if hotplugging is not supported
619

620
    """
621
    raise errors.HotplugError("Hotplug is not supported.")
622

    
623
  def HotplugSupported(self, instance):
624
    """Checks if hotplug is supported.
625

626
    By default is not. Currently only KVM hypervisor supports it.
627

628
    """
629
    raise errors.HotplugError("Hotplug is not supported by this hypervisor")