Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ bb3011ad

History | View | Annotate | Download (68.1 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 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
from ganeti import serializer
51

    
52
from socket import AF_INET
53

    
54

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

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

    
61

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

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

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

    
83

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

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

    
97

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

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

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

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

    
110

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

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

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

    
127

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

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

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

    
141

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

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

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

    
156
  return result
157

    
158

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

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

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

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

    
177

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

181
  """
182
  return {}
183

    
184

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

188
  It has the following properties:
189

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

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

197
  """
198
  __slots__ = []
199

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

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

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

215
    """
216

    
217
  def ToDict(self, _with_private=False):
218
    """Convert to a dict holding only standard python types.
219

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

226
    Private fields can be included or not with the _with_private switch.
227
    The actual implementation of this switch is left for those subclassses
228
    with private fields to implement.
229

230
    @type _with_private: bool
231
    @param _with_private: if True, the object will leak its private fields in
232
                          the dictionary representation. If False, the values
233
                          will be replaced with None.
234

235
    """
236
    result = {}
237
    for name in self.GetAllSlots():
238
      value = getattr(self, name, None)
239
      if value is not None:
240
        result[name] = value
241
    return result
242

    
243
  __getstate__ = ToDict
244

    
245
  @classmethod
246
  def FromDict(cls, val):
247
    """Create an object from a dictionary.
248

249
    This generic routine takes a dict, instantiates a new instance of
250
    the given class, and sets attributes based on the dict content.
251

252
    As for `ToDict`, this does not work if the class has children
253
    who are ConfigObjects themselves (e.g. the nics list in an
254
    Instance), in which case the object should subclass the function
255
    and alter the objects.
256

257
    """
258
    if not isinstance(val, dict):
259
      raise errors.ConfigurationError("Invalid object passed to FromDict:"
260
                                      " expected dict, got %s" % type(val))
261
    val_str = dict([(str(k), v) for k, v in val.iteritems()])
262
    obj = cls(**val_str) # pylint: disable=W0142
263
    return obj
264

    
265
  def Copy(self):
266
    """Makes a deep copy of the current object and its children.
267

268
    """
269
    dict_form = self.ToDict()
270
    clone_obj = self.__class__.FromDict(dict_form)
271
    return clone_obj
272

    
273
  def __repr__(self):
274
    """Implement __repr__ for ConfigObjects."""
275
    return repr(self.ToDict())
276

    
277
  def __eq__(self, other):
278
    """Implement __eq__ for ConfigObjects."""
279
    return isinstance(other, self.__class__) and self.ToDict() == other.ToDict()
280

    
281
  def UpgradeConfig(self):
282
    """Fill defaults for missing configuration values.
283

284
    This method will be called at configuration load time, and its
285
    implementation will be object dependent.
286

287
    """
288
    pass
289

    
290

    
291
class TaggableObject(ConfigObject):
292
  """An generic class supporting tags.
293

294
  """
295
  __slots__ = ["tags"]
296
  VALID_TAG_RE = re.compile(r"^[\w.+*/:@-]+$")
297

    
298
  @classmethod
299
  def ValidateTag(cls, tag):
300
    """Check if a tag is valid.
301

302
    If the tag is invalid, an errors.TagError will be raised. The
303
    function has no return value.
304

305
    """
306
    if not isinstance(tag, basestring):
307
      raise errors.TagError("Invalid tag type (not a string)")
308
    if len(tag) > constants.MAX_TAG_LEN:
309
      raise errors.TagError("Tag too long (>%d characters)" %
310
                            constants.MAX_TAG_LEN)
311
    if not tag:
312
      raise errors.TagError("Tags cannot be empty")
313
    if not cls.VALID_TAG_RE.match(tag):
314
      raise errors.TagError("Tag contains invalid characters")
315

    
316
  def GetTags(self):
317
    """Return the tags list.
318

319
    """
320
    tags = getattr(self, "tags", None)
321
    if tags is None:
322
      tags = self.tags = set()
323
    return tags
324

    
325
  def AddTag(self, tag):
326
    """Add a new tag.
327

328
    """
329
    self.ValidateTag(tag)
330
    tags = self.GetTags()
331
    if len(tags) >= constants.MAX_TAGS_PER_OBJ:
332
      raise errors.TagError("Too many tags")
333
    self.GetTags().add(tag)
334

    
335
  def RemoveTag(self, tag):
336
    """Remove a tag.
337

338
    """
339
    self.ValidateTag(tag)
340
    tags = self.GetTags()
341
    try:
342
      tags.remove(tag)
343
    except KeyError:
344
      raise errors.TagError("Tag not found")
345

    
346
  def ToDict(self, _with_private=False):
347
    """Taggable-object-specific conversion to standard python types.
348

349
    This replaces the tags set with a list.
350

351
    """
352
    bo = super(TaggableObject, self).ToDict(_with_private=_with_private)
353

    
354
    tags = bo.get("tags", None)
355
    if isinstance(tags, set):
356
      bo["tags"] = list(tags)
357
    return bo
358

    
359
  @classmethod
360
  def FromDict(cls, val):
361
    """Custom function for instances.
362

363
    """
364
    obj = super(TaggableObject, cls).FromDict(val)
365
    if hasattr(obj, "tags") and isinstance(obj.tags, list):
366
      obj.tags = set(obj.tags)
367
    return obj
368

    
369

    
370
class MasterNetworkParameters(ConfigObject):
371
  """Network configuration parameters for the master
372

373
  @ivar uuid: master nodes UUID
374
  @ivar ip: master IP
375
  @ivar netmask: master netmask
376
  @ivar netdev: master network device
377
  @ivar ip_family: master IP family
378

379
  """
380
  __slots__ = [
381
    "uuid",
382
    "ip",
383
    "netmask",
384
    "netdev",
385
    "ip_family",
386
    ]
387

    
388

    
389
class ConfigData(ConfigObject):
390
  """Top-level config object."""
391
  __slots__ = [
392
    "version",
393
    "cluster",
394
    "nodes",
395
    "nodegroups",
396
    "instances",
397
    "networks",
398
    "disks",
399
    "serial_no",
400
    ] + _TIMESTAMPS
401

    
402
  def ToDict(self, _with_private=False):
403
    """Custom function for top-level config data.
404

405
    This just replaces the list of nodes, instances, nodegroups,
406
    networks, disks and the cluster with standard python types.
407

408
    """
409
    mydict = super(ConfigData, self).ToDict(_with_private=_with_private)
410
    mydict["cluster"] = mydict["cluster"].ToDict()
411
    for key in "nodes", "instances", "nodegroups", "networks", "disks":
412
      mydict[key] = outils.ContainerToDicts(mydict[key])
413

    
414
    return mydict
415

    
416
  @classmethod
417
  def FromDict(cls, val):
418
    """Custom function for top-level config data
419

420
    """
421
    obj = super(ConfigData, cls).FromDict(val)
422
    obj.cluster = Cluster.FromDict(obj.cluster)
423
    obj.nodes = outils.ContainerFromDicts(obj.nodes, dict, Node)
424
    obj.instances = \
425
      outils.ContainerFromDicts(obj.instances, dict, Instance)
426
    obj.nodegroups = \
427
      outils.ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
428
    obj.networks = outils.ContainerFromDicts(obj.networks, dict, Network)
429
    obj.disks = outils.ContainerFromDicts(obj.disks, dict, Disk)
430
    return obj
431

    
432
  def HasAnyDiskOfType(self, dev_type):
433
    """Check if in there is at disk of the given type in the configuration.
434

435
    @type dev_type: L{constants.DTS_BLOCK}
436
    @param dev_type: the type to look for
437
    @rtype: boolean
438
    @return: boolean indicating if a disk of the given type was found or not
439

440
    """
441
    for disk in self.disks.values():
442
      if disk.IsBasedOnDiskType(dev_type):
443
        return True
444
    return False
445

    
446
  def UpgradeConfig(self):
447
    """Fill defaults for missing configuration values.
448

449
    """
450
    self.cluster.UpgradeConfig()
451
    for node in self.nodes.values():
452
      node.UpgradeConfig()
453
    for instance in self.instances.values():
454
      instance.UpgradeConfig()
455
    self._UpgradeEnabledDiskTemplates()
456
    if self.nodegroups is None:
457
      self.nodegroups = {}
458
    for nodegroup in self.nodegroups.values():
459
      nodegroup.UpgradeConfig()
460
      InstancePolicy.UpgradeDiskTemplates(
461
        nodegroup.ipolicy, self.cluster.enabled_disk_templates)
462
    if self.cluster.drbd_usermode_helper is None:
463
      if self.cluster.IsDiskTemplateEnabled(constants.DT_DRBD8):
464
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
465
    if self.networks is None:
466
      self.networks = {}
467
    for network in self.networks.values():
468
      network.UpgradeConfig()
469
    for disk in self.disks.values():
470
      disk.UpgradeConfig()
471

    
472
  def _UpgradeEnabledDiskTemplates(self):
473
    """Upgrade the cluster's enabled disk templates by inspecting the currently
474
       enabled and/or used disk templates.
475

476
    """
477
    if not self.cluster.enabled_disk_templates:
478
      template_set = \
479
        set([inst.disk_template for inst in self.instances.values()])
480
      # Add drbd and plain, if lvm is enabled (by specifying a volume group)
481
      if self.cluster.volume_group_name:
482
        template_set.add(constants.DT_DRBD8)
483
        template_set.add(constants.DT_PLAIN)
484
      # Set enabled_disk_templates to the inferred disk templates. Order them
485
      # according to a preference list that is based on Ganeti's history of
486
      # supported disk templates.
487
      self.cluster.enabled_disk_templates = []
488
      for preferred_template in constants.DISK_TEMPLATE_PREFERENCE:
489
        if preferred_template in template_set:
490
          self.cluster.enabled_disk_templates.append(preferred_template)
491
          template_set.remove(preferred_template)
492
      self.cluster.enabled_disk_templates.extend(list(template_set))
493
    InstancePolicy.UpgradeDiskTemplates(
494
      self.cluster.ipolicy, self.cluster.enabled_disk_templates)
495

    
496

    
497
class NIC(ConfigObject):
498
  """Config object representing a network card."""
499
  __slots__ = ["name", "mac", "ip", "network",
500
               "nicparams", "netinfo", "pci"] + _UUID
501

    
502
  @classmethod
503
  def CheckParameterSyntax(cls, nicparams):
504
    """Check the given parameters for validity.
505

506
    @type nicparams:  dict
507
    @param nicparams: dictionary with parameter names/value
508
    @raise errors.ConfigurationError: when a parameter is not valid
509

510
    """
511
    mode = nicparams[constants.NIC_MODE]
512
    if (mode not in constants.NIC_VALID_MODES and
513
        mode != constants.VALUE_AUTO):
514
      raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
515

    
516
    if (mode == constants.NIC_MODE_BRIDGED and
517
        not nicparams[constants.NIC_LINK]):
518
      raise errors.ConfigurationError("Missing bridged NIC link")
519

    
520

    
521
class Disk(ConfigObject):
522
  """Config object representing a block device."""
523
  __slots__ = (["name", "dev_type", "logical_id", "children", "iv_name",
524
                "size", "mode", "params", "spindles", "pci", "instance",
525
                "serial_no"]
526
               + _UUID + _TIMESTAMPS +
527
               # dynamic_params is special. It depends on the node this instance
528
               # is sent to, and should not be persisted.
529
               ["dynamic_params"])
530

    
531
  def _ComputeAllNodes(self):
532
    """Compute the list of all nodes covered by a device and its children."""
533
    nodes = list()
534

    
535
    if self.dev_type in constants.DTS_DRBD:
536
      nodea, nodeb = self.logical_id[:2]
537
      nodes.append(nodea)
538
      nodes.append(nodeb)
539
    if self.children:
540
      for child in self.children:
541
        nodes.extend(child.all_nodes)
542

    
543
    return tuple(set(nodes))
544

    
545
  all_nodes = property(_ComputeAllNodes, None, None,
546
                       "List of names of all the nodes of a disk")
547

    
548
  def CreateOnSecondary(self):
549
    """Test if this device needs to be created on a secondary node."""
550
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
551

    
552
  def AssembleOnSecondary(self):
553
    """Test if this device needs to be assembled on a secondary node."""
554
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
555

    
556
  def OpenOnSecondary(self):
557
    """Test if this device needs to be opened on a secondary node."""
558
    return self.dev_type in (constants.DT_PLAIN,)
559

    
560
  def StaticDevPath(self):
561
    """Return the device path if this device type has a static one.
562

563
    Some devices (LVM for example) live always at the same /dev/ path,
564
    irrespective of their status. For such devices, we return this
565
    path, for others we return None.
566

567
    @warning: The path returned is not a normalized pathname; callers
568
        should check that it is a valid path.
569

570
    """
571
    if self.dev_type == constants.DT_PLAIN:
572
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
573
    elif self.dev_type == constants.DT_BLOCK:
574
      return self.logical_id[1]
575
    elif self.dev_type == constants.DT_RBD:
576
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
577
    return None
578

    
579
  def ChildrenNeeded(self):
580
    """Compute the needed number of children for activation.
581

582
    This method will return either -1 (all children) or a positive
583
    number denoting the minimum number of children needed for
584
    activation (only mirrored devices will usually return >=0).
585

586
    Currently, only DRBD8 supports diskless activation (therefore we
587
    return 0), for all other we keep the previous semantics and return
588
    -1.
589

590
    """
591
    if self.dev_type == constants.DT_DRBD8:
592
      return 0
593
    return -1
594

    
595
  def IsBasedOnDiskType(self, dev_type):
596
    """Check if the disk or its children are based on the given type.
597

598
    @type dev_type: L{constants.DTS_BLOCK}
599
    @param dev_type: the type to look for
600
    @rtype: boolean
601
    @return: boolean indicating if a device of the given type was found or not
602

603
    """
604
    if self.children:
605
      for child in self.children:
606
        if child.IsBasedOnDiskType(dev_type):
607
          return True
608
    return self.dev_type == dev_type
609

    
610
  def GetNodes(self, node_uuid):
611
    """This function returns the nodes this device lives on.
612

613
    Given the node on which the parent of the device lives on (or, in
614
    case of a top-level device, the primary node of the devices'
615
    instance), this function will return a list of nodes on which this
616
    devices needs to (or can) be assembled.
617

618
    """
619
    if self.dev_type in [constants.DT_PLAIN, constants.DT_FILE,
620
                         constants.DT_BLOCK, constants.DT_RBD,
621
                         constants.DT_EXT, constants.DT_SHARED_FILE,
622
                         constants.DT_GLUSTER]:
623
      result = [node_uuid]
624
    elif self.dev_type in constants.DTS_DRBD:
625
      result = [self.logical_id[0], self.logical_id[1]]
626
      if node_uuid not in result:
627
        raise errors.ConfigurationError("DRBD device passed unknown node")
628
    else:
629
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
630
    return result
631

    
632
  def ComputeNodeTree(self, parent_node_uuid):
633
    """Compute the node/disk tree for this disk and its children.
634

635
    This method, given the node on which the parent disk lives, will
636
    return the list of all (node UUID, disk) pairs which describe the disk
637
    tree in the most compact way. For example, a drbd/lvm stack
638
    will be returned as (primary_node, drbd) and (secondary_node, drbd)
639
    which represents all the top-level devices on the nodes.
640

641
    """
642
    my_nodes = self.GetNodes(parent_node_uuid)
643
    result = [(node, self) for node in my_nodes]
644
    if not self.children:
645
      # leaf device
646
      return result
647
    for node in my_nodes:
648
      for child in self.children:
649
        child_result = child.ComputeNodeTree(node)
650
        if len(child_result) == 1:
651
          # child (and all its descendants) is simple, doesn't split
652
          # over multiple hosts, so we don't need to describe it, our
653
          # own entry for this node describes it completely
654
          continue
655
        else:
656
          # check if child nodes differ from my nodes; note that
657
          # subdisk can differ from the child itself, and be instead
658
          # one of its descendants
659
          for subnode, subdisk in child_result:
660
            if subnode not in my_nodes:
661
              result.append((subnode, subdisk))
662
            # otherwise child is under our own node, so we ignore this
663
            # entry (but probably the other results in the list will
664
            # be different)
665
    return result
666

    
667
  def ComputeGrowth(self, amount):
668
    """Compute the per-VG growth requirements.
669

670
    This only works for VG-based disks.
671

672
    @type amount: integer
673
    @param amount: the desired increase in (user-visible) disk space
674
    @rtype: dict
675
    @return: a dictionary of volume-groups and the required size
676

677
    """
678
    if self.dev_type == constants.DT_PLAIN:
679
      return {self.logical_id[0]: amount}
680
    elif self.dev_type == constants.DT_DRBD8:
681
      if self.children:
682
        return self.children[0].ComputeGrowth(amount)
683
      else:
684
        return {}
685
    else:
686
      # Other disk types do not require VG space
687
      return {}
688

    
689
  def RecordGrow(self, amount):
690
    """Update the size of this disk after growth.
691

692
    This method recurses over the disks's children and updates their
693
    size correspondigly. The method needs to be kept in sync with the
694
    actual algorithms from bdev.
695

696
    """
697
    if self.dev_type in (constants.DT_PLAIN, constants.DT_FILE,
698
                         constants.DT_RBD, constants.DT_EXT,
699
                         constants.DT_SHARED_FILE, constants.DT_GLUSTER):
700
      self.size += amount
701
    elif self.dev_type == constants.DT_DRBD8:
702
      if self.children:
703
        self.children[0].RecordGrow(amount)
704
      self.size += amount
705
    else:
706
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
707
                                   " disk type %s" % self.dev_type)
708

    
709
  def Update(self, size=None, mode=None, spindles=None):
710
    """Apply changes to size, spindles and mode.
711

712
    """
713
    if self.dev_type == constants.DT_DRBD8:
714
      if self.children:
715
        self.children[0].Update(size=size, mode=mode)
716
    else:
717
      assert not self.children
718

    
719
    if size is not None:
720
      self.size = size
721
    if mode is not None:
722
      self.mode = mode
723
    if spindles is not None:
724
      self.spindles = spindles
725

    
726
  def UnsetSize(self):
727
    """Sets recursively the size to zero for the disk and its children.
728

729
    """
730
    if self.children:
731
      for child in self.children:
732
        child.UnsetSize()
733
    self.size = 0
734

    
735
  def UpdateDynamicDiskParams(self, target_node_uuid, nodes_ip):
736
    """Updates the dynamic disk params for the given node.
737

738
    This is mainly used for drbd, which needs ip/port configuration.
739

740
    Arguments:
741
      - target_node_uuid: the node UUID we wish to configure for
742
      - nodes_ip: a mapping of node name to ip
743

744
    The target_node must exist in nodes_ip, and should be one of the
745
    nodes in the logical ID if this device is a DRBD device.
746

747
    """
748
    if self.children:
749
      for child in self.children:
750
        child.UpdateDynamicDiskParams(target_node_uuid, nodes_ip)
751

    
752
    dyn_disk_params = {}
753
    if self.logical_id is not None and self.dev_type in constants.DTS_DRBD:
754
      pnode_uuid, snode_uuid, _, pminor, sminor, _ = self.logical_id
755
      if target_node_uuid not in (pnode_uuid, snode_uuid):
756
        # disk object is being sent to neither the primary nor the secondary
757
        # node. reset the dynamic parameters, the target node is not
758
        # supposed to use them.
759
        self.dynamic_params = dyn_disk_params
760
        return
761

    
762
      pnode_ip = nodes_ip.get(pnode_uuid, None)
763
      snode_ip = nodes_ip.get(snode_uuid, None)
764
      if pnode_ip is None or snode_ip is None:
765
        raise errors.ConfigurationError("Can't find primary or secondary node"
766
                                        " for %s" % str(self))
767
      if pnode_uuid == target_node_uuid:
768
        dyn_disk_params[constants.DDP_LOCAL_IP] = pnode_ip
769
        dyn_disk_params[constants.DDP_REMOTE_IP] = snode_ip
770
        dyn_disk_params[constants.DDP_LOCAL_MINOR] = pminor
771
        dyn_disk_params[constants.DDP_REMOTE_MINOR] = sminor
772
      else: # it must be secondary, we tested above
773
        dyn_disk_params[constants.DDP_LOCAL_IP] = snode_ip
774
        dyn_disk_params[constants.DDP_REMOTE_IP] = pnode_ip
775
        dyn_disk_params[constants.DDP_LOCAL_MINOR] = sminor
776
        dyn_disk_params[constants.DDP_REMOTE_MINOR] = pminor
777

    
778
    self.dynamic_params = dyn_disk_params
779

    
780
  # pylint: disable=W0221
781
  def ToDict(self, include_dynamic_params=False,
782
             _with_private=False):
783
    """Disk-specific conversion to standard python types.
784

785
    This replaces the children lists of objects with lists of
786
    standard python types.
787

788
    """
789
    bo = super(Disk, self).ToDict()
790
    if not include_dynamic_params and "dynamic_params" in bo:
791
      del bo["dynamic_params"]
792

    
793
    for attr in ("children",):
794
      alist = bo.get(attr, None)
795
      if alist:
796
        bo[attr] = outils.ContainerToDicts(alist)
797
    return bo
798

    
799
  @classmethod
800
  def FromDict(cls, val):
801
    """Custom function for Disks
802

803
    """
804
    obj = super(Disk, cls).FromDict(val)
805
    if obj.children:
806
      obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
807
    if obj.logical_id and isinstance(obj.logical_id, list):
808
      obj.logical_id = tuple(obj.logical_id)
809
    if obj.dev_type in constants.DTS_DRBD:
810
      # we need a tuple of length six here
811
      if len(obj.logical_id) < 6:
812
        obj.logical_id += (None,) * (6 - len(obj.logical_id))
813
    return obj
814

    
815
  def __str__(self):
816
    """Custom str() formatter for disks.
817

818
    """
819
    if self.dev_type == constants.DT_PLAIN:
820
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
821
    elif self.dev_type in constants.DTS_DRBD:
822
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
823
      val = "<DRBD8("
824

    
825
      val += ("hosts=%s/%d-%s/%d, port=%s, " %
826
              (node_a, minor_a, node_b, minor_b, port))
827
      if self.children and self.children.count(None) == 0:
828
        val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
829
      else:
830
        val += "no local storage"
831
    else:
832
      val = ("<Disk(type=%s, logical_id=%s, children=%s" %
833
             (self.dev_type, self.logical_id, self.children))
834
    if self.iv_name is None:
835
      val += ", not visible"
836
    else:
837
      val += ", visible as /dev/%s" % self.iv_name
838
    if self.spindles is not None:
839
      val += ", spindles=%s" % self.spindles
840
    if isinstance(self.size, int):
841
      val += ", size=%dm)>" % self.size
842
    else:
843
      val += ", size='%s')>" % (self.size,)
844
    return val
845

    
846
  def Verify(self):
847
    """Checks that this disk is correctly configured.
848

849
    """
850
    all_errors = []
851
    if self.mode not in constants.DISK_ACCESS_SET:
852
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
853
    return all_errors
854

    
855
  def UpgradeConfig(self):
856
    """Fill defaults for missing configuration values.
857

858
    """
859
    if self.children:
860
      for child in self.children:
861
        child.UpgradeConfig()
862

    
863
    # FIXME: Make this configurable in Ganeti 2.7
864
    # Params should be an empty dict that gets filled any time needed
865
    # In case of ext template we allow arbitrary params that should not
866
    # be overrided during a config reload/upgrade.
867
    if not self.params or not isinstance(self.params, dict):
868
      self.params = {}
869

    
870
    # add here config upgrade for this disk
871

    
872
    # map of legacy device types (mapping differing LD constants to new
873
    # DT constants)
874
    LEG_DEV_TYPE_MAP = {"lvm": constants.DT_PLAIN, "drbd8": constants.DT_DRBD8}
875
    if self.dev_type in LEG_DEV_TYPE_MAP:
876
      self.dev_type = LEG_DEV_TYPE_MAP[self.dev_type]
877

    
878
  @staticmethod
879
  def ComputeLDParams(disk_template, disk_params):
880
    """Computes Logical Disk parameters from Disk Template parameters.
881

882
    @type disk_template: string
883
    @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
884
    @type disk_params: dict
885
    @param disk_params: disk template parameters;
886
                        dict(template_name -> parameters
887
    @rtype: list(dict)
888
    @return: a list of dicts, one for each node of the disk hierarchy. Each dict
889
      contains the LD parameters of the node. The tree is flattened in-order.
890

891
    """
892
    if disk_template not in constants.DISK_TEMPLATES:
893
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
894

    
895
    assert disk_template in disk_params
896

    
897
    result = list()
898
    dt_params = disk_params[disk_template]
899

    
900
    if disk_template == constants.DT_DRBD8:
901
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_DRBD8], {
902
        constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
903
        constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
904
        constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
905
        constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
906
        constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
907
        constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
908
        constants.LDP_PROTOCOL: dt_params[constants.DRBD_PROTOCOL],
909
        constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
910
        constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
911
        constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
912
        constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
913
        constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
914
        constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
915
        }))
916

    
917
      # data LV
918
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
919
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
920
        }))
921

    
922
      # metadata LV
923
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
924
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
925
        }))
926

    
927
    else:
928
      defaults = constants.DISK_LD_DEFAULTS[disk_template]
929
      values = {}
930
      for field in defaults:
931
        values[field] = dt_params[field]
932
      result.append(FillDict(defaults, values))
933

    
934
    return result
935

    
936

    
937
class InstancePolicy(ConfigObject):
938
  """Config object representing instance policy limits dictionary.
939

940
  Note that this object is not actually used in the config, it's just
941
  used as a placeholder for a few functions.
942

943
  """
944
  @classmethod
945
  def UpgradeDiskTemplates(cls, ipolicy, enabled_disk_templates):
946
    """Upgrades the ipolicy configuration."""
947
    if constants.IPOLICY_DTS in ipolicy:
948
      if not set(ipolicy[constants.IPOLICY_DTS]).issubset(
949
        set(enabled_disk_templates)):
950
        ipolicy[constants.IPOLICY_DTS] = list(
951
          set(ipolicy[constants.IPOLICY_DTS]) & set(enabled_disk_templates))
952

    
953
  @classmethod
954
  def CheckParameterSyntax(cls, ipolicy, check_std):
955
    """ Check the instance policy for validity.
956

957
    @type ipolicy: dict
958
    @param ipolicy: dictionary with min/max/std specs and policies
959
    @type check_std: bool
960
    @param check_std: Whether to check std value or just assume compliance
961
    @raise errors.ConfigurationError: when the policy is not legal
962

963
    """
964
    InstancePolicy.CheckISpecSyntax(ipolicy, check_std)
965
    if constants.IPOLICY_DTS in ipolicy:
966
      InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
967
    for key in constants.IPOLICY_PARAMETERS:
968
      if key in ipolicy:
969
        InstancePolicy.CheckParameter(key, ipolicy[key])
970
    wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
971
    if wrong_keys:
972
      raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
973
                                      utils.CommaJoin(wrong_keys))
974

    
975
  @classmethod
976
  def _CheckIncompleteSpec(cls, spec, keyname):
977
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
978
    if missing_params:
979
      msg = ("Missing instance specs parameters for %s: %s" %
980
             (keyname, utils.CommaJoin(missing_params)))
981
      raise errors.ConfigurationError(msg)
982

    
983
  @classmethod
984
  def CheckISpecSyntax(cls, ipolicy, check_std):
985
    """Check the instance policy specs for validity.
986

987
    @type ipolicy: dict
988
    @param ipolicy: dictionary with min/max/std specs
989
    @type check_std: bool
990
    @param check_std: Whether to check std value or just assume compliance
991
    @raise errors.ConfigurationError: when specs are not valid
992

993
    """
994
    if constants.ISPECS_MINMAX not in ipolicy:
995
      # Nothing to check
996
      return
997

    
998
    if check_std and constants.ISPECS_STD not in ipolicy:
999
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
1000
      raise errors.ConfigurationError(msg)
1001
    stdspec = ipolicy.get(constants.ISPECS_STD)
1002
    if check_std:
1003
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
1004

    
1005
    if not ipolicy[constants.ISPECS_MINMAX]:
1006
      raise errors.ConfigurationError("Empty minmax specifications")
1007
    std_is_good = False
1008
    for minmaxspecs in ipolicy[constants.ISPECS_MINMAX]:
1009
      missing = constants.ISPECS_MINMAX_KEYS - frozenset(minmaxspecs.keys())
1010
      if missing:
1011
        msg = "Missing instance specification: %s" % utils.CommaJoin(missing)
1012
        raise errors.ConfigurationError(msg)
1013
      for (key, spec) in minmaxspecs.items():
1014
        InstancePolicy._CheckIncompleteSpec(spec, key)
1015

    
1016
      spec_std_ok = True
1017
      for param in constants.ISPECS_PARAMETERS:
1018
        par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
1019
                                                           param, check_std)
1020
        spec_std_ok = spec_std_ok and par_std_ok
1021
      std_is_good = std_is_good or spec_std_ok
1022
    if not std_is_good:
1023
      raise errors.ConfigurationError("Invalid std specifications")
1024

    
1025
  @classmethod
1026
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
1027
    """Check the instance policy specs for validity on a given key.
1028

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

1032
    @type minmaxspecs: dict
1033
    @param minmaxspecs: dictionary with min and max instance spec
1034
    @type stdspec: dict
1035
    @param stdspec: dictionary with standard instance spec
1036
    @type name: string
1037
    @param name: what are the limits for
1038
    @type check_std: bool
1039
    @param check_std: Whether to check std value or just assume compliance
1040
    @rtype: bool
1041
    @return: C{True} when specs are valid, C{False} when standard spec for the
1042
        given name is not valid
1043
    @raise errors.ConfigurationError: when min/max specs for the given name
1044
        are not valid
1045

1046
    """
1047
    minspec = minmaxspecs[constants.ISPECS_MIN]
1048
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1049
    min_v = minspec[name]
1050
    max_v = maxspec[name]
1051

    
1052
    if min_v > max_v:
1053
      err = ("Invalid specification of min/max values for %s: %s/%s" %
1054
             (name, min_v, max_v))
1055
      raise errors.ConfigurationError(err)
1056
    elif check_std:
1057
      std_v = stdspec.get(name, min_v)
1058
      return std_v >= min_v and std_v <= max_v
1059
    else:
1060
      return True
1061

    
1062
  @classmethod
1063
  def CheckDiskTemplates(cls, disk_templates):
1064
    """Checks the disk templates for validity.
1065

1066
    """
1067
    if not disk_templates:
1068
      raise errors.ConfigurationError("Instance policy must contain" +
1069
                                      " at least one disk template")
1070
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1071
    if wrong:
1072
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1073
                                      utils.CommaJoin(wrong))
1074

    
1075
  @classmethod
1076
  def CheckParameter(cls, key, value):
1077
    """Checks a parameter.
1078

1079
    Currently we expect all parameters to be float values.
1080

1081
    """
1082
    try:
1083
      float(value)
1084
    except (TypeError, ValueError), err:
1085
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1086
                                      " '%s', error: %s" % (key, value, err))
1087

    
1088

    
1089
class Instance(TaggableObject):
1090
  """Config object representing an instance."""
1091
  __slots__ = [
1092
    "name",
1093
    "primary_node",
1094
    "secondary_nodes",
1095
    "os",
1096
    "hypervisor",
1097
    "hvparams",
1098
    "beparams",
1099
    "osparams",
1100
    "osparams_private",
1101
    "admin_state",
1102
    "nics",
1103
    "disks",
1104
    "disks_info",
1105
    "disk_template",
1106
    "disks_active",
1107
    "network_port",
1108
    "serial_no",
1109
    ] + _TIMESTAMPS + _UUID
1110

    
1111
  def FindDisk(self, idx):
1112
    """Find a disk given having a specified index.
1113

1114
    This is just a wrapper that does validation of the index.
1115

1116
    @type idx: int
1117
    @param idx: the disk index
1118
    @rtype: string
1119
    @return: the corresponding disk's uuid
1120
    @raise errors.OpPrereqError: when the given index is not valid
1121

1122
    """
1123
    try:
1124
      idx = int(idx)
1125
      return self.disks[idx]
1126
    except (TypeError, ValueError), err:
1127
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1128
                                 errors.ECODE_INVAL)
1129
    except IndexError:
1130
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1131
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1132
                                 errors.ECODE_INVAL)
1133

    
1134
  def ToDict(self, _with_private=False):
1135
    """Instance-specific conversion to standard python types.
1136

1137
    This replaces the children lists of objects with lists of standard
1138
    python types.
1139

1140
    """
1141
    bo = super(Instance, self).ToDict(_with_private=_with_private)
1142

    
1143
    if _with_private:
1144
      bo["osparams_private"] = self.osparams_private.Unprivate()
1145

    
1146
    for attr in "nics", "disks_info":
1147
      alist = bo.get(attr, None)
1148
      if alist:
1149
        nlist = outils.ContainerToDicts(alist)
1150
      else:
1151
        nlist = []
1152
      bo[attr] = nlist
1153
    return bo
1154

    
1155
  @classmethod
1156
  def FromDict(cls, val):
1157
    """Custom function for instances.
1158

1159
    """
1160
    if "admin_state" not in val:
1161
      if val.get("admin_up", False):
1162
        val["admin_state"] = constants.ADMINST_UP
1163
      else:
1164
        val["admin_state"] = constants.ADMINST_DOWN
1165
    if "admin_up" in val:
1166
      del val["admin_up"]
1167
    obj = super(Instance, cls).FromDict(val)
1168
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1169
    obj.disks_info = outils.ContainerFromDicts(obj.disks_info, list, Disk)
1170
    return obj
1171

    
1172
  def UpgradeConfig(self):
1173
    """Fill defaults for missing configuration values.
1174

1175
    """
1176
    for nic in self.nics:
1177
      nic.UpgradeConfig()
1178
    if self.hvparams:
1179
      for key in constants.HVC_GLOBALS:
1180
        try:
1181
          del self.hvparams[key]
1182
        except KeyError:
1183
          pass
1184
    if self.osparams is None:
1185
      self.osparams = {}
1186
    if self.osparams_private is None:
1187
      self.osparams_private = serializer.PrivateDict()
1188
    UpgradeBeParams(self.beparams)
1189
    if self.disks_active is None:
1190
      self.disks_active = self.admin_state == constants.ADMINST_UP
1191

    
1192

    
1193
class OS(ConfigObject):
1194
  """Config object representing an operating system.
1195

1196
  @type supported_parameters: list
1197
  @ivar supported_parameters: a list of tuples, name and description,
1198
      containing the supported parameters by this OS
1199

1200
  @type VARIANT_DELIM: string
1201
  @cvar VARIANT_DELIM: the variant delimiter
1202

1203
  """
1204
  __slots__ = [
1205
    "name",
1206
    "path",
1207
    "api_versions",
1208
    "create_script",
1209
    "export_script",
1210
    "import_script",
1211
    "rename_script",
1212
    "verify_script",
1213
    "supported_variants",
1214
    "supported_parameters",
1215
    ]
1216

    
1217
  VARIANT_DELIM = "+"
1218

    
1219
  @classmethod
1220
  def SplitNameVariant(cls, name):
1221
    """Splits the name into the proper name and variant.
1222

1223
    @param name: the OS (unprocessed) name
1224
    @rtype: list
1225
    @return: a list of two elements; if the original name didn't
1226
        contain a variant, it's returned as an empty string
1227

1228
    """
1229
    nv = name.split(cls.VARIANT_DELIM, 1)
1230
    if len(nv) == 1:
1231
      nv.append("")
1232
    return nv
1233

    
1234
  @classmethod
1235
  def GetName(cls, name):
1236
    """Returns the proper name of the os (without the variant).
1237

1238
    @param name: the OS (unprocessed) name
1239

1240
    """
1241
    return cls.SplitNameVariant(name)[0]
1242

    
1243
  @classmethod
1244
  def GetVariant(cls, name):
1245
    """Returns the variant the os (without the base name).
1246

1247
    @param name: the OS (unprocessed) name
1248

1249
    """
1250
    return cls.SplitNameVariant(name)[1]
1251

    
1252

    
1253
class ExtStorage(ConfigObject):
1254
  """Config object representing an External Storage Provider.
1255

1256
  """
1257
  __slots__ = [
1258
    "name",
1259
    "path",
1260
    "create_script",
1261
    "remove_script",
1262
    "grow_script",
1263
    "attach_script",
1264
    "detach_script",
1265
    "setinfo_script",
1266
    "verify_script",
1267
    "supported_parameters",
1268
    ]
1269

    
1270

    
1271
class NodeHvState(ConfigObject):
1272
  """Hypvervisor state on a node.
1273

1274
  @ivar mem_total: Total amount of memory
1275
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1276
    available)
1277
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1278
    rounding
1279
  @ivar mem_inst: Memory used by instances living on node
1280
  @ivar cpu_total: Total node CPU core count
1281
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1282

1283
  """
1284
  __slots__ = [
1285
    "mem_total",
1286
    "mem_node",
1287
    "mem_hv",
1288
    "mem_inst",
1289
    "cpu_total",
1290
    "cpu_node",
1291
    ] + _TIMESTAMPS
1292

    
1293

    
1294
class NodeDiskState(ConfigObject):
1295
  """Disk state on a node.
1296

1297
  """
1298
  __slots__ = [
1299
    "total",
1300
    "reserved",
1301
    "overhead",
1302
    ] + _TIMESTAMPS
1303

    
1304

    
1305
class Node(TaggableObject):
1306
  """Config object representing a node.
1307

1308
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1309
  @ivar hv_state_static: Hypervisor state overriden by user
1310
  @ivar disk_state: Disk state (e.g. free space)
1311
  @ivar disk_state_static: Disk state overriden by user
1312

1313
  """
1314
  __slots__ = [
1315
    "name",
1316
    "primary_ip",
1317
    "secondary_ip",
1318
    "serial_no",
1319
    "master_candidate",
1320
    "offline",
1321
    "drained",
1322
    "group",
1323
    "master_capable",
1324
    "vm_capable",
1325
    "ndparams",
1326
    "powered",
1327
    "hv_state",
1328
    "hv_state_static",
1329
    "disk_state",
1330
    "disk_state_static",
1331
    ] + _TIMESTAMPS + _UUID
1332

    
1333
  def UpgradeConfig(self):
1334
    """Fill defaults for missing configuration values.
1335

1336
    """
1337
    # pylint: disable=E0203
1338
    # because these are "defined" via slots, not manually
1339
    if self.master_capable is None:
1340
      self.master_capable = True
1341

    
1342
    if self.vm_capable is None:
1343
      self.vm_capable = True
1344

    
1345
    if self.ndparams is None:
1346
      self.ndparams = {}
1347
    # And remove any global parameter
1348
    for key in constants.NDC_GLOBALS:
1349
      if key in self.ndparams:
1350
        logging.warning("Ignoring %s node parameter for node %s",
1351
                        key, self.name)
1352
        del self.ndparams[key]
1353

    
1354
    if self.powered is None:
1355
      self.powered = True
1356

    
1357
  def ToDict(self, _with_private=False):
1358
    """Custom function for serializing.
1359

1360
    """
1361
    data = super(Node, self).ToDict(_with_private=_with_private)
1362

    
1363
    hv_state = data.get("hv_state", None)
1364
    if hv_state is not None:
1365
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1366

    
1367
    disk_state = data.get("disk_state", None)
1368
    if disk_state is not None:
1369
      data["disk_state"] = \
1370
        dict((key, outils.ContainerToDicts(value))
1371
             for (key, value) in disk_state.items())
1372

    
1373
    return data
1374

    
1375
  @classmethod
1376
  def FromDict(cls, val):
1377
    """Custom function for deserializing.
1378

1379
    """
1380
    obj = super(Node, cls).FromDict(val)
1381

    
1382
    if obj.hv_state is not None:
1383
      obj.hv_state = \
1384
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1385

    
1386
    if obj.disk_state is not None:
1387
      obj.disk_state = \
1388
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1389
             for (key, value) in obj.disk_state.items())
1390

    
1391
    return obj
1392

    
1393

    
1394
class NodeGroup(TaggableObject):
1395
  """Config object representing a node group."""
1396
  __slots__ = [
1397
    "name",
1398
    "members",
1399
    "ndparams",
1400
    "diskparams",
1401
    "ipolicy",
1402
    "serial_no",
1403
    "hv_state_static",
1404
    "disk_state_static",
1405
    "alloc_policy",
1406
    "networks",
1407
    ] + _TIMESTAMPS + _UUID
1408

    
1409
  def ToDict(self, _with_private=False):
1410
    """Custom function for nodegroup.
1411

1412
    This discards the members object, which gets recalculated and is only kept
1413
    in memory.
1414

1415
    """
1416
    mydict = super(NodeGroup, self).ToDict(_with_private=_with_private)
1417
    del mydict["members"]
1418
    return mydict
1419

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

1424
    The members slot is initialized to an empty list, upon deserialization.
1425

1426
    """
1427
    obj = super(NodeGroup, cls).FromDict(val)
1428
    obj.members = []
1429
    return obj
1430

    
1431
  def UpgradeConfig(self):
1432
    """Fill defaults for missing configuration values.
1433

1434
    """
1435
    if self.ndparams is None:
1436
      self.ndparams = {}
1437

    
1438
    if self.serial_no is None:
1439
      self.serial_no = 1
1440

    
1441
    if self.alloc_policy is None:
1442
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1443

    
1444
    # We only update mtime, and not ctime, since we would not be able
1445
    # to provide a correct value for creation time.
1446
    if self.mtime is None:
1447
      self.mtime = time.time()
1448

    
1449
    if self.diskparams is None:
1450
      self.diskparams = {}
1451
    if self.ipolicy is None:
1452
      self.ipolicy = MakeEmptyIPolicy()
1453

    
1454
    if self.networks is None:
1455
      self.networks = {}
1456

    
1457
  def FillND(self, node):
1458
    """Return filled out ndparams for L{objects.Node}
1459

1460
    @type node: L{objects.Node}
1461
    @param node: A Node object to fill
1462
    @return a copy of the node's ndparams with defaults filled
1463

1464
    """
1465
    return self.SimpleFillND(node.ndparams)
1466

    
1467
  def SimpleFillND(self, ndparams):
1468
    """Fill a given ndparams dict with defaults.
1469

1470
    @type ndparams: dict
1471
    @param ndparams: the dict to fill
1472
    @rtype: dict
1473
    @return: a copy of the passed in ndparams with missing keys filled
1474
        from the node group defaults
1475

1476
    """
1477
    return FillDict(self.ndparams, ndparams)
1478

    
1479

    
1480
class Cluster(TaggableObject):
1481
  """Config object representing the cluster."""
1482
  __slots__ = [
1483
    "serial_no",
1484
    "rsahostkeypub",
1485
    "dsahostkeypub",
1486
    "highest_used_port",
1487
    "tcpudp_port_pool",
1488
    "mac_prefix",
1489
    "volume_group_name",
1490
    "reserved_lvs",
1491
    "drbd_usermode_helper",
1492
    "default_bridge",
1493
    "default_hypervisor",
1494
    "master_node",
1495
    "master_ip",
1496
    "master_netdev",
1497
    "master_netmask",
1498
    "use_external_mip_script",
1499
    "cluster_name",
1500
    "file_storage_dir",
1501
    "shared_file_storage_dir",
1502
    "gluster_storage_dir",
1503
    "enabled_hypervisors",
1504
    "hvparams",
1505
    "ipolicy",
1506
    "os_hvp",
1507
    "beparams",
1508
    "osparams",
1509
    "osparams_private_cluster",
1510
    "nicparams",
1511
    "ndparams",
1512
    "diskparams",
1513
    "candidate_pool_size",
1514
    "modify_etc_hosts",
1515
    "modify_ssh_setup",
1516
    "maintain_node_health",
1517
    "uid_pool",
1518
    "default_iallocator",
1519
    "default_iallocator_params",
1520
    "hidden_os",
1521
    "blacklisted_os",
1522
    "primary_ip_family",
1523
    "prealloc_wipe_disks",
1524
    "hv_state_static",
1525
    "disk_state_static",
1526
    "enabled_disk_templates",
1527
    "candidate_certs",
1528
    "max_running_jobs",
1529
    "instance_communication_network",
1530
    ] + _TIMESTAMPS + _UUID
1531

    
1532
  def UpgradeConfig(self):
1533
    """Fill defaults for missing configuration values.
1534

1535
    """
1536
    # pylint: disable=E0203
1537
    # because these are "defined" via slots, not manually
1538
    if self.hvparams is None:
1539
      self.hvparams = constants.HVC_DEFAULTS
1540
    else:
1541
      for hypervisor in constants.HYPER_TYPES:
1542
        try:
1543
          existing_params = self.hvparams[hypervisor]
1544
        except KeyError:
1545
          existing_params = {}
1546
        self.hvparams[hypervisor] = FillDict(
1547
            constants.HVC_DEFAULTS[hypervisor], existing_params)
1548

    
1549
    if self.os_hvp is None:
1550
      self.os_hvp = {}
1551

    
1552
    if self.osparams is None:
1553
      self.osparams = {}
1554
    # osparams_private_cluster added in 2.12
1555
    if self.osparams_private_cluster is None:
1556
      self.osparams_private_cluster = {}
1557

    
1558
    self.ndparams = UpgradeNDParams(self.ndparams)
1559

    
1560
    self.beparams = UpgradeGroupedParams(self.beparams,
1561
                                         constants.BEC_DEFAULTS)
1562
    for beparams_group in self.beparams:
1563
      UpgradeBeParams(self.beparams[beparams_group])
1564

    
1565
    migrate_default_bridge = not self.nicparams
1566
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1567
                                          constants.NICC_DEFAULTS)
1568
    if migrate_default_bridge:
1569
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1570
        self.default_bridge
1571

    
1572
    if self.modify_etc_hosts is None:
1573
      self.modify_etc_hosts = True
1574

    
1575
    if self.modify_ssh_setup is None:
1576
      self.modify_ssh_setup = True
1577

    
1578
    # default_bridge is no longer used in 2.1. The slot is left there to
1579
    # support auto-upgrading. It can be removed once we decide to deprecate
1580
    # upgrading straight from 2.0.
1581
    if self.default_bridge is not None:
1582
      self.default_bridge = None
1583

    
1584
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1585
    # code can be removed once upgrading straight from 2.0 is deprecated.
1586
    if self.default_hypervisor is not None:
1587
      self.enabled_hypervisors = ([self.default_hypervisor] +
1588
                                  [hvname for hvname in self.enabled_hypervisors
1589
                                   if hvname != self.default_hypervisor])
1590
      self.default_hypervisor = None
1591

    
1592
    # maintain_node_health added after 2.1.1
1593
    if self.maintain_node_health is None:
1594
      self.maintain_node_health = False
1595

    
1596
    if self.uid_pool is None:
1597
      self.uid_pool = []
1598

    
1599
    if self.default_iallocator is None:
1600
      self.default_iallocator = ""
1601

    
1602
    if self.default_iallocator_params is None:
1603
      self.default_iallocator_params = {}
1604

    
1605
    # reserved_lvs added before 2.2
1606
    if self.reserved_lvs is None:
1607
      self.reserved_lvs = []
1608

    
1609
    # hidden and blacklisted operating systems added before 2.2.1
1610
    if self.hidden_os is None:
1611
      self.hidden_os = []
1612

    
1613
    if self.blacklisted_os is None:
1614
      self.blacklisted_os = []
1615

    
1616
    # primary_ip_family added before 2.3
1617
    if self.primary_ip_family is None:
1618
      self.primary_ip_family = AF_INET
1619

    
1620
    if self.master_netmask is None:
1621
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1622
      self.master_netmask = ipcls.iplen
1623

    
1624
    if self.prealloc_wipe_disks is None:
1625
      self.prealloc_wipe_disks = False
1626

    
1627
    # shared_file_storage_dir added before 2.5
1628
    if self.shared_file_storage_dir is None:
1629
      self.shared_file_storage_dir = ""
1630

    
1631
    # gluster_storage_dir added in 2.11
1632
    if self.gluster_storage_dir is None:
1633
      self.gluster_storage_dir = ""
1634

    
1635
    if self.use_external_mip_script is None:
1636
      self.use_external_mip_script = False
1637

    
1638
    if self.diskparams:
1639
      self.diskparams = UpgradeDiskParams(self.diskparams)
1640
    else:
1641
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1642

    
1643
    # instance policy added before 2.6
1644
    if self.ipolicy is None:
1645
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1646
    else:
1647
      # we can either make sure to upgrade the ipolicy always, or only
1648
      # do it in some corner cases (e.g. missing keys); note that this
1649
      # will break any removal of keys from the ipolicy dict
1650
      wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1651
      if wrongkeys:
1652
        # These keys would be silently removed by FillIPolicy()
1653
        msg = ("Cluster instance policy contains spurious keys: %s" %
1654
               utils.CommaJoin(wrongkeys))
1655
        raise errors.ConfigurationError(msg)
1656
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1657

    
1658
    if self.candidate_certs is None:
1659
      self.candidate_certs = {}
1660

    
1661
    if self.max_running_jobs is None:
1662
      self.max_running_jobs = constants.LUXID_MAXIMAL_RUNNING_JOBS_DEFAULT
1663

    
1664
    if self.instance_communication_network is None:
1665
      self.instance_communication_network = ""
1666

    
1667
  @property
1668
  def primary_hypervisor(self):
1669
    """The first hypervisor is the primary.
1670

1671
    Useful, for example, for L{Node}'s hv/disk state.
1672

1673
    """
1674
    return self.enabled_hypervisors[0]
1675

    
1676
  def ToDict(self, _with_private=False):
1677
    """Custom function for cluster.
1678

1679
    """
1680
    mydict = super(Cluster, self).ToDict(_with_private=_with_private)
1681

    
1682
    # Explicitly save private parameters.
1683
    if _with_private:
1684
      for os in mydict["osparams_private_cluster"]:
1685
        mydict["osparams_private_cluster"][os] = \
1686
          self.osparams_private_cluster[os].Unprivate()
1687

    
1688
    if self.tcpudp_port_pool is None:
1689
      tcpudp_port_pool = []
1690
    else:
1691
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1692

    
1693
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1694

    
1695
    return mydict
1696

    
1697
  @classmethod
1698
  def FromDict(cls, val):
1699
    """Custom function for cluster.
1700

1701
    """
1702
    obj = super(Cluster, cls).FromDict(val)
1703

    
1704
    if obj.tcpudp_port_pool is None:
1705
      obj.tcpudp_port_pool = set()
1706
    elif not isinstance(obj.tcpudp_port_pool, set):
1707
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1708

    
1709
    return obj
1710

    
1711
  def SimpleFillDP(self, diskparams):
1712
    """Fill a given diskparams dict with cluster defaults.
1713

1714
    @param diskparams: The diskparams
1715
    @return: The defaults dict
1716

1717
    """
1718
    return FillDiskParams(self.diskparams, diskparams)
1719

    
1720
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1721
    """Get the default hypervisor parameters for the cluster.
1722

1723
    @param hypervisor: the hypervisor name
1724
    @param os_name: if specified, we'll also update the defaults for this OS
1725
    @param skip_keys: if passed, list of keys not to use
1726
    @return: the defaults dict
1727

1728
    """
1729
    if skip_keys is None:
1730
      skip_keys = []
1731

    
1732
    fill_stack = [self.hvparams.get(hypervisor, {})]
1733
    if os_name is not None:
1734
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1735
      fill_stack.append(os_hvp)
1736

    
1737
    ret_dict = {}
1738
    for o_dict in fill_stack:
1739
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1740

    
1741
    return ret_dict
1742

    
1743
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1744
    """Fill a given hvparams dict with cluster defaults.
1745

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

1757
    """
1758
    if skip_globals:
1759
      skip_keys = constants.HVC_GLOBALS
1760
    else:
1761
      skip_keys = []
1762

    
1763
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1764
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1765

    
1766
  def FillHV(self, instance, skip_globals=False):
1767
    """Fill an instance's hvparams dict with cluster defaults.
1768

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

1778
    """
1779
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1780
                             instance.hvparams, skip_globals)
1781

    
1782
  def SimpleFillBE(self, beparams):
1783
    """Fill a given beparams dict with cluster defaults.
1784

1785
    @type beparams: dict
1786
    @param beparams: the dict to fill
1787
    @rtype: dict
1788
    @return: a copy of the passed in beparams with missing keys filled
1789
        from the cluster defaults
1790

1791
    """
1792
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1793

    
1794
  def FillBE(self, instance):
1795
    """Fill an instance's beparams dict with cluster defaults.
1796

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

1803
    """
1804
    return self.SimpleFillBE(instance.beparams)
1805

    
1806
  def SimpleFillNIC(self, nicparams):
1807
    """Fill a given nicparams dict with cluster defaults.
1808

1809
    @type nicparams: dict
1810
    @param nicparams: the dict to fill
1811
    @rtype: dict
1812
    @return: a copy of the passed in nicparams with missing keys filled
1813
        from the cluster defaults
1814

1815
    """
1816
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1817

    
1818
  def SimpleFillOS(self, os_name,
1819
                    os_params_public,
1820
                    os_params_private=None,
1821
                    os_params_secret=None):
1822
    """Fill an instance's osparams dict with cluster defaults.
1823

1824
    @type os_name: string
1825
    @param os_name: the OS name to use
1826
    @type os_params_public: dict
1827
    @param os_params_public: the dict to fill with default values
1828
    @type os_params_private: dict
1829
    @param os_params_private: the dict with private fields to fill
1830
                              with default values. Not passing this field
1831
                              results in no private fields being added to the
1832
                              return value. Private fields will be wrapped in
1833
                              L{Private} objects.
1834
    @type os_params_secret: dict
1835
    @param os_params_secret: the dict with secret fields to fill
1836
                             with default values. Not passing this field
1837
                             results in no secret fields being added to the
1838
                             return value. Private fields will be wrapped in
1839
                             L{Private} objects.
1840
    @rtype: dict
1841
    @return: a copy of the instance's osparams with missing keys filled from
1842
        the cluster defaults. Private and secret parameters are not included
1843
        unless the respective optional parameters are supplied.
1844

1845
    """
1846
    name_only = os_name.split("+", 1)[0]
1847

    
1848
    defaults_base_public = self.osparams.get(name_only, {})
1849
    defaults_public = FillDict(defaults_base_public,
1850
                               self.osparams.get(os_name, {}))
1851
    params_public = FillDict(defaults_public, os_params_public)
1852

    
1853
    if os_params_private is not None:
1854
      defaults_base_private = self.osparams_private_cluster.get(name_only, {})
1855
      defaults_private = FillDict(defaults_base_private,
1856
                                  self.osparams_private_cluster.get(os_name,
1857
                                                                    {}))
1858
      params_private = FillDict(defaults_private, os_params_private)
1859
    else:
1860
      params_private = {}
1861

    
1862
    if os_params_secret is not None:
1863
      # There can't be default secret settings, so there's nothing to be done.
1864
      params_secret = os_params_secret
1865
    else:
1866
      params_secret = {}
1867

    
1868
    # Enforce that the set of keys be distinct:
1869
    duplicate_keys = utils.GetRepeatedKeys(params_public,
1870
                                           params_private,
1871
                                           params_secret)
1872
    if not duplicate_keys:
1873

    
1874
      # Actually update them:
1875
      params_public.update(params_private)
1876
      params_public.update(params_secret)
1877

    
1878
      return params_public
1879

    
1880
    else:
1881

    
1882
      def formatter(keys):
1883
        return utils.CommaJoin(sorted(map(repr, keys))) if keys else "(none)"
1884

    
1885
      #Lose the values.
1886
      params_public = set(params_public)
1887
      params_private = set(params_private)
1888
      params_secret = set(params_secret)
1889

    
1890
      msg = """Cannot assign multiple values to OS parameters.
1891

1892
      Conflicting OS parameters that would have been set by this operation:
1893
      - at public visibility:  {public}
1894
      - at private visibility: {private}
1895
      - at secret visibility:  {secret}
1896
      """.format(dupes=formatter(duplicate_keys),
1897
                 public=formatter(params_public & duplicate_keys),
1898
                 private=formatter(params_private & duplicate_keys),
1899
                 secret=formatter(params_secret & duplicate_keys))
1900
      raise errors.OpPrereqError(msg)
1901

    
1902
  @staticmethod
1903
  def SimpleFillHvState(hv_state):
1904
    """Fill an hv_state sub dict with cluster defaults.
1905

1906
    """
1907
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1908

    
1909
  @staticmethod
1910
  def SimpleFillDiskState(disk_state):
1911
    """Fill an disk_state sub dict with cluster defaults.
1912

1913
    """
1914
    return FillDict(constants.DS_DEFAULTS, disk_state)
1915

    
1916
  def FillND(self, node, nodegroup):
1917
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1918

1919
    @type node: L{objects.Node}
1920
    @param node: A Node object to fill
1921
    @type nodegroup: L{objects.NodeGroup}
1922
    @param nodegroup: A Node object to fill
1923
    @return a copy of the node's ndparams with defaults filled
1924

1925
    """
1926
    return self.SimpleFillND(nodegroup.FillND(node))
1927

    
1928
  def FillNDGroup(self, nodegroup):
1929
    """Return filled out ndparams for just L{objects.NodeGroup}
1930

1931
    @type nodegroup: L{objects.NodeGroup}
1932
    @param nodegroup: A Node object to fill
1933
    @return a copy of the node group's ndparams with defaults filled
1934

1935
    """
1936
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
1937

    
1938
  def SimpleFillND(self, ndparams):
1939
    """Fill a given ndparams dict with defaults.
1940

1941
    @type ndparams: dict
1942
    @param ndparams: the dict to fill
1943
    @rtype: dict
1944
    @return: a copy of the passed in ndparams with missing keys filled
1945
        from the cluster defaults
1946

1947
    """
1948
    return FillDict(self.ndparams, ndparams)
1949

    
1950
  def SimpleFillIPolicy(self, ipolicy):
1951
    """ Fill instance policy dict with defaults.
1952

1953
    @type ipolicy: dict
1954
    @param ipolicy: the dict to fill
1955
    @rtype: dict
1956
    @return: a copy of passed ipolicy with missing keys filled from
1957
      the cluster defaults
1958

1959
    """
1960
    return FillIPolicy(self.ipolicy, ipolicy)
1961

    
1962
  def IsDiskTemplateEnabled(self, disk_template):
1963
    """Checks if a particular disk template is enabled.
1964

1965
    """
1966
    return utils.storage.IsDiskTemplateEnabled(
1967
        disk_template, self.enabled_disk_templates)
1968

    
1969
  def IsFileStorageEnabled(self):
1970
    """Checks if file storage is enabled.
1971

1972
    """
1973
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1974

    
1975
  def IsSharedFileStorageEnabled(self):
1976
    """Checks if shared file storage is enabled.
1977

1978
    """
1979
    return utils.storage.IsSharedFileStorageEnabled(
1980
        self.enabled_disk_templates)
1981

    
1982

    
1983
class BlockDevStatus(ConfigObject):
1984
  """Config object representing the status of a block device."""
1985
  __slots__ = [
1986
    "dev_path",
1987
    "major",
1988
    "minor",
1989
    "sync_percent",
1990
    "estimated_time",
1991
    "is_degraded",
1992
    "ldisk_status",
1993
    ]
1994

    
1995

    
1996
class ImportExportStatus(ConfigObject):
1997
  """Config object representing the status of an import or export."""
1998
  __slots__ = [
1999
    "recent_output",
2000
    "listen_port",
2001
    "connected",
2002
    "progress_mbytes",
2003
    "progress_throughput",
2004
    "progress_eta",
2005
    "progress_percent",
2006
    "exit_status",
2007
    "error_message",
2008
    ] + _TIMESTAMPS
2009

    
2010

    
2011
class ImportExportOptions(ConfigObject):
2012
  """Options for import/export daemon
2013

2014
  @ivar key_name: X509 key name (None for cluster certificate)
2015
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
2016
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
2017
  @ivar magic: Used to ensure the connection goes to the right disk
2018
  @ivar ipv6: Whether to use IPv6
2019
  @ivar connect_timeout: Number of seconds for establishing connection
2020

2021
  """
2022
  __slots__ = [
2023
    "key_name",
2024
    "ca_pem",
2025
    "compress",
2026
    "magic",
2027
    "ipv6",
2028
    "connect_timeout",
2029
    ]
2030

    
2031

    
2032
class ConfdRequest(ConfigObject):
2033
  """Object holding a confd request.
2034

2035
  @ivar protocol: confd protocol version
2036
  @ivar type: confd query type
2037
  @ivar query: query request
2038
  @ivar rsalt: requested reply salt
2039

2040
  """
2041
  __slots__ = [
2042
    "protocol",
2043
    "type",
2044
    "query",
2045
    "rsalt",
2046
    ]
2047

    
2048

    
2049
class ConfdReply(ConfigObject):
2050
  """Object holding a confd reply.
2051

2052
  @ivar protocol: confd protocol version
2053
  @ivar status: reply status code (ok, error)
2054
  @ivar answer: confd query reply
2055
  @ivar serial: configuration serial number
2056

2057
  """
2058
  __slots__ = [
2059
    "protocol",
2060
    "status",
2061
    "answer",
2062
    "serial",
2063
    ]
2064

    
2065

    
2066
class QueryFieldDefinition(ConfigObject):
2067
  """Object holding a query field definition.
2068

2069
  @ivar name: Field name
2070
  @ivar title: Human-readable title
2071
  @ivar kind: Field type
2072
  @ivar doc: Human-readable description
2073

2074
  """
2075
  __slots__ = [
2076
    "name",
2077
    "title",
2078
    "kind",
2079
    "doc",
2080
    ]
2081

    
2082

    
2083
class _QueryResponseBase(ConfigObject):
2084
  __slots__ = [
2085
    "fields",
2086
    ]
2087

    
2088
  def ToDict(self, _with_private=False):
2089
    """Custom function for serializing.
2090

2091
    """
2092
    mydict = super(_QueryResponseBase, self).ToDict()
2093
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2094
    return mydict
2095

    
2096
  @classmethod
2097
  def FromDict(cls, val):
2098
    """Custom function for de-serializing.
2099

2100
    """
2101
    obj = super(_QueryResponseBase, cls).FromDict(val)
2102
    obj.fields = \
2103
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2104
    return obj
2105

    
2106

    
2107
class QueryResponse(_QueryResponseBase):
2108
  """Object holding the response to a query.
2109

2110
  @ivar fields: List of L{QueryFieldDefinition} objects
2111
  @ivar data: Requested data
2112

2113
  """
2114
  __slots__ = [
2115
    "data",
2116
    ]
2117

    
2118

    
2119
class QueryFieldsRequest(ConfigObject):
2120
  """Object holding a request for querying available fields.
2121

2122
  """
2123
  __slots__ = [
2124
    "what",
2125
    "fields",
2126
    ]
2127

    
2128

    
2129
class QueryFieldsResponse(_QueryResponseBase):
2130
  """Object holding the response to a query for fields.
2131

2132
  @ivar fields: List of L{QueryFieldDefinition} objects
2133

2134
  """
2135
  __slots__ = []
2136

    
2137

    
2138
class MigrationStatus(ConfigObject):
2139
  """Object holding the status of a migration.
2140

2141
  """
2142
  __slots__ = [
2143
    "status",
2144
    "transferred_ram",
2145
    "total_ram",
2146
    ]
2147

    
2148

    
2149
class InstanceConsole(ConfigObject):
2150
  """Object describing how to access the console of an instance.
2151

2152
  """
2153
  __slots__ = [
2154
    "instance",
2155
    "kind",
2156
    "message",
2157
    "host",
2158
    "port",
2159
    "user",
2160
    "command",
2161
    "display",
2162
    ]
2163

    
2164
  def Validate(self):
2165
    """Validates contents of this object.
2166

2167
    """
2168
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2169
    assert self.instance, "Missing instance name"
2170
    assert self.message or self.kind in [constants.CONS_SSH,
2171
                                         constants.CONS_SPICE,
2172
                                         constants.CONS_VNC]
2173
    assert self.host or self.kind == constants.CONS_MESSAGE
2174
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2175
                                      constants.CONS_SSH]
2176
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2177
                                      constants.CONS_SPICE,
2178
                                      constants.CONS_VNC]
2179
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2180
                                         constants.CONS_SPICE,
2181
                                         constants.CONS_VNC]
2182
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2183
                                         constants.CONS_SPICE,
2184
                                         constants.CONS_SSH]
2185
    return True
2186

    
2187

    
2188
class Network(TaggableObject):
2189
  """Object representing a network definition for ganeti.
2190

2191
  """
2192
  __slots__ = [
2193
    "name",
2194
    "serial_no",
2195
    "mac_prefix",
2196
    "network",
2197
    "network6",
2198
    "gateway",
2199
    "gateway6",
2200
    "reservations",
2201
    "ext_reservations",
2202
    ] + _TIMESTAMPS + _UUID
2203

    
2204
  def HooksDict(self, prefix=""):
2205
    """Export a dictionary used by hooks with a network's information.
2206

2207
    @type prefix: String
2208
    @param prefix: Prefix to prepend to the dict entries
2209

2210
    """
2211
    result = {
2212
      "%sNETWORK_NAME" % prefix: self.name,
2213
      "%sNETWORK_UUID" % prefix: self.uuid,
2214
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2215
    }
2216
    if self.network:
2217
      result["%sNETWORK_SUBNET" % prefix] = self.network
2218
    if self.gateway:
2219
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2220
    if self.network6:
2221
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2222
    if self.gateway6:
2223
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2224
    if self.mac_prefix:
2225
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2226

    
2227
    return result
2228

    
2229
  @classmethod
2230
  def FromDict(cls, val):
2231
    """Custom function for networks.
2232

2233
    Remove deprecated network_type and family.
2234

2235
    """
2236
    if "network_type" in val:
2237
      del val["network_type"]
2238
    if "family" in val:
2239
      del val["family"]
2240
    obj = super(Network, cls).FromDict(val)
2241
    return obj
2242

    
2243

    
2244
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2245
  """Simple wrapper over ConfigParse that allows serialization.
2246

2247
  This class is basically ConfigParser.SafeConfigParser with two
2248
  additional methods that allow it to serialize/unserialize to/from a
2249
  buffer.
2250

2251
  """
2252
  def Dumps(self):
2253
    """Dump this instance and return the string representation."""
2254
    buf = StringIO()
2255
    self.write(buf)
2256
    return buf.getvalue()
2257

    
2258
  @classmethod
2259
  def Loads(cls, data):
2260
    """Load data from a string."""
2261
    buf = StringIO(data)
2262
    cfp = cls()
2263
    cfp.readfp(buf)
2264
    return cfp
2265

    
2266

    
2267
class LvmPvInfo(ConfigObject):
2268
  """Information about an LVM physical volume (PV).
2269

2270
  @type name: string
2271
  @ivar name: name of the PV
2272
  @type vg_name: string
2273
  @ivar vg_name: name of the volume group containing the PV
2274
  @type size: float
2275
  @ivar size: size of the PV in MiB
2276
  @type free: float
2277
  @ivar free: free space in the PV, in MiB
2278
  @type attributes: string
2279
  @ivar attributes: PV attributes
2280
  @type lv_list: list of strings
2281
  @ivar lv_list: names of the LVs hosted on the PV
2282
  """
2283
  __slots__ = [
2284
    "name",
2285
    "vg_name",
2286
    "size",
2287
    "free",
2288
    "attributes",
2289
    "lv_list"
2290
    ]
2291

    
2292
  def IsEmpty(self):
2293
    """Is this PV empty?
2294

2295
    """
2296
    return self.size <= (self.free + 1)
2297

    
2298
  def IsAllocatable(self):
2299
    """Is this PV allocatable?
2300

2301
    """
2302
    return ("a" in self.attributes)