Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 63e52d34

History | View | Annotate | Download (63.8 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 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
"""Transportable objects for Ganeti.
23

24
This module provides small, mostly data-only objects which are safe to
25
pass to and from external parties.
26

27
"""
28

    
29
# pylint: disable=E0203,W0201,R0902
30

    
31
# E0203: Access to member %r before its definition, since we use
32
# objects.py which doesn't explicitly initialise its members
33

    
34
# W0201: Attribute '%s' defined outside __init__
35

    
36
# R0902: Allow instances of these objects to have more than 20 attributes
37

    
38
import ConfigParser
39
import re
40
import copy
41
import logging
42
import time
43
from cStringIO import StringIO
44

    
45
from ganeti import errors
46
from ganeti import constants
47
from ganeti import netutils
48
from ganeti import outils
49
from ganeti import utils
50

    
51
from socket import AF_INET
52

    
53

    
54
__all__ = ["ConfigObject", "ConfigData", "NIC", "Disk", "Instance",
55
           "OS", "Node", "NodeGroup", "Cluster", "FillDict", "Network"]
56

    
57
_TIMESTAMPS = ["ctime", "mtime"]
58
_UUID = ["uuid"]
59

    
60

    
61
def FillDict(defaults_dict, custom_dict, skip_keys=None):
62
  """Basic function to apply settings on top a default dict.
63

64
  @type defaults_dict: dict
65
  @param defaults_dict: dictionary holding the default values
66
  @type custom_dict: dict
67
  @param custom_dict: dictionary holding customized value
68
  @type skip_keys: list
69
  @param skip_keys: which keys not to fill
70
  @rtype: dict
71
  @return: dict with the 'full' values
72

73
  """
74
  ret_dict = copy.deepcopy(defaults_dict)
75
  ret_dict.update(custom_dict)
76
  if skip_keys:
77
    for k in skip_keys:
78
      try:
79
        del ret_dict[k]
80
      except KeyError:
81
        pass
82
  return ret_dict
83

    
84

    
85
def FillIPolicy(default_ipolicy, custom_ipolicy):
86
  """Fills an instance policy with defaults.
87

88
  """
89
  assert frozenset(default_ipolicy.keys()) == constants.IPOLICY_ALL_KEYS
90
  ret_dict = copy.deepcopy(custom_ipolicy)
91
  for key in default_ipolicy:
92
    if key not in ret_dict:
93
      ret_dict[key] = copy.deepcopy(default_ipolicy[key])
94
    elif key == constants.ISPECS_STD:
95
      ret_dict[key] = FillDict(default_ipolicy[key], ret_dict[key])
96
  return ret_dict
97

    
98

    
99
def FillDiskParams(default_dparams, custom_dparams, skip_keys=None):
100
  """Fills the disk parameter defaults.
101

102
  @see: L{FillDict} for parameters and return value
103

104
  """
105
  assert frozenset(default_dparams.keys()) == constants.DISK_TEMPLATES
106

    
107
  return dict((dt, FillDict(default_dparams[dt], custom_dparams.get(dt, {}),
108
                             skip_keys=skip_keys))
109
              for dt in constants.DISK_TEMPLATES)
110

    
111

    
112
def UpgradeGroupedParams(target, defaults):
113
  """Update all groups for the target parameter.
114

115
  @type target: dict of dicts
116
  @param target: {group: {parameter: value}}
117
  @type defaults: dict
118
  @param defaults: default parameter values
119

120
  """
121
  if target is None:
122
    target = {constants.PP_DEFAULT: defaults}
123
  else:
124
    for group in target:
125
      target[group] = FillDict(defaults, target[group])
126
  return target
127

    
128

    
129
def UpgradeBeParams(target):
130
  """Update the be parameters dict to the new format.
131

132
  @type target: dict
133
  @param target: "be" parameters dict
134

135
  """
136
  if constants.BE_MEMORY in target:
137
    memory = target[constants.BE_MEMORY]
138
    target[constants.BE_MAXMEM] = memory
139
    target[constants.BE_MINMEM] = memory
140
    del target[constants.BE_MEMORY]
141

    
142

    
143
def UpgradeDiskParams(diskparams):
144
  """Upgrade the disk parameters.
145

146
  @type diskparams: dict
147
  @param diskparams: disk parameters to upgrade
148
  @rtype: dict
149
  @return: the upgraded disk parameters dict
150

151
  """
152
  if not diskparams:
153
    result = {}
154
  else:
155
    result = FillDiskParams(constants.DISK_DT_DEFAULTS, diskparams)
156

    
157
  return result
158

    
159

    
160
def UpgradeNDParams(ndparams):
161
  """Upgrade ndparams structure.
162

163
  @type ndparams: dict
164
  @param ndparams: disk parameters to upgrade
165
  @rtype: dict
166
  @return: the upgraded node parameters dict
167

168
  """
169
  if ndparams is None:
170
    ndparams = {}
171

    
172
  if (constants.ND_OOB_PROGRAM in ndparams and
173
      ndparams[constants.ND_OOB_PROGRAM] is None):
174
    # will be reset by the line below
175
    del ndparams[constants.ND_OOB_PROGRAM]
176
  return FillDict(constants.NDC_DEFAULTS, ndparams)
177

    
178

    
179
def MakeEmptyIPolicy():
180
  """Create empty IPolicy dictionary.
181

182
  """
183
  return {}
184

    
185

    
186
class ConfigObject(outils.ValidatedSlots):
187
  """A generic config object.
188

189
  It has the following properties:
190

191
    - provides somewhat safe recursive unpickling and pickling for its classes
192
    - unset attributes which are defined in slots are always returned
193
      as None instead of raising an error
194

195
  Classes derived from this must always declare __slots__ (we use many
196
  config objects and the memory reduction is useful)
197

198
  """
199
  __slots__ = []
200

    
201
  def __getattr__(self, name):
202
    if name not in self.GetAllSlots():
203
      raise AttributeError("Invalid object attribute %s.%s" %
204
                           (type(self).__name__, name))
205
    return None
206

    
207
  def __setstate__(self, state):
208
    slots = self.GetAllSlots()
209
    for name in state:
210
      if name in slots:
211
        setattr(self, name, state[name])
212

    
213
  def Validate(self):
214
    """Validates the slots.
215

216
    """
217

    
218
  def ToDict(self):
219
    """Convert to a dict holding only standard python types.
220

221
    The generic routine just dumps all of this object's attributes in
222
    a dict. It does not work if the class has children who are
223
    ConfigObjects themselves (e.g. the nics list in an Instance), in
224
    which case the object should subclass the function in order to
225
    make sure all objects returned are only standard python types.
226

227
    """
228
    result = {}
229
    for name in self.GetAllSlots():
230
      value = getattr(self, name, None)
231
      if value is not None:
232
        result[name] = value
233
    return result
234

    
235
  __getstate__ = ToDict
236

    
237
  @classmethod
238
  def FromDict(cls, val):
239
    """Create an object from a dictionary.
240

241
    This generic routine takes a dict, instantiates a new instance of
242
    the given class, and sets attributes based on the dict content.
243

244
    As for `ToDict`, this does not work if the class has children
245
    who are ConfigObjects themselves (e.g. the nics list in an
246
    Instance), in which case the object should subclass the function
247
    and alter the objects.
248

249
    """
250
    if not isinstance(val, dict):
251
      raise errors.ConfigurationError("Invalid object passed to FromDict:"
252
                                      " expected dict, got %s" % type(val))
253
    val_str = dict([(str(k), v) for k, v in val.iteritems()])
254
    obj = cls(**val_str) # pylint: disable=W0142
255
    return obj
256

    
257
  def Copy(self):
258
    """Makes a deep copy of the current object and its children.
259

260
    """
261
    dict_form = self.ToDict()
262
    clone_obj = self.__class__.FromDict(dict_form)
263
    return clone_obj
264

    
265
  def __repr__(self):
266
    """Implement __repr__ for ConfigObjects."""
267
    return repr(self.ToDict())
268

    
269
  def UpgradeConfig(self):
270
    """Fill defaults for missing configuration values.
271

272
    This method will be called at configuration load time, and its
273
    implementation will be object dependent.
274

275
    """
276
    pass
277

    
278

    
279
class TaggableObject(ConfigObject):
280
  """An generic class supporting tags.
281

282
  """
283
  __slots__ = ["tags"]
284
  VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
285

    
286
  @classmethod
287
  def ValidateTag(cls, tag):
288
    """Check if a tag is valid.
289

290
    If the tag is invalid, an errors.TagError will be raised. The
291
    function has no return value.
292

293
    """
294
    if not isinstance(tag, basestring):
295
      raise errors.TagError("Invalid tag type (not a string)")
296
    if len(tag) > constants.MAX_TAG_LEN:
297
      raise errors.TagError("Tag too long (>%d characters)" %
298
                            constants.MAX_TAG_LEN)
299
    if not tag:
300
      raise errors.TagError("Tags cannot be empty")
301
    if not cls.VALID_TAG_RE.match(tag):
302
      raise errors.TagError("Tag contains invalid characters")
303

    
304
  def GetTags(self):
305
    """Return the tags list.
306

307
    """
308
    tags = getattr(self, "tags", None)
309
    if tags is None:
310
      tags = self.tags = set()
311
    return tags
312

    
313
  def AddTag(self, tag):
314
    """Add a new tag.
315

316
    """
317
    self.ValidateTag(tag)
318
    tags = self.GetTags()
319
    if len(tags) >= constants.MAX_TAGS_PER_OBJ:
320
      raise errors.TagError("Too many tags")
321
    self.GetTags().add(tag)
322

    
323
  def RemoveTag(self, tag):
324
    """Remove a tag.
325

326
    """
327
    self.ValidateTag(tag)
328
    tags = self.GetTags()
329
    try:
330
      tags.remove(tag)
331
    except KeyError:
332
      raise errors.TagError("Tag not found")
333

    
334
  def ToDict(self):
335
    """Taggable-object-specific conversion to standard python types.
336

337
    This replaces the tags set with a list.
338

339
    """
340
    bo = super(TaggableObject, self).ToDict()
341

    
342
    tags = bo.get("tags", None)
343
    if isinstance(tags, set):
344
      bo["tags"] = list(tags)
345
    return bo
346

    
347
  @classmethod
348
  def FromDict(cls, val):
349
    """Custom function for instances.
350

351
    """
352
    obj = super(TaggableObject, cls).FromDict(val)
353
    if hasattr(obj, "tags") and isinstance(obj.tags, list):
354
      obj.tags = set(obj.tags)
355
    return obj
356

    
357

    
358
class MasterNetworkParameters(ConfigObject):
359
  """Network configuration parameters for the master
360

361
  @ivar uuid: master nodes UUID
362
  @ivar ip: master IP
363
  @ivar netmask: master netmask
364
  @ivar netdev: master network device
365
  @ivar ip_family: master IP family
366

367
  """
368
  __slots__ = [
369
    "uuid",
370
    "ip",
371
    "netmask",
372
    "netdev",
373
    "ip_family",
374
    ]
375

    
376

    
377
class ConfigData(ConfigObject):
378
  """Top-level config object."""
379
  __slots__ = [
380
    "version",
381
    "cluster",
382
    "nodes",
383
    "nodegroups",
384
    "instances",
385
    "networks",
386
    "serial_no",
387
    ] + _TIMESTAMPS
388

    
389
  def ToDict(self):
390
    """Custom function for top-level config data.
391

392
    This just replaces the list of instances, nodes and the cluster
393
    with standard python types.
394

395
    """
396
    mydict = super(ConfigData, self).ToDict()
397
    mydict["cluster"] = mydict["cluster"].ToDict()
398
    for key in "nodes", "instances", "nodegroups", "networks":
399
      mydict[key] = outils.ContainerToDicts(mydict[key])
400

    
401
    return mydict
402

    
403
  @classmethod
404
  def FromDict(cls, val):
405
    """Custom function for top-level config data
406

407
    """
408
    obj = super(ConfigData, cls).FromDict(val)
409
    obj.cluster = Cluster.FromDict(obj.cluster)
410
    obj.nodes = outils.ContainerFromDicts(obj.nodes, dict, Node)
411
    obj.instances = \
412
      outils.ContainerFromDicts(obj.instances, dict, Instance)
413
    obj.nodegroups = \
414
      outils.ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
415
    obj.networks = outils.ContainerFromDicts(obj.networks, dict, Network)
416
    return obj
417

    
418
  def HasAnyDiskOfType(self, dev_type):
419
    """Check if in there is at disk of the given type in the configuration.
420

421
    @type dev_type: L{constants.LDS_BLOCK}
422
    @param dev_type: the type to look for
423
    @rtype: boolean
424
    @return: boolean indicating if a disk of the given type was found or not
425

426
    """
427
    for instance in self.instances.values():
428
      for disk in instance.disks:
429
        if disk.IsBasedOnDiskType(dev_type):
430
          return True
431
    return False
432

    
433
  def UpgradeConfig(self):
434
    """Fill defaults for missing configuration values.
435

436
    """
437
    self.cluster.UpgradeConfig()
438
    for node in self.nodes.values():
439
      node.UpgradeConfig()
440
    for instance in self.instances.values():
441
      instance.UpgradeConfig()
442
    if self.nodegroups is None:
443
      self.nodegroups = {}
444
    for nodegroup in self.nodegroups.values():
445
      nodegroup.UpgradeConfig()
446
    if self.cluster.drbd_usermode_helper is None:
447
      # To decide if we set an helper let's check if at least one instance has
448
      # a DRBD disk. This does not cover all the possible scenarios but it
449
      # gives a good approximation.
450
      if self.HasAnyDiskOfType(constants.LD_DRBD8):
451
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
452
    if self.networks is None:
453
      self.networks = {}
454
    for network in self.networks.values():
455
      network.UpgradeConfig()
456
    self._UpgradeEnabledDiskTemplates()
457

    
458
  def _UpgradeEnabledDiskTemplates(self):
459
    """Upgrade the cluster's enabled disk templates by inspecting the currently
460
       enabled and/or used disk templates.
461

462
    """
463
    # enabled_disk_templates in the cluster config were introduced in 2.8.
464
    # Remove this code once upgrading from earlier versions is deprecated.
465
    if not self.cluster.enabled_disk_templates:
466
      template_set = \
467
        set([inst.disk_template for inst in self.instances.values()])
468
      # Add drbd and plain, if lvm is enabled (by specifying a volume group)
469
      if self.cluster.volume_group_name:
470
        template_set.add(constants.DT_DRBD8)
471
        template_set.add(constants.DT_PLAIN)
472
      # FIXME: Adapt this when dis/enabling at configure time is removed.
473
      # Enable 'file' and 'sharedfile', if they are enabled, even though they
474
      # might currently not be used.
475
      if constants.ENABLE_FILE_STORAGE:
476
        template_set.add(constants.DT_FILE)
477
      if constants.ENABLE_SHARED_FILE_STORAGE:
478
        template_set.add(constants.DT_SHARED_FILE)
479
      # Set enabled_disk_templates to the inferred disk templates. Order them
480
      # according to a preference list that is based on Ganeti's history of
481
      # supported disk templates.
482
      self.cluster.enabled_disk_templates = []
483
      for preferred_template in constants.DISK_TEMPLATE_PREFERENCE:
484
        if preferred_template in template_set:
485
          self.cluster.enabled_disk_templates.append(preferred_template)
486
          template_set.remove(preferred_template)
487
      self.cluster.enabled_disk_templates.extend(list(template_set))
488

    
489

    
490
class NIC(ConfigObject):
491
  """Config object representing a network card."""
492
  __slots__ = ["name", "mac", "ip", "network",
493
               "nicparams", "netinfo", "pci"] + _UUID
494

    
495
  @classmethod
496
  def CheckParameterSyntax(cls, nicparams):
497
    """Check the given parameters for validity.
498

499
    @type nicparams:  dict
500
    @param nicparams: dictionary with parameter names/value
501
    @raise errors.ConfigurationError: when a parameter is not valid
502

503
    """
504
    mode = nicparams[constants.NIC_MODE]
505
    if (mode not in constants.NIC_VALID_MODES and
506
        mode != constants.VALUE_AUTO):
507
      raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
508

    
509
    if (mode == constants.NIC_MODE_BRIDGED and
510
        not nicparams[constants.NIC_LINK]):
511
      raise errors.ConfigurationError("Missing bridged NIC link")
512

    
513

    
514
class Disk(ConfigObject):
515
  """Config object representing a block device."""
516
  __slots__ = (["name", "dev_type", "logical_id", "physical_id",
517
                "children", "iv_name", "size", "mode", "params",
518
                "spindles", "pci"] + _UUID)
519

    
520
  def CreateOnSecondary(self):
521
    """Test if this device needs to be created on a secondary node."""
522
    return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
523

    
524
  def AssembleOnSecondary(self):
525
    """Test if this device needs to be assembled on a secondary node."""
526
    return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
527

    
528
  def OpenOnSecondary(self):
529
    """Test if this device needs to be opened on a secondary node."""
530
    return self.dev_type in (constants.LD_LV,)
531

    
532
  def StaticDevPath(self):
533
    """Return the device path if this device type has a static one.
534

535
    Some devices (LVM for example) live always at the same /dev/ path,
536
    irrespective of their status. For such devices, we return this
537
    path, for others we return None.
538

539
    @warning: The path returned is not a normalized pathname; callers
540
        should check that it is a valid path.
541

542
    """
543
    if self.dev_type == constants.LD_LV:
544
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
545
    elif self.dev_type == constants.LD_BLOCKDEV:
546
      return self.logical_id[1]
547
    elif self.dev_type == constants.LD_RBD:
548
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
549
    return None
550

    
551
  def ChildrenNeeded(self):
552
    """Compute the needed number of children for activation.
553

554
    This method will return either -1 (all children) or a positive
555
    number denoting the minimum number of children needed for
556
    activation (only mirrored devices will usually return >=0).
557

558
    Currently, only DRBD8 supports diskless activation (therefore we
559
    return 0), for all other we keep the previous semantics and return
560
    -1.
561

562
    """
563
    if self.dev_type == constants.LD_DRBD8:
564
      return 0
565
    return -1
566

    
567
  def IsBasedOnDiskType(self, dev_type):
568
    """Check if the disk or its children are based on the given type.
569

570
    @type dev_type: L{constants.LDS_BLOCK}
571
    @param dev_type: the type to look for
572
    @rtype: boolean
573
    @return: boolean indicating if a device of the given type was found or not
574

575
    """
576
    if self.children:
577
      for child in self.children:
578
        if child.IsBasedOnDiskType(dev_type):
579
          return True
580
    return self.dev_type == dev_type
581

    
582
  def GetNodes(self, node_uuid):
583
    """This function returns the nodes this device lives on.
584

585
    Given the node on which the parent of the device lives on (or, in
586
    case of a top-level device, the primary node of the devices'
587
    instance), this function will return a list of nodes on which this
588
    devices needs to (or can) be assembled.
589

590
    """
591
    if self.dev_type in [constants.LD_LV, constants.LD_FILE,
592
                         constants.LD_BLOCKDEV, constants.LD_RBD,
593
                         constants.LD_EXT]:
594
      result = [node_uuid]
595
    elif self.dev_type in constants.LDS_DRBD:
596
      result = [self.logical_id[0], self.logical_id[1]]
597
      if node_uuid not in result:
598
        raise errors.ConfigurationError("DRBD device passed unknown node")
599
    else:
600
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
601
    return result
602

    
603
  def ComputeNodeTree(self, parent_node_uuid):
604
    """Compute the node/disk tree for this disk and its children.
605

606
    This method, given the node on which the parent disk lives, will
607
    return the list of all (node UUID, disk) pairs which describe the disk
608
    tree in the most compact way. For example, a drbd/lvm stack
609
    will be returned as (primary_node, drbd) and (secondary_node, drbd)
610
    which represents all the top-level devices on the nodes.
611

612
    """
613
    my_nodes = self.GetNodes(parent_node_uuid)
614
    result = [(node, self) for node in my_nodes]
615
    if not self.children:
616
      # leaf device
617
      return result
618
    for node in my_nodes:
619
      for child in self.children:
620
        child_result = child.ComputeNodeTree(node)
621
        if len(child_result) == 1:
622
          # child (and all its descendants) is simple, doesn't split
623
          # over multiple hosts, so we don't need to describe it, our
624
          # own entry for this node describes it completely
625
          continue
626
        else:
627
          # check if child nodes differ from my nodes; note that
628
          # subdisk can differ from the child itself, and be instead
629
          # one of its descendants
630
          for subnode, subdisk in child_result:
631
            if subnode not in my_nodes:
632
              result.append((subnode, subdisk))
633
            # otherwise child is under our own node, so we ignore this
634
            # entry (but probably the other results in the list will
635
            # be different)
636
    return result
637

    
638
  def ComputeGrowth(self, amount):
639
    """Compute the per-VG growth requirements.
640

641
    This only works for VG-based disks.
642

643
    @type amount: integer
644
    @param amount: the desired increase in (user-visible) disk space
645
    @rtype: dict
646
    @return: a dictionary of volume-groups and the required size
647

648
    """
649
    if self.dev_type == constants.LD_LV:
650
      return {self.logical_id[0]: amount}
651
    elif self.dev_type == constants.LD_DRBD8:
652
      if self.children:
653
        return self.children[0].ComputeGrowth(amount)
654
      else:
655
        return {}
656
    else:
657
      # Other disk types do not require VG space
658
      return {}
659

    
660
  def RecordGrow(self, amount):
661
    """Update the size of this disk after growth.
662

663
    This method recurses over the disks's children and updates their
664
    size correspondigly. The method needs to be kept in sync with the
665
    actual algorithms from bdev.
666

667
    """
668
    if self.dev_type in (constants.LD_LV, constants.LD_FILE,
669
                         constants.LD_RBD, constants.LD_EXT):
670
      self.size += amount
671
    elif self.dev_type == constants.LD_DRBD8:
672
      if self.children:
673
        self.children[0].RecordGrow(amount)
674
      self.size += amount
675
    else:
676
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
677
                                   " disk type %s" % self.dev_type)
678

    
679
  def Update(self, size=None, mode=None, spindles=None):
680
    """Apply changes to size, spindles and mode.
681

682
    """
683
    if self.dev_type == constants.LD_DRBD8:
684
      if self.children:
685
        self.children[0].Update(size=size, mode=mode)
686
    else:
687
      assert not self.children
688

    
689
    if size is not None:
690
      self.size = size
691
    if mode is not None:
692
      self.mode = mode
693
    if spindles is not None:
694
      self.spindles = spindles
695

    
696
  def UnsetSize(self):
697
    """Sets recursively the size to zero for the disk and its children.
698

699
    """
700
    if self.children:
701
      for child in self.children:
702
        child.UnsetSize()
703
    self.size = 0
704

    
705
  def SetPhysicalID(self, target_node_uuid, nodes_ip):
706
    """Convert the logical ID to the physical ID.
707

708
    This is used only for drbd, which needs ip/port configuration.
709

710
    The routine descends down and updates its children also, because
711
    this helps when the only the top device is passed to the remote
712
    node.
713

714
    Arguments:
715
      - target_node_uuid: the node UUID we wish to configure for
716
      - nodes_ip: a mapping of node name to ip
717

718
    The target_node must exist in in nodes_ip, and must be one of the
719
    nodes in the logical ID for each of the DRBD devices encountered
720
    in the disk tree.
721

722
    """
723
    if self.children:
724
      for child in self.children:
725
        child.SetPhysicalID(target_node_uuid, nodes_ip)
726

    
727
    if self.logical_id is None and self.physical_id is not None:
728
      return
729
    if self.dev_type in constants.LDS_DRBD:
730
      pnode_uuid, snode_uuid, port, pminor, sminor, secret = self.logical_id
731
      if target_node_uuid not in (pnode_uuid, snode_uuid):
732
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
733
                                        target_node_uuid)
734
      pnode_ip = nodes_ip.get(pnode_uuid, None)
735
      snode_ip = nodes_ip.get(snode_uuid, None)
736
      if pnode_ip is None or snode_ip is None:
737
        raise errors.ConfigurationError("Can't find primary or secondary node"
738
                                        " for %s" % str(self))
739
      p_data = (pnode_ip, port)
740
      s_data = (snode_ip, port)
741
      if pnode_uuid == target_node_uuid:
742
        self.physical_id = p_data + s_data + (pminor, secret)
743
      else: # it must be secondary, we tested above
744
        self.physical_id = s_data + p_data + (sminor, secret)
745
    else:
746
      self.physical_id = self.logical_id
747
    return
748

    
749
  def ToDict(self):
750
    """Disk-specific conversion to standard python types.
751

752
    This replaces the children lists of objects with lists of
753
    standard python types.
754

755
    """
756
    bo = super(Disk, self).ToDict()
757

    
758
    for attr in ("children",):
759
      alist = bo.get(attr, None)
760
      if alist:
761
        bo[attr] = outils.ContainerToDicts(alist)
762
    return bo
763

    
764
  @classmethod
765
  def FromDict(cls, val):
766
    """Custom function for Disks
767

768
    """
769
    obj = super(Disk, cls).FromDict(val)
770
    if obj.children:
771
      obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
772
    if obj.logical_id and isinstance(obj.logical_id, list):
773
      obj.logical_id = tuple(obj.logical_id)
774
    if obj.physical_id and isinstance(obj.physical_id, list):
775
      obj.physical_id = tuple(obj.physical_id)
776
    if obj.dev_type in constants.LDS_DRBD:
777
      # we need a tuple of length six here
778
      if len(obj.logical_id) < 6:
779
        obj.logical_id += (None,) * (6 - len(obj.logical_id))
780
    return obj
781

    
782
  def __str__(self):
783
    """Custom str() formatter for disks.
784

785
    """
786
    if self.dev_type == constants.LD_LV:
787
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
788
    elif self.dev_type in constants.LDS_DRBD:
789
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
790
      val = "<DRBD8("
791
      if self.physical_id is None:
792
        phy = "unconfigured"
793
      else:
794
        phy = ("configured as %s:%s %s:%s" %
795
               (self.physical_id[0], self.physical_id[1],
796
                self.physical_id[2], self.physical_id[3]))
797

    
798
      val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
799
              (node_a, minor_a, node_b, minor_b, port, phy))
800
      if self.children and self.children.count(None) == 0:
801
        val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
802
      else:
803
        val += "no local storage"
804
    else:
805
      val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
806
             (self.dev_type, self.logical_id, self.physical_id, self.children))
807
    if self.iv_name is None:
808
      val += ", not visible"
809
    else:
810
      val += ", visible as /dev/%s" % self.iv_name
811
    if self.spindles is not None:
812
      val += ", spindles=%s" % self.spindles
813
    if isinstance(self.size, int):
814
      val += ", size=%dm)>" % self.size
815
    else:
816
      val += ", size='%s')>" % (self.size,)
817
    return val
818

    
819
  def Verify(self):
820
    """Checks that this disk is correctly configured.
821

822
    """
823
    all_errors = []
824
    if self.mode not in constants.DISK_ACCESS_SET:
825
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
826
    return all_errors
827

    
828
  def UpgradeConfig(self):
829
    """Fill defaults for missing configuration values.
830

831
    """
832
    if self.children:
833
      for child in self.children:
834
        child.UpgradeConfig()
835

    
836
    # FIXME: Make this configurable in Ganeti 2.7
837
    self.params = {}
838
    # add here config upgrade for this disk
839

    
840
  @staticmethod
841
  def ComputeLDParams(disk_template, disk_params):
842
    """Computes Logical Disk parameters from Disk Template parameters.
843

844
    @type disk_template: string
845
    @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
846
    @type disk_params: dict
847
    @param disk_params: disk template parameters;
848
                        dict(template_name -> parameters
849
    @rtype: list(dict)
850
    @return: a list of dicts, one for each node of the disk hierarchy. Each dict
851
      contains the LD parameters of the node. The tree is flattened in-order.
852

853
    """
854
    if disk_template not in constants.DISK_TEMPLATES:
855
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
856

    
857
    assert disk_template in disk_params
858

    
859
    result = list()
860
    dt_params = disk_params[disk_template]
861
    if disk_template == constants.DT_DRBD8:
862
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8], {
863
        constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
864
        constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
865
        constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
866
        constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
867
        constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
868
        constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
869
        constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
870
        constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
871
        constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
872
        constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
873
        constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
874
        constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
875
        }))
876

    
877
      # data LV
878
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
879
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
880
        }))
881

    
882
      # metadata LV
883
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
884
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
885
        }))
886

    
887
    elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
888
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
889

    
890
    elif disk_template == constants.DT_PLAIN:
891
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
892
        constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
893
        }))
894

    
895
    elif disk_template == constants.DT_BLOCK:
896
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
897

    
898
    elif disk_template == constants.DT_RBD:
899
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD], {
900
        constants.LDP_POOL: dt_params[constants.RBD_POOL],
901
        }))
902

    
903
    elif disk_template == constants.DT_EXT:
904
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_EXT])
905

    
906
    return result
907

    
908

    
909
class InstancePolicy(ConfigObject):
910
  """Config object representing instance policy limits dictionary.
911

912
  Note that this object is not actually used in the config, it's just
913
  used as a placeholder for a few functions.
914

915
  """
916
  @classmethod
917
  def CheckParameterSyntax(cls, ipolicy, check_std):
918
    """ Check the instance policy for validity.
919

920
    @type ipolicy: dict
921
    @param ipolicy: dictionary with min/max/std specs and policies
922
    @type check_std: bool
923
    @param check_std: Whether to check std value or just assume compliance
924
    @raise errors.ConfigurationError: when the policy is not legal
925

926
    """
927
    InstancePolicy.CheckISpecSyntax(ipolicy, check_std)
928
    if constants.IPOLICY_DTS in ipolicy:
929
      InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
930
    for key in constants.IPOLICY_PARAMETERS:
931
      if key in ipolicy:
932
        InstancePolicy.CheckParameter(key, ipolicy[key])
933
    wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
934
    if wrong_keys:
935
      raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
936
                                      utils.CommaJoin(wrong_keys))
937

    
938
  @classmethod
939
  def _CheckIncompleteSpec(cls, spec, keyname):
940
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
941
    if missing_params:
942
      msg = ("Missing instance specs parameters for %s: %s" %
943
             (keyname, utils.CommaJoin(missing_params)))
944
      raise errors.ConfigurationError(msg)
945

    
946
  @classmethod
947
  def CheckISpecSyntax(cls, ipolicy, check_std):
948
    """Check the instance policy specs for validity.
949

950
    @type ipolicy: dict
951
    @param ipolicy: dictionary with min/max/std specs
952
    @type check_std: bool
953
    @param check_std: Whether to check std value or just assume compliance
954
    @raise errors.ConfigurationError: when specs are not valid
955

956
    """
957
    if constants.ISPECS_MINMAX not in ipolicy:
958
      # Nothing to check
959
      return
960

    
961
    if check_std and constants.ISPECS_STD not in ipolicy:
962
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
963
      raise errors.ConfigurationError(msg)
964
    stdspec = ipolicy.get(constants.ISPECS_STD)
965
    if check_std:
966
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
967

    
968
    if not ipolicy[constants.ISPECS_MINMAX]:
969
      raise errors.ConfigurationError("Empty minmax specifications")
970
    std_is_good = False
971
    for minmaxspecs in ipolicy[constants.ISPECS_MINMAX]:
972
      missing = constants.ISPECS_MINMAX_KEYS - frozenset(minmaxspecs.keys())
973
      if missing:
974
        msg = "Missing instance specification: %s" % utils.CommaJoin(missing)
975
        raise errors.ConfigurationError(msg)
976
      for (key, spec) in minmaxspecs.items():
977
        InstancePolicy._CheckIncompleteSpec(spec, key)
978

    
979
      spec_std_ok = True
980
      for param in constants.ISPECS_PARAMETERS:
981
        par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
982
                                                           param, check_std)
983
        spec_std_ok = spec_std_ok and par_std_ok
984
      std_is_good = std_is_good or spec_std_ok
985
    if not std_is_good:
986
      raise errors.ConfigurationError("Invalid std specifications")
987

    
988
  @classmethod
989
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
990
    """Check the instance policy specs for validity on a given key.
991

992
    We check if the instance specs makes sense for a given key, that is
993
    if minmaxspecs[min][name] <= stdspec[name] <= minmaxspec[max][name].
994

995
    @type minmaxspecs: dict
996
    @param minmaxspecs: dictionary with min and max instance spec
997
    @type stdspec: dict
998
    @param stdspec: dictionary with standard instance spec
999
    @type name: string
1000
    @param name: what are the limits for
1001
    @type check_std: bool
1002
    @param check_std: Whether to check std value or just assume compliance
1003
    @rtype: bool
1004
    @return: C{True} when specs are valid, C{False} when standard spec for the
1005
        given name is not valid
1006
    @raise errors.ConfigurationError: when min/max specs for the given name
1007
        are not valid
1008

1009
    """
1010
    minspec = minmaxspecs[constants.ISPECS_MIN]
1011
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1012
    min_v = minspec[name]
1013
    max_v = maxspec[name]
1014

    
1015
    if min_v > max_v:
1016
      err = ("Invalid specification of min/max values for %s: %s/%s" %
1017
             (name, min_v, max_v))
1018
      raise errors.ConfigurationError(err)
1019
    elif check_std:
1020
      std_v = stdspec.get(name, min_v)
1021
      return std_v >= min_v and std_v <= max_v
1022
    else:
1023
      return True
1024

    
1025
  @classmethod
1026
  def CheckDiskTemplates(cls, disk_templates):
1027
    """Checks the disk templates for validity.
1028

1029
    """
1030
    if not disk_templates:
1031
      raise errors.ConfigurationError("Instance policy must contain" +
1032
                                      " at least one disk template")
1033
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1034
    if wrong:
1035
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1036
                                      utils.CommaJoin(wrong))
1037

    
1038
  @classmethod
1039
  def CheckParameter(cls, key, value):
1040
    """Checks a parameter.
1041

1042
    Currently we expect all parameters to be float values.
1043

1044
    """
1045
    try:
1046
      float(value)
1047
    except (TypeError, ValueError), err:
1048
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1049
                                      " '%s', error: %s" % (key, value, err))
1050

    
1051

    
1052
class Instance(TaggableObject):
1053
  """Config object representing an instance."""
1054
  __slots__ = [
1055
    "name",
1056
    "primary_node",
1057
    "os",
1058
    "hypervisor",
1059
    "hvparams",
1060
    "beparams",
1061
    "osparams",
1062
    "dev_idxs",
1063
    "admin_state",
1064
    "nics",
1065
    "disks",
1066
    "disk_template",
1067
    "disks_active",
1068
    "network_port",
1069
    "serial_no",
1070
    ] + _TIMESTAMPS + _UUID
1071

    
1072
  def _ComputeSecondaryNodes(self):
1073
    """Compute the list of secondary nodes.
1074

1075
    This is a simple wrapper over _ComputeAllNodes.
1076

1077
    """
1078
    all_nodes = set(self._ComputeAllNodes())
1079
    all_nodes.discard(self.primary_node)
1080
    return tuple(all_nodes)
1081

    
1082
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1083
                             "List of names of secondary nodes")
1084

    
1085
  def _ComputeAllNodes(self):
1086
    """Compute the list of all nodes.
1087

1088
    Since the data is already there (in the drbd disks), keeping it as
1089
    a separate normal attribute is redundant and if not properly
1090
    synchronised can cause problems. Thus it's better to compute it
1091
    dynamically.
1092

1093
    """
1094
    def _Helper(nodes, device):
1095
      """Recursively computes nodes given a top device."""
1096
      if device.dev_type in constants.LDS_DRBD:
1097
        nodea, nodeb = device.logical_id[:2]
1098
        nodes.add(nodea)
1099
        nodes.add(nodeb)
1100
      if device.children:
1101
        for child in device.children:
1102
          _Helper(nodes, child)
1103

    
1104
    all_nodes = set()
1105
    all_nodes.add(self.primary_node)
1106
    for device in self.disks:
1107
      _Helper(all_nodes, device)
1108
    return tuple(all_nodes)
1109

    
1110
  all_nodes = property(_ComputeAllNodes, None, None,
1111
                       "List of names of all the nodes of the instance")
1112

    
1113
  def MapLVsByNode(self, lvmap=None, devs=None, node=None):
1114
    """Provide a mapping of nodes to LVs this instance owns.
1115

1116
    This function figures out what logical volumes should belong on
1117
    which nodes, recursing through a device tree.
1118

1119
    @param lvmap: optional dictionary to receive the
1120
        'node' : ['lv', ...] data.
1121

1122
    @return: None if lvmap arg is given, otherwise, a dictionary of
1123
        the form { 'node_uuid' : ['volume1', 'volume2', ...], ... };
1124
        volumeN is of the form "vg_name/lv_name", compatible with
1125
        GetVolumeList()
1126

1127
    """
1128
    if node is None:
1129
      node = self.primary_node
1130

    
1131
    if lvmap is None:
1132
      lvmap = {
1133
        node: [],
1134
        }
1135
      ret = lvmap
1136
    else:
1137
      if not node in lvmap:
1138
        lvmap[node] = []
1139
      ret = None
1140

    
1141
    if not devs:
1142
      devs = self.disks
1143

    
1144
    for dev in devs:
1145
      if dev.dev_type == constants.LD_LV:
1146
        lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1147

    
1148
      elif dev.dev_type in constants.LDS_DRBD:
1149
        if dev.children:
1150
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1151
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1152

    
1153
      elif dev.children:
1154
        self.MapLVsByNode(lvmap, dev.children, node)
1155

    
1156
    return ret
1157

    
1158
  def FindDisk(self, idx):
1159
    """Find a disk given having a specified index.
1160

1161
    This is just a wrapper that does validation of the index.
1162

1163
    @type idx: int
1164
    @param idx: the disk index
1165
    @rtype: L{Disk}
1166
    @return: the corresponding disk
1167
    @raise errors.OpPrereqError: when the given index is not valid
1168

1169
    """
1170
    try:
1171
      idx = int(idx)
1172
      return self.disks[idx]
1173
    except (TypeError, ValueError), err:
1174
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1175
                                 errors.ECODE_INVAL)
1176
    except IndexError:
1177
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1178
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1179
                                 errors.ECODE_INVAL)
1180

    
1181
  def ToDict(self):
1182
    """Instance-specific conversion to standard python types.
1183

1184
    This replaces the children lists of objects with lists of standard
1185
    python types.
1186

1187
    """
1188
    bo = super(Instance, self).ToDict()
1189

    
1190
    for attr in "nics", "disks":
1191
      alist = bo.get(attr, None)
1192
      if alist:
1193
        nlist = outils.ContainerToDicts(alist)
1194
      else:
1195
        nlist = []
1196
      bo[attr] = nlist
1197
    return bo
1198

    
1199
  @classmethod
1200
  def FromDict(cls, val):
1201
    """Custom function for instances.
1202

1203
    """
1204
    if "admin_state" not in val:
1205
      if val.get("admin_up", False):
1206
        val["admin_state"] = constants.ADMINST_UP
1207
      else:
1208
        val["admin_state"] = constants.ADMINST_DOWN
1209
    if "admin_up" in val:
1210
      del val["admin_up"]
1211
    obj = super(Instance, cls).FromDict(val)
1212
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1213
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1214
    return obj
1215

    
1216
  def UpgradeConfig(self):
1217
    """Fill defaults for missing configuration values.
1218

1219
    """
1220
    for nic in self.nics:
1221
      nic.UpgradeConfig()
1222
    for disk in self.disks:
1223
      disk.UpgradeConfig()
1224
    if self.hvparams:
1225
      for key in constants.HVC_GLOBALS:
1226
        try:
1227
          del self.hvparams[key]
1228
        except KeyError:
1229
          pass
1230
    if self.osparams is None:
1231
      self.osparams = {}
1232
    UpgradeBeParams(self.beparams)
1233
    if self.disks_active is None:
1234
      self.disks_active = self.admin_state == constants.ADMINST_UP
1235

    
1236

    
1237
class OS(ConfigObject):
1238
  """Config object representing an operating system.
1239

1240
  @type supported_parameters: list
1241
  @ivar supported_parameters: a list of tuples, name and description,
1242
      containing the supported parameters by this OS
1243

1244
  @type VARIANT_DELIM: string
1245
  @cvar VARIANT_DELIM: the variant delimiter
1246

1247
  """
1248
  __slots__ = [
1249
    "name",
1250
    "path",
1251
    "api_versions",
1252
    "create_script",
1253
    "export_script",
1254
    "import_script",
1255
    "rename_script",
1256
    "verify_script",
1257
    "supported_variants",
1258
    "supported_parameters",
1259
    ]
1260

    
1261
  VARIANT_DELIM = "+"
1262

    
1263
  @classmethod
1264
  def SplitNameVariant(cls, name):
1265
    """Splits the name into the proper name and variant.
1266

1267
    @param name: the OS (unprocessed) name
1268
    @rtype: list
1269
    @return: a list of two elements; if the original name didn't
1270
        contain a variant, it's returned as an empty string
1271

1272
    """
1273
    nv = name.split(cls.VARIANT_DELIM, 1)
1274
    if len(nv) == 1:
1275
      nv.append("")
1276
    return nv
1277

    
1278
  @classmethod
1279
  def GetName(cls, name):
1280
    """Returns the proper name of the os (without the variant).
1281

1282
    @param name: the OS (unprocessed) name
1283

1284
    """
1285
    return cls.SplitNameVariant(name)[0]
1286

    
1287
  @classmethod
1288
  def GetVariant(cls, name):
1289
    """Returns the variant the os (without the base name).
1290

1291
    @param name: the OS (unprocessed) name
1292

1293
    """
1294
    return cls.SplitNameVariant(name)[1]
1295

    
1296

    
1297
class ExtStorage(ConfigObject):
1298
  """Config object representing an External Storage Provider.
1299

1300
  """
1301
  __slots__ = [
1302
    "name",
1303
    "path",
1304
    "create_script",
1305
    "remove_script",
1306
    "grow_script",
1307
    "attach_script",
1308
    "detach_script",
1309
    "setinfo_script",
1310
    "verify_script",
1311
    "supported_parameters",
1312
    ]
1313

    
1314

    
1315
class NodeHvState(ConfigObject):
1316
  """Hypvervisor state on a node.
1317

1318
  @ivar mem_total: Total amount of memory
1319
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1320
    available)
1321
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1322
    rounding
1323
  @ivar mem_inst: Memory used by instances living on node
1324
  @ivar cpu_total: Total node CPU core count
1325
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1326

1327
  """
1328
  __slots__ = [
1329
    "mem_total",
1330
    "mem_node",
1331
    "mem_hv",
1332
    "mem_inst",
1333
    "cpu_total",
1334
    "cpu_node",
1335
    ] + _TIMESTAMPS
1336

    
1337

    
1338
class NodeDiskState(ConfigObject):
1339
  """Disk state on a node.
1340

1341
  """
1342
  __slots__ = [
1343
    "total",
1344
    "reserved",
1345
    "overhead",
1346
    ] + _TIMESTAMPS
1347

    
1348

    
1349
class Node(TaggableObject):
1350
  """Config object representing a node.
1351

1352
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1353
  @ivar hv_state_static: Hypervisor state overriden by user
1354
  @ivar disk_state: Disk state (e.g. free space)
1355
  @ivar disk_state_static: Disk state overriden by user
1356

1357
  """
1358
  __slots__ = [
1359
    "name",
1360
    "primary_ip",
1361
    "secondary_ip",
1362
    "serial_no",
1363
    "master_candidate",
1364
    "offline",
1365
    "drained",
1366
    "group",
1367
    "master_capable",
1368
    "vm_capable",
1369
    "ndparams",
1370
    "powered",
1371
    "hv_state",
1372
    "hv_state_static",
1373
    "disk_state",
1374
    "disk_state_static",
1375
    ] + _TIMESTAMPS + _UUID
1376

    
1377
  def UpgradeConfig(self):
1378
    """Fill defaults for missing configuration values.
1379

1380
    """
1381
    # pylint: disable=E0203
1382
    # because these are "defined" via slots, not manually
1383
    if self.master_capable is None:
1384
      self.master_capable = True
1385

    
1386
    if self.vm_capable is None:
1387
      self.vm_capable = True
1388

    
1389
    if self.ndparams is None:
1390
      self.ndparams = {}
1391
    # And remove any global parameter
1392
    for key in constants.NDC_GLOBALS:
1393
      if key in self.ndparams:
1394
        logging.warning("Ignoring %s node parameter for node %s",
1395
                        key, self.name)
1396
        del self.ndparams[key]
1397

    
1398
    if self.powered is None:
1399
      self.powered = True
1400

    
1401
  def ToDict(self):
1402
    """Custom function for serializing.
1403

1404
    """
1405
    data = super(Node, self).ToDict()
1406

    
1407
    hv_state = data.get("hv_state", None)
1408
    if hv_state is not None:
1409
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1410

    
1411
    disk_state = data.get("disk_state", None)
1412
    if disk_state is not None:
1413
      data["disk_state"] = \
1414
        dict((key, outils.ContainerToDicts(value))
1415
             for (key, value) in disk_state.items())
1416

    
1417
    return data
1418

    
1419
  @classmethod
1420
  def FromDict(cls, val):
1421
    """Custom function for deserializing.
1422

1423
    """
1424
    obj = super(Node, cls).FromDict(val)
1425

    
1426
    if obj.hv_state is not None:
1427
      obj.hv_state = \
1428
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1429

    
1430
    if obj.disk_state is not None:
1431
      obj.disk_state = \
1432
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1433
             for (key, value) in obj.disk_state.items())
1434

    
1435
    return obj
1436

    
1437

    
1438
class NodeGroup(TaggableObject):
1439
  """Config object representing a node group."""
1440
  __slots__ = [
1441
    "name",
1442
    "members",
1443
    "ndparams",
1444
    "diskparams",
1445
    "ipolicy",
1446
    "serial_no",
1447
    "hv_state_static",
1448
    "disk_state_static",
1449
    "alloc_policy",
1450
    "networks",
1451
    ] + _TIMESTAMPS + _UUID
1452

    
1453
  def ToDict(self):
1454
    """Custom function for nodegroup.
1455

1456
    This discards the members object, which gets recalculated and is only kept
1457
    in memory.
1458

1459
    """
1460
    mydict = super(NodeGroup, self).ToDict()
1461
    del mydict["members"]
1462
    return mydict
1463

    
1464
  @classmethod
1465
  def FromDict(cls, val):
1466
    """Custom function for nodegroup.
1467

1468
    The members slot is initialized to an empty list, upon deserialization.
1469

1470
    """
1471
    obj = super(NodeGroup, cls).FromDict(val)
1472
    obj.members = []
1473
    return obj
1474

    
1475
  def UpgradeConfig(self):
1476
    """Fill defaults for missing configuration values.
1477

1478
    """
1479
    if self.ndparams is None:
1480
      self.ndparams = {}
1481

    
1482
    if self.serial_no is None:
1483
      self.serial_no = 1
1484

    
1485
    if self.alloc_policy is None:
1486
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1487

    
1488
    # We only update mtime, and not ctime, since we would not be able
1489
    # to provide a correct value for creation time.
1490
    if self.mtime is None:
1491
      self.mtime = time.time()
1492

    
1493
    if self.diskparams is None:
1494
      self.diskparams = {}
1495
    if self.ipolicy is None:
1496
      self.ipolicy = MakeEmptyIPolicy()
1497

    
1498
    if self.networks is None:
1499
      self.networks = {}
1500

    
1501
  def FillND(self, node):
1502
    """Return filled out ndparams for L{objects.Node}
1503

1504
    @type node: L{objects.Node}
1505
    @param node: A Node object to fill
1506
    @return a copy of the node's ndparams with defaults filled
1507

1508
    """
1509
    return self.SimpleFillND(node.ndparams)
1510

    
1511
  def SimpleFillND(self, ndparams):
1512
    """Fill a given ndparams dict with defaults.
1513

1514
    @type ndparams: dict
1515
    @param ndparams: the dict to fill
1516
    @rtype: dict
1517
    @return: a copy of the passed in ndparams with missing keys filled
1518
        from the node group defaults
1519

1520
    """
1521
    return FillDict(self.ndparams, ndparams)
1522

    
1523

    
1524
class Cluster(TaggableObject):
1525
  """Config object representing the cluster."""
1526
  __slots__ = [
1527
    "serial_no",
1528
    "rsahostkeypub",
1529
    "highest_used_port",
1530
    "tcpudp_port_pool",
1531
    "mac_prefix",
1532
    "volume_group_name",
1533
    "reserved_lvs",
1534
    "drbd_usermode_helper",
1535
    "default_bridge",
1536
    "default_hypervisor",
1537
    "master_node",
1538
    "master_ip",
1539
    "master_netdev",
1540
    "master_netmask",
1541
    "use_external_mip_script",
1542
    "cluster_name",
1543
    "file_storage_dir",
1544
    "shared_file_storage_dir",
1545
    "enabled_hypervisors",
1546
    "hvparams",
1547
    "ipolicy",
1548
    "os_hvp",
1549
    "beparams",
1550
    "osparams",
1551
    "nicparams",
1552
    "ndparams",
1553
    "diskparams",
1554
    "candidate_pool_size",
1555
    "modify_etc_hosts",
1556
    "modify_ssh_setup",
1557
    "maintain_node_health",
1558
    "uid_pool",
1559
    "default_iallocator",
1560
    "hidden_os",
1561
    "blacklisted_os",
1562
    "primary_ip_family",
1563
    "prealloc_wipe_disks",
1564
    "hv_state_static",
1565
    "disk_state_static",
1566
    "enabled_disk_templates",
1567
    ] + _TIMESTAMPS + _UUID
1568

    
1569
  def UpgradeConfig(self):
1570
    """Fill defaults for missing configuration values.
1571

1572
    """
1573
    # pylint: disable=E0203
1574
    # because these are "defined" via slots, not manually
1575
    if self.hvparams is None:
1576
      self.hvparams = constants.HVC_DEFAULTS
1577
    else:
1578
      for hypervisor in self.hvparams:
1579
        self.hvparams[hypervisor] = FillDict(
1580
            constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1581

    
1582
    if self.os_hvp is None:
1583
      self.os_hvp = {}
1584

    
1585
    # osparams added before 2.2
1586
    if self.osparams is None:
1587
      self.osparams = {}
1588

    
1589
    self.ndparams = UpgradeNDParams(self.ndparams)
1590

    
1591
    self.beparams = UpgradeGroupedParams(self.beparams,
1592
                                         constants.BEC_DEFAULTS)
1593
    for beparams_group in self.beparams:
1594
      UpgradeBeParams(self.beparams[beparams_group])
1595

    
1596
    migrate_default_bridge = not self.nicparams
1597
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1598
                                          constants.NICC_DEFAULTS)
1599
    if migrate_default_bridge:
1600
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1601
        self.default_bridge
1602

    
1603
    if self.modify_etc_hosts is None:
1604
      self.modify_etc_hosts = True
1605

    
1606
    if self.modify_ssh_setup is None:
1607
      self.modify_ssh_setup = True
1608

    
1609
    # default_bridge is no longer used in 2.1. The slot is left there to
1610
    # support auto-upgrading. It can be removed once we decide to deprecate
1611
    # upgrading straight from 2.0.
1612
    if self.default_bridge is not None:
1613
      self.default_bridge = None
1614

    
1615
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1616
    # code can be removed once upgrading straight from 2.0 is deprecated.
1617
    if self.default_hypervisor is not None:
1618
      self.enabled_hypervisors = ([self.default_hypervisor] +
1619
                                  [hvname for hvname in self.enabled_hypervisors
1620
                                   if hvname != self.default_hypervisor])
1621
      self.default_hypervisor = None
1622

    
1623
    # maintain_node_health added after 2.1.1
1624
    if self.maintain_node_health is None:
1625
      self.maintain_node_health = False
1626

    
1627
    if self.uid_pool is None:
1628
      self.uid_pool = []
1629

    
1630
    if self.default_iallocator is None:
1631
      self.default_iallocator = ""
1632

    
1633
    # reserved_lvs added before 2.2
1634
    if self.reserved_lvs is None:
1635
      self.reserved_lvs = []
1636

    
1637
    # hidden and blacklisted operating systems added before 2.2.1
1638
    if self.hidden_os is None:
1639
      self.hidden_os = []
1640

    
1641
    if self.blacklisted_os is None:
1642
      self.blacklisted_os = []
1643

    
1644
    # primary_ip_family added before 2.3
1645
    if self.primary_ip_family is None:
1646
      self.primary_ip_family = AF_INET
1647

    
1648
    if self.master_netmask is None:
1649
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1650
      self.master_netmask = ipcls.iplen
1651

    
1652
    if self.prealloc_wipe_disks is None:
1653
      self.prealloc_wipe_disks = False
1654

    
1655
    # shared_file_storage_dir added before 2.5
1656
    if self.shared_file_storage_dir is None:
1657
      self.shared_file_storage_dir = ""
1658

    
1659
    if self.use_external_mip_script is None:
1660
      self.use_external_mip_script = False
1661

    
1662
    if self.diskparams:
1663
      self.diskparams = UpgradeDiskParams(self.diskparams)
1664
    else:
1665
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1666

    
1667
    # instance policy added before 2.6
1668
    if self.ipolicy is None:
1669
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1670
    else:
1671
      # we can either make sure to upgrade the ipolicy always, or only
1672
      # do it in some corner cases (e.g. missing keys); note that this
1673
      # will break any removal of keys from the ipolicy dict
1674
      wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1675
      if wrongkeys:
1676
        # These keys would be silently removed by FillIPolicy()
1677
        msg = ("Cluster instance policy contains spurious keys: %s" %
1678
               utils.CommaJoin(wrongkeys))
1679
        raise errors.ConfigurationError(msg)
1680
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1681

    
1682
  @property
1683
  def primary_hypervisor(self):
1684
    """The first hypervisor is the primary.
1685

1686
    Useful, for example, for L{Node}'s hv/disk state.
1687

1688
    """
1689
    return self.enabled_hypervisors[0]
1690

    
1691
  def ToDict(self):
1692
    """Custom function for cluster.
1693

1694
    """
1695
    mydict = super(Cluster, self).ToDict()
1696

    
1697
    if self.tcpudp_port_pool is None:
1698
      tcpudp_port_pool = []
1699
    else:
1700
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1701

    
1702
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1703

    
1704
    return mydict
1705

    
1706
  @classmethod
1707
  def FromDict(cls, val):
1708
    """Custom function for cluster.
1709

1710
    """
1711
    obj = super(Cluster, cls).FromDict(val)
1712

    
1713
    if obj.tcpudp_port_pool is None:
1714
      obj.tcpudp_port_pool = set()
1715
    elif not isinstance(obj.tcpudp_port_pool, set):
1716
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1717

    
1718
    return obj
1719

    
1720
  def SimpleFillDP(self, diskparams):
1721
    """Fill a given diskparams dict with cluster defaults.
1722

1723
    @param diskparams: The diskparams
1724
    @return: The defaults dict
1725

1726
    """
1727
    return FillDiskParams(self.diskparams, diskparams)
1728

    
1729
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1730
    """Get the default hypervisor parameters for the cluster.
1731

1732
    @param hypervisor: the hypervisor name
1733
    @param os_name: if specified, we'll also update the defaults for this OS
1734
    @param skip_keys: if passed, list of keys not to use
1735
    @return: the defaults dict
1736

1737
    """
1738
    if skip_keys is None:
1739
      skip_keys = []
1740

    
1741
    fill_stack = [self.hvparams.get(hypervisor, {})]
1742
    if os_name is not None:
1743
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1744
      fill_stack.append(os_hvp)
1745

    
1746
    ret_dict = {}
1747
    for o_dict in fill_stack:
1748
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1749

    
1750
    return ret_dict
1751

    
1752
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1753
    """Fill a given hvparams dict with cluster defaults.
1754

1755
    @type hv_name: string
1756
    @param hv_name: the hypervisor to use
1757
    @type os_name: string
1758
    @param os_name: the OS to use for overriding the hypervisor defaults
1759
    @type skip_globals: boolean
1760
    @param skip_globals: if True, the global hypervisor parameters will
1761
        not be filled
1762
    @rtype: dict
1763
    @return: a copy of the given hvparams with missing keys filled from
1764
        the cluster defaults
1765

1766
    """
1767
    if skip_globals:
1768
      skip_keys = constants.HVC_GLOBALS
1769
    else:
1770
      skip_keys = []
1771

    
1772
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1773
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1774

    
1775
  def FillHV(self, instance, skip_globals=False):
1776
    """Fill an instance's hvparams dict with cluster defaults.
1777

1778
    @type instance: L{objects.Instance}
1779
    @param instance: the instance parameter to fill
1780
    @type skip_globals: boolean
1781
    @param skip_globals: if True, the global hypervisor parameters will
1782
        not be filled
1783
    @rtype: dict
1784
    @return: a copy of the instance's hvparams with missing keys filled from
1785
        the cluster defaults
1786

1787
    """
1788
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1789
                             instance.hvparams, skip_globals)
1790

    
1791
  def SimpleFillBE(self, beparams):
1792
    """Fill a given beparams dict with cluster defaults.
1793

1794
    @type beparams: dict
1795
    @param beparams: the dict to fill
1796
    @rtype: dict
1797
    @return: a copy of the passed in beparams with missing keys filled
1798
        from the cluster defaults
1799

1800
    """
1801
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1802

    
1803
  def FillBE(self, instance):
1804
    """Fill an instance's beparams dict with cluster defaults.
1805

1806
    @type instance: L{objects.Instance}
1807
    @param instance: the instance parameter to fill
1808
    @rtype: dict
1809
    @return: a copy of the instance's beparams with missing keys filled from
1810
        the cluster defaults
1811

1812
    """
1813
    return self.SimpleFillBE(instance.beparams)
1814

    
1815
  def SimpleFillNIC(self, nicparams):
1816
    """Fill a given nicparams dict with cluster defaults.
1817

1818
    @type nicparams: dict
1819
    @param nicparams: the dict to fill
1820
    @rtype: dict
1821
    @return: a copy of the passed in nicparams with missing keys filled
1822
        from the cluster defaults
1823

1824
    """
1825
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1826

    
1827
  def SimpleFillOS(self, os_name, os_params):
1828
    """Fill an instance's osparams dict with cluster defaults.
1829

1830
    @type os_name: string
1831
    @param os_name: the OS name to use
1832
    @type os_params: dict
1833
    @param os_params: the dict to fill with default values
1834
    @rtype: dict
1835
    @return: a copy of the instance's osparams with missing keys filled from
1836
        the cluster defaults
1837

1838
    """
1839
    name_only = os_name.split("+", 1)[0]
1840
    # base OS
1841
    result = self.osparams.get(name_only, {})
1842
    # OS with variant
1843
    result = FillDict(result, self.osparams.get(os_name, {}))
1844
    # specified params
1845
    return FillDict(result, os_params)
1846

    
1847
  @staticmethod
1848
  def SimpleFillHvState(hv_state):
1849
    """Fill an hv_state sub dict with cluster defaults.
1850

1851
    """
1852
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1853

    
1854
  @staticmethod
1855
  def SimpleFillDiskState(disk_state):
1856
    """Fill an disk_state sub dict with cluster defaults.
1857

1858
    """
1859
    return FillDict(constants.DS_DEFAULTS, disk_state)
1860

    
1861
  def FillND(self, node, nodegroup):
1862
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1863

1864
    @type node: L{objects.Node}
1865
    @param node: A Node object to fill
1866
    @type nodegroup: L{objects.NodeGroup}
1867
    @param nodegroup: A Node object to fill
1868
    @return a copy of the node's ndparams with defaults filled
1869

1870
    """
1871
    return self.SimpleFillND(nodegroup.FillND(node))
1872

    
1873
  def SimpleFillND(self, ndparams):
1874
    """Fill a given ndparams dict with defaults.
1875

1876
    @type ndparams: dict
1877
    @param ndparams: the dict to fill
1878
    @rtype: dict
1879
    @return: a copy of the passed in ndparams with missing keys filled
1880
        from the cluster defaults
1881

1882
    """
1883
    return FillDict(self.ndparams, ndparams)
1884

    
1885
  def SimpleFillIPolicy(self, ipolicy):
1886
    """ Fill instance policy dict with defaults.
1887

1888
    @type ipolicy: dict
1889
    @param ipolicy: the dict to fill
1890
    @rtype: dict
1891
    @return: a copy of passed ipolicy with missing keys filled from
1892
      the cluster defaults
1893

1894
    """
1895
    return FillIPolicy(self.ipolicy, ipolicy)
1896

    
1897

    
1898
class BlockDevStatus(ConfigObject):
1899
  """Config object representing the status of a block device."""
1900
  __slots__ = [
1901
    "dev_path",
1902
    "major",
1903
    "minor",
1904
    "sync_percent",
1905
    "estimated_time",
1906
    "is_degraded",
1907
    "ldisk_status",
1908
    ]
1909

    
1910

    
1911
class ImportExportStatus(ConfigObject):
1912
  """Config object representing the status of an import or export."""
1913
  __slots__ = [
1914
    "recent_output",
1915
    "listen_port",
1916
    "connected",
1917
    "progress_mbytes",
1918
    "progress_throughput",
1919
    "progress_eta",
1920
    "progress_percent",
1921
    "exit_status",
1922
    "error_message",
1923
    ] + _TIMESTAMPS
1924

    
1925

    
1926
class ImportExportOptions(ConfigObject):
1927
  """Options for import/export daemon
1928

1929
  @ivar key_name: X509 key name (None for cluster certificate)
1930
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1931
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
1932
  @ivar magic: Used to ensure the connection goes to the right disk
1933
  @ivar ipv6: Whether to use IPv6
1934
  @ivar connect_timeout: Number of seconds for establishing connection
1935

1936
  """
1937
  __slots__ = [
1938
    "key_name",
1939
    "ca_pem",
1940
    "compress",
1941
    "magic",
1942
    "ipv6",
1943
    "connect_timeout",
1944
    ]
1945

    
1946

    
1947
class ConfdRequest(ConfigObject):
1948
  """Object holding a confd request.
1949

1950
  @ivar protocol: confd protocol version
1951
  @ivar type: confd query type
1952
  @ivar query: query request
1953
  @ivar rsalt: requested reply salt
1954

1955
  """
1956
  __slots__ = [
1957
    "protocol",
1958
    "type",
1959
    "query",
1960
    "rsalt",
1961
    ]
1962

    
1963

    
1964
class ConfdReply(ConfigObject):
1965
  """Object holding a confd reply.
1966

1967
  @ivar protocol: confd protocol version
1968
  @ivar status: reply status code (ok, error)
1969
  @ivar answer: confd query reply
1970
  @ivar serial: configuration serial number
1971

1972
  """
1973
  __slots__ = [
1974
    "protocol",
1975
    "status",
1976
    "answer",
1977
    "serial",
1978
    ]
1979

    
1980

    
1981
class QueryFieldDefinition(ConfigObject):
1982
  """Object holding a query field definition.
1983

1984
  @ivar name: Field name
1985
  @ivar title: Human-readable title
1986
  @ivar kind: Field type
1987
  @ivar doc: Human-readable description
1988

1989
  """
1990
  __slots__ = [
1991
    "name",
1992
    "title",
1993
    "kind",
1994
    "doc",
1995
    ]
1996

    
1997

    
1998
class _QueryResponseBase(ConfigObject):
1999
  __slots__ = [
2000
    "fields",
2001
    ]
2002

    
2003
  def ToDict(self):
2004
    """Custom function for serializing.
2005

2006
    """
2007
    mydict = super(_QueryResponseBase, self).ToDict()
2008
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2009
    return mydict
2010

    
2011
  @classmethod
2012
  def FromDict(cls, val):
2013
    """Custom function for de-serializing.
2014

2015
    """
2016
    obj = super(_QueryResponseBase, cls).FromDict(val)
2017
    obj.fields = \
2018
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2019
    return obj
2020

    
2021

    
2022
class QueryResponse(_QueryResponseBase):
2023
  """Object holding the response to a query.
2024

2025
  @ivar fields: List of L{QueryFieldDefinition} objects
2026
  @ivar data: Requested data
2027

2028
  """
2029
  __slots__ = [
2030
    "data",
2031
    ]
2032

    
2033

    
2034
class QueryFieldsRequest(ConfigObject):
2035
  """Object holding a request for querying available fields.
2036

2037
  """
2038
  __slots__ = [
2039
    "what",
2040
    "fields",
2041
    ]
2042

    
2043

    
2044
class QueryFieldsResponse(_QueryResponseBase):
2045
  """Object holding the response to a query for fields.
2046

2047
  @ivar fields: List of L{QueryFieldDefinition} objects
2048

2049
  """
2050
  __slots__ = []
2051

    
2052

    
2053
class MigrationStatus(ConfigObject):
2054
  """Object holding the status of a migration.
2055

2056
  """
2057
  __slots__ = [
2058
    "status",
2059
    "transferred_ram",
2060
    "total_ram",
2061
    ]
2062

    
2063

    
2064
class InstanceConsole(ConfigObject):
2065
  """Object describing how to access the console of an instance.
2066

2067
  """
2068
  __slots__ = [
2069
    "instance",
2070
    "kind",
2071
    "message",
2072
    "host",
2073
    "port",
2074
    "user",
2075
    "command",
2076
    "display",
2077
    ]
2078

    
2079
  def Validate(self):
2080
    """Validates contents of this object.
2081

2082
    """
2083
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2084
    assert self.instance, "Missing instance name"
2085
    assert self.message or self.kind in [constants.CONS_SSH,
2086
                                         constants.CONS_SPICE,
2087
                                         constants.CONS_VNC]
2088
    assert self.host or self.kind == constants.CONS_MESSAGE
2089
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2090
                                      constants.CONS_SSH]
2091
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2092
                                      constants.CONS_SPICE,
2093
                                      constants.CONS_VNC]
2094
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2095
                                         constants.CONS_SPICE,
2096
                                         constants.CONS_VNC]
2097
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2098
                                         constants.CONS_SPICE,
2099
                                         constants.CONS_SSH]
2100
    return True
2101

    
2102

    
2103
class Network(TaggableObject):
2104
  """Object representing a network definition for ganeti.
2105

2106
  """
2107
  __slots__ = [
2108
    "name",
2109
    "serial_no",
2110
    "mac_prefix",
2111
    "network",
2112
    "network6",
2113
    "gateway",
2114
    "gateway6",
2115
    "reservations",
2116
    "ext_reservations",
2117
    ] + _TIMESTAMPS + _UUID
2118

    
2119
  def HooksDict(self, prefix=""):
2120
    """Export a dictionary used by hooks with a network's information.
2121

2122
    @type prefix: String
2123
    @param prefix: Prefix to prepend to the dict entries
2124

2125
    """
2126
    result = {
2127
      "%sNETWORK_NAME" % prefix: self.name,
2128
      "%sNETWORK_UUID" % prefix: self.uuid,
2129
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2130
    }
2131
    if self.network:
2132
      result["%sNETWORK_SUBNET" % prefix] = self.network
2133
    if self.gateway:
2134
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2135
    if self.network6:
2136
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2137
    if self.gateway6:
2138
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2139
    if self.mac_prefix:
2140
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2141

    
2142
    return result
2143

    
2144
  @classmethod
2145
  def FromDict(cls, val):
2146
    """Custom function for networks.
2147

2148
    Remove deprecated network_type and family.
2149

2150
    """
2151
    if "network_type" in val:
2152
      del val["network_type"]
2153
    if "family" in val:
2154
      del val["family"]
2155
    obj = super(Network, cls).FromDict(val)
2156
    return obj
2157

    
2158

    
2159
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2160
  """Simple wrapper over ConfigParse that allows serialization.
2161

2162
  This class is basically ConfigParser.SafeConfigParser with two
2163
  additional methods that allow it to serialize/unserialize to/from a
2164
  buffer.
2165

2166
  """
2167
  def Dumps(self):
2168
    """Dump this instance and return the string representation."""
2169
    buf = StringIO()
2170
    self.write(buf)
2171
    return buf.getvalue()
2172

    
2173
  @classmethod
2174
  def Loads(cls, data):
2175
    """Load data from a string."""
2176
    buf = StringIO(data)
2177
    cfp = cls()
2178
    cfp.readfp(buf)
2179
    return cfp
2180

    
2181

    
2182
class LvmPvInfo(ConfigObject):
2183
  """Information about an LVM physical volume (PV).
2184

2185
  @type name: string
2186
  @ivar name: name of the PV
2187
  @type vg_name: string
2188
  @ivar vg_name: name of the volume group containing the PV
2189
  @type size: float
2190
  @ivar size: size of the PV in MiB
2191
  @type free: float
2192
  @ivar free: free space in the PV, in MiB
2193
  @type attributes: string
2194
  @ivar attributes: PV attributes
2195
  @type lv_list: list of strings
2196
  @ivar lv_list: names of the LVs hosted on the PV
2197
  """
2198
  __slots__ = [
2199
    "name",
2200
    "vg_name",
2201
    "size",
2202
    "free",
2203
    "attributes",
2204
    "lv_list"
2205
    ]
2206

    
2207
  def IsEmpty(self):
2208
    """Is this PV empty?
2209

2210
    """
2211
    return self.size <= (self.free + 1)
2212

    
2213
  def IsAllocatable(self):
2214
    """Is this PV allocatable?
2215

2216
    """
2217
    return ("a" in self.attributes)