Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ b54ecf12

History | View | Annotate | Download (63.5 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 name: master name
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
    "name",
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", "nicparams", "netinfo"] + _UUID
493

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

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

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

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

    
512

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

640
    This only works for VG-based disks.
641

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

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

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

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

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

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

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

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

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

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

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

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

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

713
    Arguments:
714
      - target_node: the node we wish to configure for
715
      - nodes_ip: a mapping of node name to ip
716

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
856
    assert disk_template in disk_params
857

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

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

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

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

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

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

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

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

    
905
    return result
906

    
907

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1050

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

    
1069
  def _ComputeSecondaryNodes(self):
1070
    """Compute the list of secondary nodes.
1071

1072
    This is a simple wrapper over _ComputeAllNodes.
1073

1074
    """
1075
    all_nodes = set(self._ComputeAllNodes())
1076
    all_nodes.discard(self.primary_node)
1077
    return tuple(all_nodes)
1078

    
1079
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1080
                             "List of names of secondary nodes")
1081

    
1082
  def _ComputeAllNodes(self):
1083
    """Compute the list of all nodes.
1084

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

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

    
1101
    all_nodes = set()
1102
    all_nodes.add(self.primary_node)
1103
    for device in self.disks:
1104
      _Helper(all_nodes, device)
1105
    return tuple(all_nodes)
1106

    
1107
  all_nodes = property(_ComputeAllNodes, None, None,
1108
                       "List of names of all the nodes of the instance")
1109

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

1113
    This function figures out what logical volumes should belong on
1114
    which nodes, recursing through a device tree.
1115

1116
    @param lvmap: optional dictionary to receive the
1117
        'node' : ['lv', ...] data.
1118

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

1124
    """
1125
    if node is None:
1126
      node = self.primary_node
1127

    
1128
    if lvmap is None:
1129
      lvmap = {
1130
        node: [],
1131
        }
1132
      ret = lvmap
1133
    else:
1134
      if not node in lvmap:
1135
        lvmap[node] = []
1136
      ret = None
1137

    
1138
    if not devs:
1139
      devs = self.disks
1140

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

    
1145
      elif dev.dev_type in constants.LDS_DRBD:
1146
        if dev.children:
1147
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1148
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1149

    
1150
      elif dev.children:
1151
        self.MapLVsByNode(lvmap, dev.children, node)
1152

    
1153
    return ret
1154

    
1155
  def FindDisk(self, idx):
1156
    """Find a disk given having a specified index.
1157

1158
    This is just a wrapper that does validation of the index.
1159

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

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

    
1178
  def ToDict(self):
1179
    """Instance-specific conversion to standard python types.
1180

1181
    This replaces the children lists of objects with lists of standard
1182
    python types.
1183

1184
    """
1185
    bo = super(Instance, self).ToDict()
1186

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

    
1196
  @classmethod
1197
  def FromDict(cls, val):
1198
    """Custom function for instances.
1199

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

    
1213
  def UpgradeConfig(self):
1214
    """Fill defaults for missing configuration values.
1215

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

    
1231

    
1232
class OS(ConfigObject):
1233
  """Config object representing an operating system.
1234

1235
  @type supported_parameters: list
1236
  @ivar supported_parameters: a list of tuples, name and description,
1237
      containing the supported parameters by this OS
1238

1239
  @type VARIANT_DELIM: string
1240
  @cvar VARIANT_DELIM: the variant delimiter
1241

1242
  """
1243
  __slots__ = [
1244
    "name",
1245
    "path",
1246
    "api_versions",
1247
    "create_script",
1248
    "export_script",
1249
    "import_script",
1250
    "rename_script",
1251
    "verify_script",
1252
    "supported_variants",
1253
    "supported_parameters",
1254
    ]
1255

    
1256
  VARIANT_DELIM = "+"
1257

    
1258
  @classmethod
1259
  def SplitNameVariant(cls, name):
1260
    """Splits the name into the proper name and variant.
1261

1262
    @param name: the OS (unprocessed) name
1263
    @rtype: list
1264
    @return: a list of two elements; if the original name didn't
1265
        contain a variant, it's returned as an empty string
1266

1267
    """
1268
    nv = name.split(cls.VARIANT_DELIM, 1)
1269
    if len(nv) == 1:
1270
      nv.append("")
1271
    return nv
1272

    
1273
  @classmethod
1274
  def GetName(cls, name):
1275
    """Returns the proper name of the os (without the variant).
1276

1277
    @param name: the OS (unprocessed) name
1278

1279
    """
1280
    return cls.SplitNameVariant(name)[0]
1281

    
1282
  @classmethod
1283
  def GetVariant(cls, name):
1284
    """Returns the variant the os (without the base name).
1285

1286
    @param name: the OS (unprocessed) name
1287

1288
    """
1289
    return cls.SplitNameVariant(name)[1]
1290

    
1291

    
1292
class ExtStorage(ConfigObject):
1293
  """Config object representing an External Storage Provider.
1294

1295
  """
1296
  __slots__ = [
1297
    "name",
1298
    "path",
1299
    "create_script",
1300
    "remove_script",
1301
    "grow_script",
1302
    "attach_script",
1303
    "detach_script",
1304
    "setinfo_script",
1305
    "verify_script",
1306
    "supported_parameters",
1307
    ]
1308

    
1309

    
1310
class NodeHvState(ConfigObject):
1311
  """Hypvervisor state on a node.
1312

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

1322
  """
1323
  __slots__ = [
1324
    "mem_total",
1325
    "mem_node",
1326
    "mem_hv",
1327
    "mem_inst",
1328
    "cpu_total",
1329
    "cpu_node",
1330
    ] + _TIMESTAMPS
1331

    
1332

    
1333
class NodeDiskState(ConfigObject):
1334
  """Disk state on a node.
1335

1336
  """
1337
  __slots__ = [
1338
    "total",
1339
    "reserved",
1340
    "overhead",
1341
    ] + _TIMESTAMPS
1342

    
1343

    
1344
class Node(TaggableObject):
1345
  """Config object representing a node.
1346

1347
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1348
  @ivar hv_state_static: Hypervisor state overriden by user
1349
  @ivar disk_state: Disk state (e.g. free space)
1350
  @ivar disk_state_static: Disk state overriden by user
1351

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

    
1372
  def UpgradeConfig(self):
1373
    """Fill defaults for missing configuration values.
1374

1375
    """
1376
    # pylint: disable=E0203
1377
    # because these are "defined" via slots, not manually
1378
    if self.master_capable is None:
1379
      self.master_capable = True
1380

    
1381
    if self.vm_capable is None:
1382
      self.vm_capable = True
1383

    
1384
    if self.ndparams is None:
1385
      self.ndparams = {}
1386
    # And remove any global parameter
1387
    for key in constants.NDC_GLOBALS:
1388
      if key in self.ndparams:
1389
        logging.warning("Ignoring %s node parameter for node %s",
1390
                        key, self.name)
1391
        del self.ndparams[key]
1392

    
1393
    if self.powered is None:
1394
      self.powered = True
1395

    
1396
  def ToDict(self):
1397
    """Custom function for serializing.
1398

1399
    """
1400
    data = super(Node, self).ToDict()
1401

    
1402
    hv_state = data.get("hv_state", None)
1403
    if hv_state is not None:
1404
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1405

    
1406
    disk_state = data.get("disk_state", None)
1407
    if disk_state is not None:
1408
      data["disk_state"] = \
1409
        dict((key, outils.ContainerToDicts(value))
1410
             for (key, value) in disk_state.items())
1411

    
1412
    return data
1413

    
1414
  @classmethod
1415
  def FromDict(cls, val):
1416
    """Custom function for deserializing.
1417

1418
    """
1419
    obj = super(Node, cls).FromDict(val)
1420

    
1421
    if obj.hv_state is not None:
1422
      obj.hv_state = \
1423
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1424

    
1425
    if obj.disk_state is not None:
1426
      obj.disk_state = \
1427
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1428
             for (key, value) in obj.disk_state.items())
1429

    
1430
    return obj
1431

    
1432

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

    
1448
  def ToDict(self):
1449
    """Custom function for nodegroup.
1450

1451
    This discards the members object, which gets recalculated and is only kept
1452
    in memory.
1453

1454
    """
1455
    mydict = super(NodeGroup, self).ToDict()
1456
    del mydict["members"]
1457
    return mydict
1458

    
1459
  @classmethod
1460
  def FromDict(cls, val):
1461
    """Custom function for nodegroup.
1462

1463
    The members slot is initialized to an empty list, upon deserialization.
1464

1465
    """
1466
    obj = super(NodeGroup, cls).FromDict(val)
1467
    obj.members = []
1468
    return obj
1469

    
1470
  def UpgradeConfig(self):
1471
    """Fill defaults for missing configuration values.
1472

1473
    """
1474
    if self.ndparams is None:
1475
      self.ndparams = {}
1476

    
1477
    if self.serial_no is None:
1478
      self.serial_no = 1
1479

    
1480
    if self.alloc_policy is None:
1481
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1482

    
1483
    # We only update mtime, and not ctime, since we would not be able
1484
    # to provide a correct value for creation time.
1485
    if self.mtime is None:
1486
      self.mtime = time.time()
1487

    
1488
    if self.diskparams is None:
1489
      self.diskparams = {}
1490
    if self.ipolicy is None:
1491
      self.ipolicy = MakeEmptyIPolicy()
1492

    
1493
    if self.networks is None:
1494
      self.networks = {}
1495

    
1496
  def FillND(self, node):
1497
    """Return filled out ndparams for L{objects.Node}
1498

1499
    @type node: L{objects.Node}
1500
    @param node: A Node object to fill
1501
    @return a copy of the node's ndparams with defaults filled
1502

1503
    """
1504
    return self.SimpleFillND(node.ndparams)
1505

    
1506
  def SimpleFillND(self, ndparams):
1507
    """Fill a given ndparams dict with defaults.
1508

1509
    @type ndparams: dict
1510
    @param ndparams: the dict to fill
1511
    @rtype: dict
1512
    @return: a copy of the passed in ndparams with missing keys filled
1513
        from the node group defaults
1514

1515
    """
1516
    return FillDict(self.ndparams, ndparams)
1517

    
1518

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

    
1564
  def UpgradeConfig(self):
1565
    """Fill defaults for missing configuration values.
1566

1567
    """
1568
    # pylint: disable=E0203
1569
    # because these are "defined" via slots, not manually
1570
    if self.hvparams is None:
1571
      self.hvparams = constants.HVC_DEFAULTS
1572
    else:
1573
      for hypervisor in self.hvparams:
1574
        self.hvparams[hypervisor] = FillDict(
1575
            constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1576

    
1577
    if self.os_hvp is None:
1578
      self.os_hvp = {}
1579

    
1580
    # osparams added before 2.2
1581
    if self.osparams is None:
1582
      self.osparams = {}
1583

    
1584
    self.ndparams = UpgradeNDParams(self.ndparams)
1585

    
1586
    self.beparams = UpgradeGroupedParams(self.beparams,
1587
                                         constants.BEC_DEFAULTS)
1588
    for beparams_group in self.beparams:
1589
      UpgradeBeParams(self.beparams[beparams_group])
1590

    
1591
    migrate_default_bridge = not self.nicparams
1592
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1593
                                          constants.NICC_DEFAULTS)
1594
    if migrate_default_bridge:
1595
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1596
        self.default_bridge
1597

    
1598
    if self.modify_etc_hosts is None:
1599
      self.modify_etc_hosts = True
1600

    
1601
    if self.modify_ssh_setup is None:
1602
      self.modify_ssh_setup = True
1603

    
1604
    # default_bridge is no longer used in 2.1. The slot is left there to
1605
    # support auto-upgrading. It can be removed once we decide to deprecate
1606
    # upgrading straight from 2.0.
1607
    if self.default_bridge is not None:
1608
      self.default_bridge = None
1609

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

    
1618
    # maintain_node_health added after 2.1.1
1619
    if self.maintain_node_health is None:
1620
      self.maintain_node_health = False
1621

    
1622
    if self.uid_pool is None:
1623
      self.uid_pool = []
1624

    
1625
    if self.default_iallocator is None:
1626
      self.default_iallocator = ""
1627

    
1628
    # reserved_lvs added before 2.2
1629
    if self.reserved_lvs is None:
1630
      self.reserved_lvs = []
1631

    
1632
    # hidden and blacklisted operating systems added before 2.2.1
1633
    if self.hidden_os is None:
1634
      self.hidden_os = []
1635

    
1636
    if self.blacklisted_os is None:
1637
      self.blacklisted_os = []
1638

    
1639
    # primary_ip_family added before 2.3
1640
    if self.primary_ip_family is None:
1641
      self.primary_ip_family = AF_INET
1642

    
1643
    if self.master_netmask is None:
1644
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1645
      self.master_netmask = ipcls.iplen
1646

    
1647
    if self.prealloc_wipe_disks is None:
1648
      self.prealloc_wipe_disks = False
1649

    
1650
    # shared_file_storage_dir added before 2.5
1651
    if self.shared_file_storage_dir is None:
1652
      self.shared_file_storage_dir = ""
1653

    
1654
    if self.use_external_mip_script is None:
1655
      self.use_external_mip_script = False
1656

    
1657
    if self.diskparams:
1658
      self.diskparams = UpgradeDiskParams(self.diskparams)
1659
    else:
1660
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1661

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

    
1677
  @property
1678
  def primary_hypervisor(self):
1679
    """The first hypervisor is the primary.
1680

1681
    Useful, for example, for L{Node}'s hv/disk state.
1682

1683
    """
1684
    return self.enabled_hypervisors[0]
1685

    
1686
  def ToDict(self):
1687
    """Custom function for cluster.
1688

1689
    """
1690
    mydict = super(Cluster, self).ToDict()
1691

    
1692
    if self.tcpudp_port_pool is None:
1693
      tcpudp_port_pool = []
1694
    else:
1695
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1696

    
1697
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1698

    
1699
    return mydict
1700

    
1701
  @classmethod
1702
  def FromDict(cls, val):
1703
    """Custom function for cluster.
1704

1705
    """
1706
    obj = super(Cluster, cls).FromDict(val)
1707

    
1708
    if obj.tcpudp_port_pool is None:
1709
      obj.tcpudp_port_pool = set()
1710
    elif not isinstance(obj.tcpudp_port_pool, set):
1711
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1712

    
1713
    return obj
1714

    
1715
  def SimpleFillDP(self, diskparams):
1716
    """Fill a given diskparams dict with cluster defaults.
1717

1718
    @param diskparams: The diskparams
1719
    @return: The defaults dict
1720

1721
    """
1722
    return FillDiskParams(self.diskparams, diskparams)
1723

    
1724
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1725
    """Get the default hypervisor parameters for the cluster.
1726

1727
    @param hypervisor: the hypervisor name
1728
    @param os_name: if specified, we'll also update the defaults for this OS
1729
    @param skip_keys: if passed, list of keys not to use
1730
    @return: the defaults dict
1731

1732
    """
1733
    if skip_keys is None:
1734
      skip_keys = []
1735

    
1736
    fill_stack = [self.hvparams.get(hypervisor, {})]
1737
    if os_name is not None:
1738
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1739
      fill_stack.append(os_hvp)
1740

    
1741
    ret_dict = {}
1742
    for o_dict in fill_stack:
1743
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1744

    
1745
    return ret_dict
1746

    
1747
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1748
    """Fill a given hvparams dict with cluster defaults.
1749

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

1761
    """
1762
    if skip_globals:
1763
      skip_keys = constants.HVC_GLOBALS
1764
    else:
1765
      skip_keys = []
1766

    
1767
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1768
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1769

    
1770
  def FillHV(self, instance, skip_globals=False):
1771
    """Fill an instance's hvparams dict with cluster defaults.
1772

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

1782
    """
1783
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1784
                             instance.hvparams, skip_globals)
1785

    
1786
  def SimpleFillBE(self, beparams):
1787
    """Fill a given beparams dict with cluster defaults.
1788

1789
    @type beparams: dict
1790
    @param beparams: the dict to fill
1791
    @rtype: dict
1792
    @return: a copy of the passed in beparams with missing keys filled
1793
        from the cluster defaults
1794

1795
    """
1796
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1797

    
1798
  def FillBE(self, instance):
1799
    """Fill an instance's beparams dict with cluster defaults.
1800

1801
    @type instance: L{objects.Instance}
1802
    @param instance: the instance parameter to fill
1803
    @rtype: dict
1804
    @return: a copy of the instance's beparams with missing keys filled from
1805
        the cluster defaults
1806

1807
    """
1808
    return self.SimpleFillBE(instance.beparams)
1809

    
1810
  def SimpleFillNIC(self, nicparams):
1811
    """Fill a given nicparams dict with cluster defaults.
1812

1813
    @type nicparams: dict
1814
    @param nicparams: the dict to fill
1815
    @rtype: dict
1816
    @return: a copy of the passed in nicparams with missing keys filled
1817
        from the cluster defaults
1818

1819
    """
1820
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1821

    
1822
  def SimpleFillOS(self, os_name, os_params):
1823
    """Fill an instance's osparams dict with cluster defaults.
1824

1825
    @type os_name: string
1826
    @param os_name: the OS name to use
1827
    @type os_params: dict
1828
    @param os_params: the dict to fill with default values
1829
    @rtype: dict
1830
    @return: a copy of the instance's osparams with missing keys filled from
1831
        the cluster defaults
1832

1833
    """
1834
    name_only = os_name.split("+", 1)[0]
1835
    # base OS
1836
    result = self.osparams.get(name_only, {})
1837
    # OS with variant
1838
    result = FillDict(result, self.osparams.get(os_name, {}))
1839
    # specified params
1840
    return FillDict(result, os_params)
1841

    
1842
  @staticmethod
1843
  def SimpleFillHvState(hv_state):
1844
    """Fill an hv_state sub dict with cluster defaults.
1845

1846
    """
1847
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1848

    
1849
  @staticmethod
1850
  def SimpleFillDiskState(disk_state):
1851
    """Fill an disk_state sub dict with cluster defaults.
1852

1853
    """
1854
    return FillDict(constants.DS_DEFAULTS, disk_state)
1855

    
1856
  def FillND(self, node, nodegroup):
1857
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1858

1859
    @type node: L{objects.Node}
1860
    @param node: A Node object to fill
1861
    @type nodegroup: L{objects.NodeGroup}
1862
    @param nodegroup: A Node object to fill
1863
    @return a copy of the node's ndparams with defaults filled
1864

1865
    """
1866
    return self.SimpleFillND(nodegroup.FillND(node))
1867

    
1868
  def SimpleFillND(self, ndparams):
1869
    """Fill a given ndparams dict with defaults.
1870

1871
    @type ndparams: dict
1872
    @param ndparams: the dict to fill
1873
    @rtype: dict
1874
    @return: a copy of the passed in ndparams with missing keys filled
1875
        from the cluster defaults
1876

1877
    """
1878
    return FillDict(self.ndparams, ndparams)
1879

    
1880
  def SimpleFillIPolicy(self, ipolicy):
1881
    """ Fill instance policy dict with defaults.
1882

1883
    @type ipolicy: dict
1884
    @param ipolicy: the dict to fill
1885
    @rtype: dict
1886
    @return: a copy of passed ipolicy with missing keys filled from
1887
      the cluster defaults
1888

1889
    """
1890
    return FillIPolicy(self.ipolicy, ipolicy)
1891

    
1892

    
1893
class BlockDevStatus(ConfigObject):
1894
  """Config object representing the status of a block device."""
1895
  __slots__ = [
1896
    "dev_path",
1897
    "major",
1898
    "minor",
1899
    "sync_percent",
1900
    "estimated_time",
1901
    "is_degraded",
1902
    "ldisk_status",
1903
    ]
1904

    
1905

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

    
1920

    
1921
class ImportExportOptions(ConfigObject):
1922
  """Options for import/export daemon
1923

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

1931
  """
1932
  __slots__ = [
1933
    "key_name",
1934
    "ca_pem",
1935
    "compress",
1936
    "magic",
1937
    "ipv6",
1938
    "connect_timeout",
1939
    ]
1940

    
1941

    
1942
class ConfdRequest(ConfigObject):
1943
  """Object holding a confd request.
1944

1945
  @ivar protocol: confd protocol version
1946
  @ivar type: confd query type
1947
  @ivar query: query request
1948
  @ivar rsalt: requested reply salt
1949

1950
  """
1951
  __slots__ = [
1952
    "protocol",
1953
    "type",
1954
    "query",
1955
    "rsalt",
1956
    ]
1957

    
1958

    
1959
class ConfdReply(ConfigObject):
1960
  """Object holding a confd reply.
1961

1962
  @ivar protocol: confd protocol version
1963
  @ivar status: reply status code (ok, error)
1964
  @ivar answer: confd query reply
1965
  @ivar serial: configuration serial number
1966

1967
  """
1968
  __slots__ = [
1969
    "protocol",
1970
    "status",
1971
    "answer",
1972
    "serial",
1973
    ]
1974

    
1975

    
1976
class QueryFieldDefinition(ConfigObject):
1977
  """Object holding a query field definition.
1978

1979
  @ivar name: Field name
1980
  @ivar title: Human-readable title
1981
  @ivar kind: Field type
1982
  @ivar doc: Human-readable description
1983

1984
  """
1985
  __slots__ = [
1986
    "name",
1987
    "title",
1988
    "kind",
1989
    "doc",
1990
    ]
1991

    
1992

    
1993
class _QueryResponseBase(ConfigObject):
1994
  __slots__ = [
1995
    "fields",
1996
    ]
1997

    
1998
  def ToDict(self):
1999
    """Custom function for serializing.
2000

2001
    """
2002
    mydict = super(_QueryResponseBase, self).ToDict()
2003
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2004
    return mydict
2005

    
2006
  @classmethod
2007
  def FromDict(cls, val):
2008
    """Custom function for de-serializing.
2009

2010
    """
2011
    obj = super(_QueryResponseBase, cls).FromDict(val)
2012
    obj.fields = \
2013
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2014
    return obj
2015

    
2016

    
2017
class QueryResponse(_QueryResponseBase):
2018
  """Object holding the response to a query.
2019

2020
  @ivar fields: List of L{QueryFieldDefinition} objects
2021
  @ivar data: Requested data
2022

2023
  """
2024
  __slots__ = [
2025
    "data",
2026
    ]
2027

    
2028

    
2029
class QueryFieldsRequest(ConfigObject):
2030
  """Object holding a request for querying available fields.
2031

2032
  """
2033
  __slots__ = [
2034
    "what",
2035
    "fields",
2036
    ]
2037

    
2038

    
2039
class QueryFieldsResponse(_QueryResponseBase):
2040
  """Object holding the response to a query for fields.
2041

2042
  @ivar fields: List of L{QueryFieldDefinition} objects
2043

2044
  """
2045
  __slots__ = []
2046

    
2047

    
2048
class MigrationStatus(ConfigObject):
2049
  """Object holding the status of a migration.
2050

2051
  """
2052
  __slots__ = [
2053
    "status",
2054
    "transferred_ram",
2055
    "total_ram",
2056
    ]
2057

    
2058

    
2059
class InstanceConsole(ConfigObject):
2060
  """Object describing how to access the console of an instance.
2061

2062
  """
2063
  __slots__ = [
2064
    "instance",
2065
    "kind",
2066
    "message",
2067
    "host",
2068
    "port",
2069
    "user",
2070
    "command",
2071
    "display",
2072
    ]
2073

    
2074
  def Validate(self):
2075
    """Validates contents of this object.
2076

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

    
2097

    
2098
class Network(TaggableObject):
2099
  """Object representing a network definition for ganeti.
2100

2101
  """
2102
  __slots__ = [
2103
    "name",
2104
    "serial_no",
2105
    "mac_prefix",
2106
    "network",
2107
    "network6",
2108
    "gateway",
2109
    "gateway6",
2110
    "reservations",
2111
    "ext_reservations",
2112
    ] + _TIMESTAMPS + _UUID
2113

    
2114
  def HooksDict(self, prefix=""):
2115
    """Export a dictionary used by hooks with a network's information.
2116

2117
    @type prefix: String
2118
    @param prefix: Prefix to prepend to the dict entries
2119

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

    
2137
    return result
2138

    
2139
  @classmethod
2140
  def FromDict(cls, val):
2141
    """Custom function for networks.
2142

2143
    Remove deprecated network_type and family.
2144

2145
    """
2146
    if "network_type" in val:
2147
      del val["network_type"]
2148
    if "family" in val:
2149
      del val["family"]
2150
    obj = super(Network, cls).FromDict(val)
2151
    return obj
2152

    
2153

    
2154
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2155
  """Simple wrapper over ConfigParse that allows serialization.
2156

2157
  This class is basically ConfigParser.SafeConfigParser with two
2158
  additional methods that allow it to serialize/unserialize to/from a
2159
  buffer.
2160

2161
  """
2162
  def Dumps(self):
2163
    """Dump this instance and return the string representation."""
2164
    buf = StringIO()
2165
    self.write(buf)
2166
    return buf.getvalue()
2167

    
2168
  @classmethod
2169
  def Loads(cls, data):
2170
    """Load data from a string."""
2171
    buf = StringIO(data)
2172
    cfp = cls()
2173
    cfp.readfp(buf)
2174
    return cfp
2175

    
2176

    
2177
class LvmPvInfo(ConfigObject):
2178
  """Information about an LVM physical volume (PV).
2179

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

    
2202
  def IsEmpty(self):
2203
    """Is this PV empty?
2204

2205
    """
2206
    return self.size <= (self.free + 1)
2207

    
2208
  def IsAllocatable(self):
2209
    """Is this PV allocatable?
2210

2211
    """
2212
    return ("a" in self.attributes)