Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 8d4c25f2

History | View | Annotate | Download (70.4 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 instance in self.instances.values():
442
      for disk in instance.disks:
443
        if disk.IsBasedOnDiskType(dev_type):
444
          return True
445
    return False
446

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

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

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

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

    
497

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

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

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

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

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

    
521

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

    
530
  def CreateOnSecondary(self):
531
    """Test if this device needs to be created on a secondary node."""
532
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
533

    
534
  def AssembleOnSecondary(self):
535
    """Test if this device needs to be assembled on a secondary node."""
536
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
537

    
538
  def OpenOnSecondary(self):
539
    """Test if this device needs to be opened on a secondary node."""
540
    return self.dev_type in (constants.DT_PLAIN,)
541

    
542
  def StaticDevPath(self):
543
    """Return the device path if this device type has a static one.
544

545
    Some devices (LVM for example) live always at the same /dev/ path,
546
    irrespective of their status. For such devices, we return this
547
    path, for others we return None.
548

549
    @warning: The path returned is not a normalized pathname; callers
550
        should check that it is a valid path.
551

552
    """
553
    if self.dev_type == constants.DT_PLAIN:
554
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
555
    elif self.dev_type == constants.DT_BLOCK:
556
      return self.logical_id[1]
557
    elif self.dev_type == constants.DT_RBD:
558
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
559
    return None
560

    
561
  def ChildrenNeeded(self):
562
    """Compute the needed number of children for activation.
563

564
    This method will return either -1 (all children) or a positive
565
    number denoting the minimum number of children needed for
566
    activation (only mirrored devices will usually return >=0).
567

568
    Currently, only DRBD8 supports diskless activation (therefore we
569
    return 0), for all other we keep the previous semantics and return
570
    -1.
571

572
    """
573
    if self.dev_type == constants.DT_DRBD8:
574
      return 0
575
    return -1
576

    
577
  def IsBasedOnDiskType(self, dev_type):
578
    """Check if the disk or its children are based on the given type.
579

580
    @type dev_type: L{constants.DTS_BLOCK}
581
    @param dev_type: the type to look for
582
    @rtype: boolean
583
    @return: boolean indicating if a device of the given type was found or not
584

585
    """
586
    if self.children:
587
      for child in self.children:
588
        if child.IsBasedOnDiskType(dev_type):
589
          return True
590
    return self.dev_type == dev_type
591

    
592
  def GetNodes(self, node_uuid):
593
    """This function returns the nodes this device lives on.
594

595
    Given the node on which the parent of the device lives on (or, in
596
    case of a top-level device, the primary node of the devices'
597
    instance), this function will return a list of nodes on which this
598
    devices needs to (or can) be assembled.
599

600
    """
601
    if self.dev_type in [constants.DT_PLAIN, constants.DT_FILE,
602
                         constants.DT_BLOCK, constants.DT_RBD,
603
                         constants.DT_EXT, constants.DT_SHARED_FILE,
604
                         constants.DT_GLUSTER]:
605
      result = [node_uuid]
606
    elif self.dev_type in constants.DTS_DRBD:
607
      result = [self.logical_id[0], self.logical_id[1]]
608
      if node_uuid not in result:
609
        raise errors.ConfigurationError("DRBD device passed unknown node")
610
    else:
611
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
612
    return result
613

    
614
  def ComputeNodeTree(self, parent_node_uuid):
615
    """Compute the node/disk tree for this disk and its children.
616

617
    This method, given the node on which the parent disk lives, will
618
    return the list of all (node UUID, disk) pairs which describe the disk
619
    tree in the most compact way. For example, a drbd/lvm stack
620
    will be returned as (primary_node, drbd) and (secondary_node, drbd)
621
    which represents all the top-level devices on the nodes.
622

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

    
649
  def ComputeGrowth(self, amount):
650
    """Compute the per-VG growth requirements.
651

652
    This only works for VG-based disks.
653

654
    @type amount: integer
655
    @param amount: the desired increase in (user-visible) disk space
656
    @rtype: dict
657
    @return: a dictionary of volume-groups and the required size
658

659
    """
660
    if self.dev_type == constants.DT_PLAIN:
661
      return {self.logical_id[0]: amount}
662
    elif self.dev_type == constants.DT_DRBD8:
663
      if self.children:
664
        return self.children[0].ComputeGrowth(amount)
665
      else:
666
        return {}
667
    else:
668
      # Other disk types do not require VG space
669
      return {}
670

    
671
  def RecordGrow(self, amount):
672
    """Update the size of this disk after growth.
673

674
    This method recurses over the disks's children and updates their
675
    size correspondigly. The method needs to be kept in sync with the
676
    actual algorithms from bdev.
677

678
    """
679
    if self.dev_type in (constants.DT_PLAIN, constants.DT_FILE,
680
                         constants.DT_RBD, constants.DT_EXT,
681
                         constants.DT_SHARED_FILE, constants.DT_GLUSTER):
682
      self.size += amount
683
    elif self.dev_type == constants.DT_DRBD8:
684
      if self.children:
685
        self.children[0].RecordGrow(amount)
686
      self.size += amount
687
    else:
688
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
689
                                   " disk type %s" % self.dev_type)
690

    
691
  def Update(self, size=None, mode=None, spindles=None):
692
    """Apply changes to size, spindles and mode.
693

694
    """
695
    if self.dev_type == constants.DT_DRBD8:
696
      if self.children:
697
        self.children[0].Update(size=size, mode=mode)
698
    else:
699
      assert not self.children
700

    
701
    if size is not None:
702
      self.size = size
703
    if mode is not None:
704
      self.mode = mode
705
    if spindles is not None:
706
      self.spindles = spindles
707

    
708
  def UnsetSize(self):
709
    """Sets recursively the size to zero for the disk and its children.
710

711
    """
712
    if self.children:
713
      for child in self.children:
714
        child.UnsetSize()
715
    self.size = 0
716

    
717
  def UpdateDynamicDiskParams(self, target_node_uuid, nodes_ip):
718
    """Updates the dynamic disk params for the given node.
719

720
    This is mainly used for drbd, which needs ip/port configuration.
721

722
    Arguments:
723
      - target_node_uuid: the node UUID we wish to configure for
724
      - nodes_ip: a mapping of node name to ip
725

726
    The target_node must exist in nodes_ip, and should be one of the
727
    nodes in the logical ID if this device is a DRBD device.
728

729
    """
730
    if self.children:
731
      for child in self.children:
732
        child.UpdateDynamicDiskParams(target_node_uuid, nodes_ip)
733

    
734
    dyn_disk_params = {}
735
    if self.logical_id is not None and self.dev_type in constants.DTS_DRBD:
736
      pnode_uuid, snode_uuid, _, pminor, sminor, _ = self.logical_id
737
      if target_node_uuid not in (pnode_uuid, snode_uuid):
738
        # disk object is being sent to neither the primary nor the secondary
739
        # node. reset the dynamic parameters, the target node is not
740
        # supposed to use them.
741
        self.dynamic_params = dyn_disk_params
742
        return
743

    
744
      pnode_ip = nodes_ip.get(pnode_uuid, None)
745
      snode_ip = nodes_ip.get(snode_uuid, None)
746
      if pnode_ip is None or snode_ip is None:
747
        raise errors.ConfigurationError("Can't find primary or secondary node"
748
                                        " for %s" % str(self))
749
      if pnode_uuid == target_node_uuid:
750
        dyn_disk_params[constants.DDP_LOCAL_IP] = pnode_ip
751
        dyn_disk_params[constants.DDP_REMOTE_IP] = snode_ip
752
        dyn_disk_params[constants.DDP_LOCAL_MINOR] = pminor
753
        dyn_disk_params[constants.DDP_REMOTE_MINOR] = sminor
754
      else: # it must be secondary, we tested above
755
        dyn_disk_params[constants.DDP_LOCAL_IP] = snode_ip
756
        dyn_disk_params[constants.DDP_REMOTE_IP] = pnode_ip
757
        dyn_disk_params[constants.DDP_LOCAL_MINOR] = sminor
758
        dyn_disk_params[constants.DDP_REMOTE_MINOR] = pminor
759

    
760
    self.dynamic_params = dyn_disk_params
761

    
762
  # pylint: disable=W0221
763
  def ToDict(self, include_dynamic_params=False,
764
             _with_private=False):
765
    """Disk-specific conversion to standard python types.
766

767
    This replaces the children lists of objects with lists of
768
    standard python types.
769

770
    """
771
    bo = super(Disk, self).ToDict()
772
    if not include_dynamic_params and "dynamic_params" in bo:
773
      del bo["dynamic_params"]
774

    
775
    for attr in ("children",):
776
      alist = bo.get(attr, None)
777
      if alist:
778
        bo[attr] = outils.ContainerToDicts(alist)
779
    return bo
780

    
781
  @classmethod
782
  def FromDict(cls, val):
783
    """Custom function for Disks
784

785
    """
786
    obj = super(Disk, cls).FromDict(val)
787
    if obj.children:
788
      obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
789
    if obj.logical_id and isinstance(obj.logical_id, list):
790
      obj.logical_id = tuple(obj.logical_id)
791
    if obj.dev_type in constants.DTS_DRBD:
792
      # we need a tuple of length six here
793
      if len(obj.logical_id) < 6:
794
        obj.logical_id += (None,) * (6 - len(obj.logical_id))
795
    return obj
796

    
797
  def __str__(self):
798
    """Custom str() formatter for disks.
799

800
    """
801
    if self.dev_type == constants.DT_PLAIN:
802
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
803
    elif self.dev_type in constants.DTS_DRBD:
804
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
805
      val = "<DRBD8("
806

    
807
      val += ("hosts=%s/%d-%s/%d, port=%s, " %
808
              (node_a, minor_a, node_b, minor_b, port))
809
      if self.children and self.children.count(None) == 0:
810
        val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
811
      else:
812
        val += "no local storage"
813
    else:
814
      val = ("<Disk(type=%s, logical_id=%s, children=%s" %
815
             (self.dev_type, self.logical_id, self.children))
816
    if self.iv_name is None:
817
      val += ", not visible"
818
    else:
819
      val += ", visible as /dev/%s" % self.iv_name
820
    if self.spindles is not None:
821
      val += ", spindles=%s" % self.spindles
822
    if isinstance(self.size, int):
823
      val += ", size=%dm)>" % self.size
824
    else:
825
      val += ", size='%s')>" % (self.size,)
826
    return val
827

    
828
  def Verify(self):
829
    """Checks that this disk is correctly configured.
830

831
    """
832
    all_errors = []
833
    if self.mode not in constants.DISK_ACCESS_SET:
834
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
835
    return all_errors
836

    
837
  def UpgradeConfig(self):
838
    """Fill defaults for missing configuration values.
839

840
    """
841
    if self.children:
842
      for child in self.children:
843
        child.UpgradeConfig()
844

    
845
    # FIXME: Make this configurable in Ganeti 2.7
846
    # Params should be an empty dict that gets filled any time needed
847
    # In case of ext template we allow arbitrary params that should not
848
    # be overrided during a config reload/upgrade.
849
    if not self.params or not isinstance(self.params, dict):
850
      self.params = {}
851

    
852
    # add here config upgrade for this disk
853

    
854
    # map of legacy device types (mapping differing LD constants to new
855
    # DT constants)
856
    LEG_DEV_TYPE_MAP = {"lvm": constants.DT_PLAIN, "drbd8": constants.DT_DRBD8}
857
    if self.dev_type in LEG_DEV_TYPE_MAP:
858
      self.dev_type = LEG_DEV_TYPE_MAP[self.dev_type]
859

    
860
  @staticmethod
861
  def ComputeLDParams(disk_template, disk_params):
862
    """Computes Logical Disk parameters from Disk Template parameters.
863

864
    @type disk_template: string
865
    @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
866
    @type disk_params: dict
867
    @param disk_params: disk template parameters;
868
                        dict(template_name -> parameters
869
    @rtype: list(dict)
870
    @return: a list of dicts, one for each node of the disk hierarchy. Each dict
871
      contains the LD parameters of the node. The tree is flattened in-order.
872

873
    """
874
    if disk_template not in constants.DISK_TEMPLATES:
875
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
876

    
877
    assert disk_template in disk_params
878

    
879
    result = list()
880
    dt_params = disk_params[disk_template]
881

    
882
    if disk_template == constants.DT_DRBD8:
883
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_DRBD8], {
884
        constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
885
        constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
886
        constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
887
        constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
888
        constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
889
        constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
890
        constants.LDP_PROTOCOL: dt_params[constants.DRBD_PROTOCOL],
891
        constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
892
        constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
893
        constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
894
        constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
895
        constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
896
        constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
897
        }))
898

    
899
      # data LV
900
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
901
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
902
        }))
903

    
904
      # metadata LV
905
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
906
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
907
        }))
908

    
909
    else:
910
      defaults = constants.DISK_LD_DEFAULTS[disk_template]
911
      values = {}
912
      for field in defaults:
913
        values[field] = dt_params[field]
914
      result.append(FillDict(defaults, values))
915

    
916
    return result
917

    
918

    
919
class InstancePolicy(ConfigObject):
920
  """Config object representing instance policy limits dictionary.
921

922
  Note that this object is not actually used in the config, it's just
923
  used as a placeholder for a few functions.
924

925
  """
926
  @classmethod
927
  def UpgradeDiskTemplates(cls, ipolicy, enabled_disk_templates):
928
    """Upgrades the ipolicy configuration."""
929
    if constants.IPOLICY_DTS in ipolicy:
930
      if not set(ipolicy[constants.IPOLICY_DTS]).issubset(
931
        set(enabled_disk_templates)):
932
        ipolicy[constants.IPOLICY_DTS] = list(
933
          set(ipolicy[constants.IPOLICY_DTS]) & set(enabled_disk_templates))
934

    
935
  @classmethod
936
  def CheckParameterSyntax(cls, ipolicy, check_std):
937
    """ Check the instance policy for validity.
938

939
    @type ipolicy: dict
940
    @param ipolicy: dictionary with min/max/std specs and policies
941
    @type check_std: bool
942
    @param check_std: Whether to check std value or just assume compliance
943
    @raise errors.ConfigurationError: when the policy is not legal
944

945
    """
946
    InstancePolicy.CheckISpecSyntax(ipolicy, check_std)
947
    if constants.IPOLICY_DTS in ipolicy:
948
      InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
949
    for key in constants.IPOLICY_PARAMETERS:
950
      if key in ipolicy:
951
        InstancePolicy.CheckParameter(key, ipolicy[key])
952
    wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
953
    if wrong_keys:
954
      raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
955
                                      utils.CommaJoin(wrong_keys))
956

    
957
  @classmethod
958
  def _CheckIncompleteSpec(cls, spec, keyname):
959
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
960
    if missing_params:
961
      msg = ("Missing instance specs parameters for %s: %s" %
962
             (keyname, utils.CommaJoin(missing_params)))
963
      raise errors.ConfigurationError(msg)
964

    
965
  @classmethod
966
  def CheckISpecSyntax(cls, ipolicy, check_std):
967
    """Check the instance policy specs for validity.
968

969
    @type ipolicy: dict
970
    @param ipolicy: dictionary with min/max/std specs
971
    @type check_std: bool
972
    @param check_std: Whether to check std value or just assume compliance
973
    @raise errors.ConfigurationError: when specs are not valid
974

975
    """
976
    if constants.ISPECS_MINMAX not in ipolicy:
977
      # Nothing to check
978
      return
979

    
980
    if check_std and constants.ISPECS_STD not in ipolicy:
981
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
982
      raise errors.ConfigurationError(msg)
983
    stdspec = ipolicy.get(constants.ISPECS_STD)
984
    if check_std:
985
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
986

    
987
    if not ipolicy[constants.ISPECS_MINMAX]:
988
      raise errors.ConfigurationError("Empty minmax specifications")
989
    std_is_good = False
990
    for minmaxspecs in ipolicy[constants.ISPECS_MINMAX]:
991
      missing = constants.ISPECS_MINMAX_KEYS - frozenset(minmaxspecs.keys())
992
      if missing:
993
        msg = "Missing instance specification: %s" % utils.CommaJoin(missing)
994
        raise errors.ConfigurationError(msg)
995
      for (key, spec) in minmaxspecs.items():
996
        InstancePolicy._CheckIncompleteSpec(spec, key)
997

    
998
      spec_std_ok = True
999
      for param in constants.ISPECS_PARAMETERS:
1000
        par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
1001
                                                           param, check_std)
1002
        spec_std_ok = spec_std_ok and par_std_ok
1003
      std_is_good = std_is_good or spec_std_ok
1004
    if not std_is_good:
1005
      raise errors.ConfigurationError("Invalid std specifications")
1006

    
1007
  @classmethod
1008
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
1009
    """Check the instance policy specs for validity on a given key.
1010

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

1014
    @type minmaxspecs: dict
1015
    @param minmaxspecs: dictionary with min and max instance spec
1016
    @type stdspec: dict
1017
    @param stdspec: dictionary with standard instance spec
1018
    @type name: string
1019
    @param name: what are the limits for
1020
    @type check_std: bool
1021
    @param check_std: Whether to check std value or just assume compliance
1022
    @rtype: bool
1023
    @return: C{True} when specs are valid, C{False} when standard spec for the
1024
        given name is not valid
1025
    @raise errors.ConfigurationError: when min/max specs for the given name
1026
        are not valid
1027

1028
    """
1029
    minspec = minmaxspecs[constants.ISPECS_MIN]
1030
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1031
    min_v = minspec[name]
1032
    max_v = maxspec[name]
1033

    
1034
    if min_v > max_v:
1035
      err = ("Invalid specification of min/max values for %s: %s/%s" %
1036
             (name, min_v, max_v))
1037
      raise errors.ConfigurationError(err)
1038
    elif check_std:
1039
      std_v = stdspec.get(name, min_v)
1040
      return std_v >= min_v and std_v <= max_v
1041
    else:
1042
      return True
1043

    
1044
  @classmethod
1045
  def CheckDiskTemplates(cls, disk_templates):
1046
    """Checks the disk templates for validity.
1047

1048
    """
1049
    if not disk_templates:
1050
      raise errors.ConfigurationError("Instance policy must contain" +
1051
                                      " at least one disk template")
1052
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1053
    if wrong:
1054
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1055
                                      utils.CommaJoin(wrong))
1056

    
1057
  @classmethod
1058
  def CheckParameter(cls, key, value):
1059
    """Checks a parameter.
1060

1061
    Currently we expect all parameters to be float values.
1062

1063
    """
1064
    try:
1065
      float(value)
1066
    except (TypeError, ValueError), err:
1067
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1068
                                      " '%s', error: %s" % (key, value, err))
1069

    
1070

    
1071
class Instance(TaggableObject):
1072
  """Config object representing an instance."""
1073
  __slots__ = [
1074
    "name",
1075
    "primary_node",
1076
    "os",
1077
    "hypervisor",
1078
    "hvparams",
1079
    "beparams",
1080
    "osparams",
1081
    "osparams_private",
1082
    "admin_state",
1083
    "nics",
1084
    "disks",
1085
    "disk_template",
1086
    "disks_active",
1087
    "network_port",
1088
    "serial_no",
1089
    ] + _TIMESTAMPS + _UUID
1090

    
1091
  def _ComputeSecondaryNodes(self):
1092
    """Compute the list of secondary nodes.
1093

1094
    This is a simple wrapper over _ComputeAllNodes.
1095

1096
    """
1097
    all_nodes = set(self._ComputeAllNodes())
1098
    all_nodes.discard(self.primary_node)
1099
    return tuple(all_nodes)
1100

    
1101
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1102
                             "List of names of secondary nodes")
1103

    
1104
  def _ComputeAllNodes(self):
1105
    """Compute the list of all nodes.
1106

1107
    Since the data is already there (in the drbd disks), keeping it as
1108
    a separate normal attribute is redundant and if not properly
1109
    synchronised can cause problems. Thus it's better to compute it
1110
    dynamically.
1111

1112
    """
1113
    def _Helper(nodes, device):
1114
      """Recursively computes nodes given a top device."""
1115
      if device.dev_type in constants.DTS_DRBD:
1116
        nodea, nodeb = device.logical_id[:2]
1117
        nodes.add(nodea)
1118
        nodes.add(nodeb)
1119
      if device.children:
1120
        for child in device.children:
1121
          _Helper(nodes, child)
1122

    
1123
    all_nodes = set()
1124
    all_nodes.add(self.primary_node)
1125
    for device in self.disks:
1126
      _Helper(all_nodes, device)
1127
    return tuple(all_nodes)
1128

    
1129
  all_nodes = property(_ComputeAllNodes, None, None,
1130
                       "List of names of all the nodes of the instance")
1131

    
1132
  def MapLVsByNode(self, lvmap=None, devs=None, node_uuid=None):
1133
    """Provide a mapping of nodes to LVs this instance owns.
1134

1135
    This function figures out what logical volumes should belong on
1136
    which nodes, recursing through a device tree.
1137

1138
    @type lvmap: dict
1139
    @param lvmap: optional dictionary to receive the
1140
        'node' : ['lv', ...] data.
1141
    @type devs: list of L{Disk}
1142
    @param devs: disks to get the LV name for. If None, all disk of this
1143
        instance are used.
1144
    @type node_uuid: string
1145
    @param node_uuid: UUID of the node to get the LV names for. If None, the
1146
        primary node of this instance is used.
1147
    @return: None if lvmap arg is given, otherwise, a dictionary of
1148
        the form { 'node_uuid' : ['volume1', 'volume2', ...], ... };
1149
        volumeN is of the form "vg_name/lv_name", compatible with
1150
        GetVolumeList()
1151

1152
    """
1153
    if node_uuid is None:
1154
      node_uuid = self.primary_node
1155

    
1156
    if lvmap is None:
1157
      lvmap = {
1158
        node_uuid: [],
1159
        }
1160
      ret = lvmap
1161
    else:
1162
      if not node_uuid in lvmap:
1163
        lvmap[node_uuid] = []
1164
      ret = None
1165

    
1166
    if not devs:
1167
      devs = self.disks
1168

    
1169
    for dev in devs:
1170
      if dev.dev_type == constants.DT_PLAIN:
1171
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1172

    
1173
      elif dev.dev_type in constants.DTS_DRBD:
1174
        if dev.children:
1175
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1176
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1177

    
1178
      elif dev.children:
1179
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1180

    
1181
    return ret
1182

    
1183
  def FindDisk(self, idx):
1184
    """Find a disk given having a specified index.
1185

1186
    This is just a wrapper that does validation of the index.
1187

1188
    @type idx: int
1189
    @param idx: the disk index
1190
    @rtype: L{Disk}
1191
    @return: the corresponding disk
1192
    @raise errors.OpPrereqError: when the given index is not valid
1193

1194
    """
1195
    try:
1196
      idx = int(idx)
1197
      return self.disks[idx]
1198
    except (TypeError, ValueError), err:
1199
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1200
                                 errors.ECODE_INVAL)
1201
    except IndexError:
1202
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1203
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1204
                                 errors.ECODE_INVAL)
1205

    
1206
  def ToDict(self, _with_private=False):
1207
    """Instance-specific conversion to standard python types.
1208

1209
    This replaces the children lists of objects with lists of standard
1210
    python types.
1211

1212
    """
1213
    bo = super(Instance, self).ToDict(_with_private=_with_private)
1214

    
1215
    if _with_private:
1216
      bo["osparams_private"] = self.osparams_private.Unprivate()
1217

    
1218
    for attr in "nics", "disks":
1219
      alist = bo.get(attr, None)
1220
      if alist:
1221
        nlist = outils.ContainerToDicts(alist)
1222
      else:
1223
        nlist = []
1224
      bo[attr] = nlist
1225
    return bo
1226

    
1227
  @classmethod
1228
  def FromDict(cls, val):
1229
    """Custom function for instances.
1230

1231
    """
1232
    if "admin_state" not in val:
1233
      if val.get("admin_up", False):
1234
        val["admin_state"] = constants.ADMINST_UP
1235
      else:
1236
        val["admin_state"] = constants.ADMINST_DOWN
1237
    if "admin_up" in val:
1238
      del val["admin_up"]
1239
    obj = super(Instance, cls).FromDict(val)
1240
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1241
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1242
    return obj
1243

    
1244
  def UpgradeConfig(self):
1245
    """Fill defaults for missing configuration values.
1246

1247
    """
1248
    for nic in self.nics:
1249
      nic.UpgradeConfig()
1250
    for disk in self.disks:
1251
      disk.UpgradeConfig()
1252
    if self.hvparams:
1253
      for key in constants.HVC_GLOBALS:
1254
        try:
1255
          del self.hvparams[key]
1256
        except KeyError:
1257
          pass
1258
    if self.osparams is None:
1259
      self.osparams = {}
1260
    if self.osparams_private is None:
1261
      self.osparams_private = serializer.PrivateDict()
1262
    UpgradeBeParams(self.beparams)
1263
    if self.disks_active is None:
1264
      self.disks_active = self.admin_state == constants.ADMINST_UP
1265

    
1266

    
1267
class OS(ConfigObject):
1268
  """Config object representing an operating system.
1269

1270
  @type supported_parameters: list
1271
  @ivar supported_parameters: a list of tuples, name and description,
1272
      containing the supported parameters by this OS
1273

1274
  @type VARIANT_DELIM: string
1275
  @cvar VARIANT_DELIM: the variant delimiter
1276

1277
  """
1278
  __slots__ = [
1279
    "name",
1280
    "path",
1281
    "api_versions",
1282
    "create_script",
1283
    "export_script",
1284
    "import_script",
1285
    "rename_script",
1286
    "verify_script",
1287
    "supported_variants",
1288
    "supported_parameters",
1289
    ]
1290

    
1291
  VARIANT_DELIM = "+"
1292

    
1293
  @classmethod
1294
  def SplitNameVariant(cls, name):
1295
    """Splits the name into the proper name and variant.
1296

1297
    @param name: the OS (unprocessed) name
1298
    @rtype: list
1299
    @return: a list of two elements; if the original name didn't
1300
        contain a variant, it's returned as an empty string
1301

1302
    """
1303
    nv = name.split(cls.VARIANT_DELIM, 1)
1304
    if len(nv) == 1:
1305
      nv.append("")
1306
    return nv
1307

    
1308
  @classmethod
1309
  def GetName(cls, name):
1310
    """Returns the proper name of the os (without the variant).
1311

1312
    @param name: the OS (unprocessed) name
1313

1314
    """
1315
    return cls.SplitNameVariant(name)[0]
1316

    
1317
  @classmethod
1318
  def GetVariant(cls, name):
1319
    """Returns the variant the os (without the base name).
1320

1321
    @param name: the OS (unprocessed) name
1322

1323
    """
1324
    return cls.SplitNameVariant(name)[1]
1325

    
1326

    
1327
class ExtStorage(ConfigObject):
1328
  """Config object representing an External Storage Provider.
1329

1330
  """
1331
  __slots__ = [
1332
    "name",
1333
    "path",
1334
    "create_script",
1335
    "remove_script",
1336
    "grow_script",
1337
    "attach_script",
1338
    "detach_script",
1339
    "setinfo_script",
1340
    "verify_script",
1341
    "supported_parameters",
1342
    ]
1343

    
1344

    
1345
class NodeHvState(ConfigObject):
1346
  """Hypvervisor state on a node.
1347

1348
  @ivar mem_total: Total amount of memory
1349
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1350
    available)
1351
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1352
    rounding
1353
  @ivar mem_inst: Memory used by instances living on node
1354
  @ivar cpu_total: Total node CPU core count
1355
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1356

1357
  """
1358
  __slots__ = [
1359
    "mem_total",
1360
    "mem_node",
1361
    "mem_hv",
1362
    "mem_inst",
1363
    "cpu_total",
1364
    "cpu_node",
1365
    ] + _TIMESTAMPS
1366

    
1367

    
1368
class NodeDiskState(ConfigObject):
1369
  """Disk state on a node.
1370

1371
  """
1372
  __slots__ = [
1373
    "total",
1374
    "reserved",
1375
    "overhead",
1376
    ] + _TIMESTAMPS
1377

    
1378

    
1379
class Node(TaggableObject):
1380
  """Config object representing a node.
1381

1382
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1383
  @ivar hv_state_static: Hypervisor state overriden by user
1384
  @ivar disk_state: Disk state (e.g. free space)
1385
  @ivar disk_state_static: Disk state overriden by user
1386

1387
  """
1388
  __slots__ = [
1389
    "name",
1390
    "primary_ip",
1391
    "secondary_ip",
1392
    "serial_no",
1393
    "master_candidate",
1394
    "offline",
1395
    "drained",
1396
    "group",
1397
    "master_capable",
1398
    "vm_capable",
1399
    "ndparams",
1400
    "powered",
1401
    "hv_state",
1402
    "hv_state_static",
1403
    "disk_state",
1404
    "disk_state_static",
1405
    ] + _TIMESTAMPS + _UUID
1406

    
1407
  def UpgradeConfig(self):
1408
    """Fill defaults for missing configuration values.
1409

1410
    """
1411
    # pylint: disable=E0203
1412
    # because these are "defined" via slots, not manually
1413
    if self.master_capable is None:
1414
      self.master_capable = True
1415

    
1416
    if self.vm_capable is None:
1417
      self.vm_capable = True
1418

    
1419
    if self.ndparams is None:
1420
      self.ndparams = {}
1421
    # And remove any global parameter
1422
    for key in constants.NDC_GLOBALS:
1423
      if key in self.ndparams:
1424
        logging.warning("Ignoring %s node parameter for node %s",
1425
                        key, self.name)
1426
        del self.ndparams[key]
1427

    
1428
    if self.powered is None:
1429
      self.powered = True
1430

    
1431
  def ToDict(self, _with_private=False):
1432
    """Custom function for serializing.
1433

1434
    """
1435
    data = super(Node, self).ToDict(_with_private=_with_private)
1436

    
1437
    hv_state = data.get("hv_state", None)
1438
    if hv_state is not None:
1439
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1440

    
1441
    disk_state = data.get("disk_state", None)
1442
    if disk_state is not None:
1443
      data["disk_state"] = \
1444
        dict((key, outils.ContainerToDicts(value))
1445
             for (key, value) in disk_state.items())
1446

    
1447
    return data
1448

    
1449
  @classmethod
1450
  def FromDict(cls, val):
1451
    """Custom function for deserializing.
1452

1453
    """
1454
    obj = super(Node, cls).FromDict(val)
1455

    
1456
    if obj.hv_state is not None:
1457
      obj.hv_state = \
1458
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1459

    
1460
    if obj.disk_state is not None:
1461
      obj.disk_state = \
1462
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1463
             for (key, value) in obj.disk_state.items())
1464

    
1465
    return obj
1466

    
1467

    
1468
class NodeGroup(TaggableObject):
1469
  """Config object representing a node group."""
1470
  __slots__ = [
1471
    "name",
1472
    "members",
1473
    "ndparams",
1474
    "diskparams",
1475
    "ipolicy",
1476
    "serial_no",
1477
    "hv_state_static",
1478
    "disk_state_static",
1479
    "alloc_policy",
1480
    "networks",
1481
    ] + _TIMESTAMPS + _UUID
1482

    
1483
  def ToDict(self, _with_private=False):
1484
    """Custom function for nodegroup.
1485

1486
    This discards the members object, which gets recalculated and is only kept
1487
    in memory.
1488

1489
    """
1490
    mydict = super(NodeGroup, self).ToDict(_with_private=_with_private)
1491
    del mydict["members"]
1492
    return mydict
1493

    
1494
  @classmethod
1495
  def FromDict(cls, val):
1496
    """Custom function for nodegroup.
1497

1498
    The members slot is initialized to an empty list, upon deserialization.
1499

1500
    """
1501
    obj = super(NodeGroup, cls).FromDict(val)
1502
    obj.members = []
1503
    return obj
1504

    
1505
  def UpgradeConfig(self):
1506
    """Fill defaults for missing configuration values.
1507

1508
    """
1509
    if self.ndparams is None:
1510
      self.ndparams = {}
1511

    
1512
    if self.serial_no is None:
1513
      self.serial_no = 1
1514

    
1515
    if self.alloc_policy is None:
1516
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1517

    
1518
    # We only update mtime, and not ctime, since we would not be able
1519
    # to provide a correct value for creation time.
1520
    if self.mtime is None:
1521
      self.mtime = time.time()
1522

    
1523
    if self.diskparams is None:
1524
      self.diskparams = {}
1525
    if self.ipolicy is None:
1526
      self.ipolicy = MakeEmptyIPolicy()
1527

    
1528
    if self.networks is None:
1529
      self.networks = {}
1530

    
1531
  def FillND(self, node):
1532
    """Return filled out ndparams for L{objects.Node}
1533

1534
    @type node: L{objects.Node}
1535
    @param node: A Node object to fill
1536
    @return a copy of the node's ndparams with defaults filled
1537

1538
    """
1539
    return self.SimpleFillND(node.ndparams)
1540

    
1541
  def SimpleFillND(self, ndparams):
1542
    """Fill a given ndparams dict with defaults.
1543

1544
    @type ndparams: dict
1545
    @param ndparams: the dict to fill
1546
    @rtype: dict
1547
    @return: a copy of the passed in ndparams with missing keys filled
1548
        from the node group defaults
1549

1550
    """
1551
    return FillDict(self.ndparams, ndparams)
1552

    
1553

    
1554
class Cluster(TaggableObject):
1555
  """Config object representing the cluster."""
1556
  __slots__ = [
1557
    "serial_no",
1558
    "rsahostkeypub",
1559
    "dsahostkeypub",
1560
    "highest_used_port",
1561
    "tcpudp_port_pool",
1562
    "mac_prefix",
1563
    "volume_group_name",
1564
    "reserved_lvs",
1565
    "drbd_usermode_helper",
1566
    "default_bridge",
1567
    "default_hypervisor",
1568
    "master_node",
1569
    "master_ip",
1570
    "master_netdev",
1571
    "master_netmask",
1572
    "use_external_mip_script",
1573
    "cluster_name",
1574
    "file_storage_dir",
1575
    "shared_file_storage_dir",
1576
    "gluster_storage_dir",
1577
    "enabled_hypervisors",
1578
    "hvparams",
1579
    "ipolicy",
1580
    "os_hvp",
1581
    "beparams",
1582
    "osparams",
1583
    "osparams_private_cluster",
1584
    "nicparams",
1585
    "ndparams",
1586
    "diskparams",
1587
    "candidate_pool_size",
1588
    "modify_etc_hosts",
1589
    "modify_ssh_setup",
1590
    "maintain_node_health",
1591
    "uid_pool",
1592
    "default_iallocator",
1593
    "default_iallocator_params",
1594
    "hidden_os",
1595
    "blacklisted_os",
1596
    "primary_ip_family",
1597
    "prealloc_wipe_disks",
1598
    "hv_state_static",
1599
    "disk_state_static",
1600
    "enabled_disk_templates",
1601
    "candidate_certs",
1602
    "max_running_jobs",
1603
    "instance_communication_network",
1604
    ] + _TIMESTAMPS + _UUID
1605

    
1606
  def UpgradeConfig(self):
1607
    """Fill defaults for missing configuration values.
1608

1609
    """
1610
    # pylint: disable=E0203
1611
    # because these are "defined" via slots, not manually
1612
    if self.hvparams is None:
1613
      self.hvparams = constants.HVC_DEFAULTS
1614
    else:
1615
      for hypervisor in constants.HYPER_TYPES:
1616
        try:
1617
          existing_params = self.hvparams[hypervisor]
1618
        except KeyError:
1619
          existing_params = {}
1620
        self.hvparams[hypervisor] = FillDict(
1621
            constants.HVC_DEFAULTS[hypervisor], existing_params)
1622

    
1623
    if self.os_hvp is None:
1624
      self.os_hvp = {}
1625

    
1626
    if self.osparams is None:
1627
      self.osparams = {}
1628
    # osparams_private_cluster added in 2.12
1629
    if self.osparams_private_cluster is None:
1630
      self.osparams_private_cluster = {}
1631

    
1632
    self.ndparams = UpgradeNDParams(self.ndparams)
1633

    
1634
    self.beparams = UpgradeGroupedParams(self.beparams,
1635
                                         constants.BEC_DEFAULTS)
1636
    for beparams_group in self.beparams:
1637
      UpgradeBeParams(self.beparams[beparams_group])
1638

    
1639
    migrate_default_bridge = not self.nicparams
1640
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1641
                                          constants.NICC_DEFAULTS)
1642
    if migrate_default_bridge:
1643
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1644
        self.default_bridge
1645

    
1646
    if self.modify_etc_hosts is None:
1647
      self.modify_etc_hosts = True
1648

    
1649
    if self.modify_ssh_setup is None:
1650
      self.modify_ssh_setup = True
1651

    
1652
    # default_bridge is no longer used in 2.1. The slot is left there to
1653
    # support auto-upgrading. It can be removed once we decide to deprecate
1654
    # upgrading straight from 2.0.
1655
    if self.default_bridge is not None:
1656
      self.default_bridge = None
1657

    
1658
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1659
    # code can be removed once upgrading straight from 2.0 is deprecated.
1660
    if self.default_hypervisor is not None:
1661
      self.enabled_hypervisors = ([self.default_hypervisor] +
1662
                                  [hvname for hvname in self.enabled_hypervisors
1663
                                   if hvname != self.default_hypervisor])
1664
      self.default_hypervisor = None
1665

    
1666
    # maintain_node_health added after 2.1.1
1667
    if self.maintain_node_health is None:
1668
      self.maintain_node_health = False
1669

    
1670
    if self.uid_pool is None:
1671
      self.uid_pool = []
1672

    
1673
    if self.default_iallocator is None:
1674
      self.default_iallocator = ""
1675

    
1676
    if self.default_iallocator_params is None:
1677
      self.default_iallocator_params = {}
1678

    
1679
    # reserved_lvs added before 2.2
1680
    if self.reserved_lvs is None:
1681
      self.reserved_lvs = []
1682

    
1683
    # hidden and blacklisted operating systems added before 2.2.1
1684
    if self.hidden_os is None:
1685
      self.hidden_os = []
1686

    
1687
    if self.blacklisted_os is None:
1688
      self.blacklisted_os = []
1689

    
1690
    # primary_ip_family added before 2.3
1691
    if self.primary_ip_family is None:
1692
      self.primary_ip_family = AF_INET
1693

    
1694
    if self.master_netmask is None:
1695
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1696
      self.master_netmask = ipcls.iplen
1697

    
1698
    if self.prealloc_wipe_disks is None:
1699
      self.prealloc_wipe_disks = False
1700

    
1701
    # shared_file_storage_dir added before 2.5
1702
    if self.shared_file_storage_dir is None:
1703
      self.shared_file_storage_dir = ""
1704

    
1705
    # gluster_storage_dir added in 2.11
1706
    if self.gluster_storage_dir is None:
1707
      self.gluster_storage_dir = ""
1708

    
1709
    if self.use_external_mip_script is None:
1710
      self.use_external_mip_script = False
1711

    
1712
    if self.diskparams:
1713
      self.diskparams = UpgradeDiskParams(self.diskparams)
1714
    else:
1715
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1716

    
1717
    # instance policy added before 2.6
1718
    if self.ipolicy is None:
1719
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1720
    else:
1721
      # we can either make sure to upgrade the ipolicy always, or only
1722
      # do it in some corner cases (e.g. missing keys); note that this
1723
      # will break any removal of keys from the ipolicy dict
1724
      wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1725
      if wrongkeys:
1726
        # These keys would be silently removed by FillIPolicy()
1727
        msg = ("Cluster instance policy contains spurious keys: %s" %
1728
               utils.CommaJoin(wrongkeys))
1729
        raise errors.ConfigurationError(msg)
1730
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1731

    
1732
    if self.candidate_certs is None:
1733
      self.candidate_certs = {}
1734

    
1735
    if self.max_running_jobs is None:
1736
      self.max_running_jobs = constants.LUXID_MAXIMAL_RUNNING_JOBS_DEFAULT
1737

    
1738
    if self.instance_communication_network is None:
1739
      self.instance_communication_network = ""
1740

    
1741
  @property
1742
  def primary_hypervisor(self):
1743
    """The first hypervisor is the primary.
1744

1745
    Useful, for example, for L{Node}'s hv/disk state.
1746

1747
    """
1748
    return self.enabled_hypervisors[0]
1749

    
1750
  def ToDict(self, _with_private=False):
1751
    """Custom function for cluster.
1752

1753
    """
1754
    mydict = super(Cluster, self).ToDict(_with_private=_with_private)
1755

    
1756
    # Explicitly save private parameters.
1757
    if _with_private:
1758
      for os in mydict["osparams_private_cluster"]:
1759
        mydict["osparams_private_cluster"][os] = \
1760
          self.osparams_private_cluster[os].Unprivate()
1761

    
1762
    if self.tcpudp_port_pool is None:
1763
      tcpudp_port_pool = []
1764
    else:
1765
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1766

    
1767
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1768

    
1769
    return mydict
1770

    
1771
  @classmethod
1772
  def FromDict(cls, val):
1773
    """Custom function for cluster.
1774

1775
    """
1776
    obj = super(Cluster, cls).FromDict(val)
1777

    
1778
    if obj.tcpudp_port_pool is None:
1779
      obj.tcpudp_port_pool = set()
1780
    elif not isinstance(obj.tcpudp_port_pool, set):
1781
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1782

    
1783
    return obj
1784

    
1785
  def SimpleFillDP(self, diskparams):
1786
    """Fill a given diskparams dict with cluster defaults.
1787

1788
    @param diskparams: The diskparams
1789
    @return: The defaults dict
1790

1791
    """
1792
    return FillDiskParams(self.diskparams, diskparams)
1793

    
1794
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1795
    """Get the default hypervisor parameters for the cluster.
1796

1797
    @param hypervisor: the hypervisor name
1798
    @param os_name: if specified, we'll also update the defaults for this OS
1799
    @param skip_keys: if passed, list of keys not to use
1800
    @return: the defaults dict
1801

1802
    """
1803
    if skip_keys is None:
1804
      skip_keys = []
1805

    
1806
    fill_stack = [self.hvparams.get(hypervisor, {})]
1807
    if os_name is not None:
1808
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1809
      fill_stack.append(os_hvp)
1810

    
1811
    ret_dict = {}
1812
    for o_dict in fill_stack:
1813
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1814

    
1815
    return ret_dict
1816

    
1817
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1818
    """Fill a given hvparams dict with cluster defaults.
1819

1820
    @type hv_name: string
1821
    @param hv_name: the hypervisor to use
1822
    @type os_name: string
1823
    @param os_name: the OS to use for overriding the hypervisor defaults
1824
    @type skip_globals: boolean
1825
    @param skip_globals: if True, the global hypervisor parameters will
1826
        not be filled
1827
    @rtype: dict
1828
    @return: a copy of the given hvparams with missing keys filled from
1829
        the cluster defaults
1830

1831
    """
1832
    if skip_globals:
1833
      skip_keys = constants.HVC_GLOBALS
1834
    else:
1835
      skip_keys = []
1836

    
1837
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1838
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1839

    
1840
  def FillHV(self, instance, skip_globals=False):
1841
    """Fill an instance's hvparams dict with cluster defaults.
1842

1843
    @type instance: L{objects.Instance}
1844
    @param instance: the instance parameter to fill
1845
    @type skip_globals: boolean
1846
    @param skip_globals: if True, the global hypervisor parameters will
1847
        not be filled
1848
    @rtype: dict
1849
    @return: a copy of the instance's hvparams with missing keys filled from
1850
        the cluster defaults
1851

1852
    """
1853
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1854
                             instance.hvparams, skip_globals)
1855

    
1856
  def SimpleFillBE(self, beparams):
1857
    """Fill a given beparams dict with cluster defaults.
1858

1859
    @type beparams: dict
1860
    @param beparams: the dict to fill
1861
    @rtype: dict
1862
    @return: a copy of the passed in beparams with missing keys filled
1863
        from the cluster defaults
1864

1865
    """
1866
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1867

    
1868
  def FillBE(self, instance):
1869
    """Fill an instance's beparams dict with cluster defaults.
1870

1871
    @type instance: L{objects.Instance}
1872
    @param instance: the instance parameter to fill
1873
    @rtype: dict
1874
    @return: a copy of the instance's beparams with missing keys filled from
1875
        the cluster defaults
1876

1877
    """
1878
    return self.SimpleFillBE(instance.beparams)
1879

    
1880
  def SimpleFillNIC(self, nicparams):
1881
    """Fill a given nicparams dict with cluster defaults.
1882

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

1889
    """
1890
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1891

    
1892
  def SimpleFillOS(self, os_name,
1893
                    os_params_public,
1894
                    os_params_private=None,
1895
                    os_params_secret=None):
1896
    """Fill an instance's osparams dict with cluster defaults.
1897

1898
    @type os_name: string
1899
    @param os_name: the OS name to use
1900
    @type os_params_public: dict
1901
    @param os_params_public: the dict to fill with default values
1902
    @type os_params_private: dict
1903
    @param os_params_private: the dict with private fields to fill
1904
                              with default values. Not passing this field
1905
                              results in no private fields being added to the
1906
                              return value. Private fields will be wrapped in
1907
                              L{Private} objects.
1908
    @type os_params_secret: dict
1909
    @param os_params_secret: the dict with secret fields to fill
1910
                             with default values. Not passing this field
1911
                             results in no secret fields being added to the
1912
                             return value. Private fields will be wrapped in
1913
                             L{Private} objects.
1914
    @rtype: dict
1915
    @return: a copy of the instance's osparams with missing keys filled from
1916
        the cluster defaults. Private and secret parameters are not included
1917
        unless the respective optional parameters are supplied.
1918

1919
    """
1920
    name_only = os_name.split("+", 1)[0]
1921

    
1922
    defaults_base_public = self.osparams.get(name_only, {})
1923
    defaults_public = FillDict(defaults_base_public,
1924
                               self.osparams.get(os_name, {}))
1925
    params_public = FillDict(defaults_public, os_params_public)
1926

    
1927
    if os_params_private is not None:
1928
      defaults_base_private = self.osparams_private_cluster.get(name_only, {})
1929
      defaults_private = FillDict(defaults_base_private,
1930
                                  self.osparams_private_cluster.get(os_name,
1931
                                                                    {}))
1932
      params_private = FillDict(defaults_private, os_params_private)
1933
    else:
1934
      params_private = {}
1935

    
1936
    if os_params_secret is not None:
1937
      # There can't be default secret settings, so there's nothing to be done.
1938
      params_secret = os_params_secret
1939
    else:
1940
      params_secret = {}
1941

    
1942
    # Enforce that the set of keys be distinct:
1943
    duplicate_keys = utils.GetRepeatedKeys(params_public,
1944
                                           params_private,
1945
                                           params_secret)
1946
    if not duplicate_keys:
1947

    
1948
      # Actually update them:
1949
      params_public.update(params_private)
1950
      params_public.update(params_secret)
1951

    
1952
      return params_public
1953

    
1954
    else:
1955

    
1956
      def formatter(keys):
1957
        return utils.CommaJoin(sorted(map(repr, keys))) if keys else "(none)"
1958

    
1959
      #Lose the values.
1960
      params_public = set(params_public)
1961
      params_private = set(params_private)
1962
      params_secret = set(params_secret)
1963

    
1964
      msg = """Cannot assign multiple values to OS parameters.
1965

1966
      Conflicting OS parameters that would have been set by this operation:
1967
      - at public visibility:  {public}
1968
      - at private visibility: {private}
1969
      - at secret visibility:  {secret}
1970
      """.format(dupes=formatter(duplicate_keys),
1971
                 public=formatter(params_public & duplicate_keys),
1972
                 private=formatter(params_private & duplicate_keys),
1973
                 secret=formatter(params_secret & duplicate_keys))
1974
      raise errors.OpPrereqError(msg)
1975

    
1976
  @staticmethod
1977
  def SimpleFillHvState(hv_state):
1978
    """Fill an hv_state sub dict with cluster defaults.
1979

1980
    """
1981
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1982

    
1983
  @staticmethod
1984
  def SimpleFillDiskState(disk_state):
1985
    """Fill an disk_state sub dict with cluster defaults.
1986

1987
    """
1988
    return FillDict(constants.DS_DEFAULTS, disk_state)
1989

    
1990
  def FillND(self, node, nodegroup):
1991
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1992

1993
    @type node: L{objects.Node}
1994
    @param node: A Node object to fill
1995
    @type nodegroup: L{objects.NodeGroup}
1996
    @param nodegroup: A Node object to fill
1997
    @return a copy of the node's ndparams with defaults filled
1998

1999
    """
2000
    return self.SimpleFillND(nodegroup.FillND(node))
2001

    
2002
  def FillNDGroup(self, nodegroup):
2003
    """Return filled out ndparams for just L{objects.NodeGroup}
2004

2005
    @type nodegroup: L{objects.NodeGroup}
2006
    @param nodegroup: A Node object to fill
2007
    @return a copy of the node group's ndparams with defaults filled
2008

2009
    """
2010
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
2011

    
2012
  def SimpleFillND(self, ndparams):
2013
    """Fill a given ndparams dict with defaults.
2014

2015
    @type ndparams: dict
2016
    @param ndparams: the dict to fill
2017
    @rtype: dict
2018
    @return: a copy of the passed in ndparams with missing keys filled
2019
        from the cluster defaults
2020

2021
    """
2022
    return FillDict(self.ndparams, ndparams)
2023

    
2024
  def SimpleFillIPolicy(self, ipolicy):
2025
    """ Fill instance policy dict with defaults.
2026

2027
    @type ipolicy: dict
2028
    @param ipolicy: the dict to fill
2029
    @rtype: dict
2030
    @return: a copy of passed ipolicy with missing keys filled from
2031
      the cluster defaults
2032

2033
    """
2034
    return FillIPolicy(self.ipolicy, ipolicy)
2035

    
2036
  def IsDiskTemplateEnabled(self, disk_template):
2037
    """Checks if a particular disk template is enabled.
2038

2039
    """
2040
    return utils.storage.IsDiskTemplateEnabled(
2041
        disk_template, self.enabled_disk_templates)
2042

    
2043
  def IsFileStorageEnabled(self):
2044
    """Checks if file storage is enabled.
2045

2046
    """
2047
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
2048

    
2049
  def IsSharedFileStorageEnabled(self):
2050
    """Checks if shared file storage is enabled.
2051

2052
    """
2053
    return utils.storage.IsSharedFileStorageEnabled(
2054
        self.enabled_disk_templates)
2055

    
2056

    
2057
class BlockDevStatus(ConfigObject):
2058
  """Config object representing the status of a block device."""
2059
  __slots__ = [
2060
    "dev_path",
2061
    "major",
2062
    "minor",
2063
    "sync_percent",
2064
    "estimated_time",
2065
    "is_degraded",
2066
    "ldisk_status",
2067
    ]
2068

    
2069

    
2070
class ImportExportStatus(ConfigObject):
2071
  """Config object representing the status of an import or export."""
2072
  __slots__ = [
2073
    "recent_output",
2074
    "listen_port",
2075
    "connected",
2076
    "progress_mbytes",
2077
    "progress_throughput",
2078
    "progress_eta",
2079
    "progress_percent",
2080
    "exit_status",
2081
    "error_message",
2082
    ] + _TIMESTAMPS
2083

    
2084

    
2085
class ImportExportOptions(ConfigObject):
2086
  """Options for import/export daemon
2087

2088
  @ivar key_name: X509 key name (None for cluster certificate)
2089
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
2090
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
2091
  @ivar magic: Used to ensure the connection goes to the right disk
2092
  @ivar ipv6: Whether to use IPv6
2093
  @ivar connect_timeout: Number of seconds for establishing connection
2094

2095
  """
2096
  __slots__ = [
2097
    "key_name",
2098
    "ca_pem",
2099
    "compress",
2100
    "magic",
2101
    "ipv6",
2102
    "connect_timeout",
2103
    ]
2104

    
2105

    
2106
class ConfdRequest(ConfigObject):
2107
  """Object holding a confd request.
2108

2109
  @ivar protocol: confd protocol version
2110
  @ivar type: confd query type
2111
  @ivar query: query request
2112
  @ivar rsalt: requested reply salt
2113

2114
  """
2115
  __slots__ = [
2116
    "protocol",
2117
    "type",
2118
    "query",
2119
    "rsalt",
2120
    ]
2121

    
2122

    
2123
class ConfdReply(ConfigObject):
2124
  """Object holding a confd reply.
2125

2126
  @ivar protocol: confd protocol version
2127
  @ivar status: reply status code (ok, error)
2128
  @ivar answer: confd query reply
2129
  @ivar serial: configuration serial number
2130

2131
  """
2132
  __slots__ = [
2133
    "protocol",
2134
    "status",
2135
    "answer",
2136
    "serial",
2137
    ]
2138

    
2139

    
2140
class QueryFieldDefinition(ConfigObject):
2141
  """Object holding a query field definition.
2142

2143
  @ivar name: Field name
2144
  @ivar title: Human-readable title
2145
  @ivar kind: Field type
2146
  @ivar doc: Human-readable description
2147

2148
  """
2149
  __slots__ = [
2150
    "name",
2151
    "title",
2152
    "kind",
2153
    "doc",
2154
    ]
2155

    
2156

    
2157
class _QueryResponseBase(ConfigObject):
2158
  __slots__ = [
2159
    "fields",
2160
    ]
2161

    
2162
  def ToDict(self, _with_private=False):
2163
    """Custom function for serializing.
2164

2165
    """
2166
    mydict = super(_QueryResponseBase, self).ToDict()
2167
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2168
    return mydict
2169

    
2170
  @classmethod
2171
  def FromDict(cls, val):
2172
    """Custom function for de-serializing.
2173

2174
    """
2175
    obj = super(_QueryResponseBase, cls).FromDict(val)
2176
    obj.fields = \
2177
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2178
    return obj
2179

    
2180

    
2181
class QueryResponse(_QueryResponseBase):
2182
  """Object holding the response to a query.
2183

2184
  @ivar fields: List of L{QueryFieldDefinition} objects
2185
  @ivar data: Requested data
2186

2187
  """
2188
  __slots__ = [
2189
    "data",
2190
    ]
2191

    
2192

    
2193
class QueryFieldsRequest(ConfigObject):
2194
  """Object holding a request for querying available fields.
2195

2196
  """
2197
  __slots__ = [
2198
    "what",
2199
    "fields",
2200
    ]
2201

    
2202

    
2203
class QueryFieldsResponse(_QueryResponseBase):
2204
  """Object holding the response to a query for fields.
2205

2206
  @ivar fields: List of L{QueryFieldDefinition} objects
2207

2208
  """
2209
  __slots__ = []
2210

    
2211

    
2212
class MigrationStatus(ConfigObject):
2213
  """Object holding the status of a migration.
2214

2215
  """
2216
  __slots__ = [
2217
    "status",
2218
    "transferred_ram",
2219
    "total_ram",
2220
    ]
2221

    
2222

    
2223
class InstanceConsole(ConfigObject):
2224
  """Object describing how to access the console of an instance.
2225

2226
  """
2227
  __slots__ = [
2228
    "instance",
2229
    "kind",
2230
    "message",
2231
    "host",
2232
    "port",
2233
    "user",
2234
    "command",
2235
    "display",
2236
    ]
2237

    
2238
  def Validate(self):
2239
    """Validates contents of this object.
2240

2241
    """
2242
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2243
    assert self.instance, "Missing instance name"
2244
    assert self.message or self.kind in [constants.CONS_SSH,
2245
                                         constants.CONS_SPICE,
2246
                                         constants.CONS_VNC]
2247
    assert self.host or self.kind == constants.CONS_MESSAGE
2248
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2249
                                      constants.CONS_SSH]
2250
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2251
                                      constants.CONS_SPICE,
2252
                                      constants.CONS_VNC]
2253
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2254
                                         constants.CONS_SPICE,
2255
                                         constants.CONS_VNC]
2256
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2257
                                         constants.CONS_SPICE,
2258
                                         constants.CONS_SSH]
2259
    return True
2260

    
2261

    
2262
class Network(TaggableObject):
2263
  """Object representing a network definition for ganeti.
2264

2265
  """
2266
  __slots__ = [
2267
    "name",
2268
    "serial_no",
2269
    "mac_prefix",
2270
    "network",
2271
    "network6",
2272
    "gateway",
2273
    "gateway6",
2274
    "reservations",
2275
    "ext_reservations",
2276
    ] + _TIMESTAMPS + _UUID
2277

    
2278
  def HooksDict(self, prefix=""):
2279
    """Export a dictionary used by hooks with a network's information.
2280

2281
    @type prefix: String
2282
    @param prefix: Prefix to prepend to the dict entries
2283

2284
    """
2285
    result = {
2286
      "%sNETWORK_NAME" % prefix: self.name,
2287
      "%sNETWORK_UUID" % prefix: self.uuid,
2288
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2289
    }
2290
    if self.network:
2291
      result["%sNETWORK_SUBNET" % prefix] = self.network
2292
    if self.gateway:
2293
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2294
    if self.network6:
2295
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2296
    if self.gateway6:
2297
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2298
    if self.mac_prefix:
2299
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2300

    
2301
    return result
2302

    
2303
  @classmethod
2304
  def FromDict(cls, val):
2305
    """Custom function for networks.
2306

2307
    Remove deprecated network_type and family.
2308

2309
    """
2310
    if "network_type" in val:
2311
      del val["network_type"]
2312
    if "family" in val:
2313
      del val["family"]
2314
    obj = super(Network, cls).FromDict(val)
2315
    return obj
2316

    
2317

    
2318
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2319
  """Simple wrapper over ConfigParse that allows serialization.
2320

2321
  This class is basically ConfigParser.SafeConfigParser with two
2322
  additional methods that allow it to serialize/unserialize to/from a
2323
  buffer.
2324

2325
  """
2326
  def Dumps(self):
2327
    """Dump this instance and return the string representation."""
2328
    buf = StringIO()
2329
    self.write(buf)
2330
    return buf.getvalue()
2331

    
2332
  @classmethod
2333
  def Loads(cls, data):
2334
    """Load data from a string."""
2335
    buf = StringIO(data)
2336
    cfp = cls()
2337
    cfp.readfp(buf)
2338
    return cfp
2339

    
2340

    
2341
class LvmPvInfo(ConfigObject):
2342
  """Information about an LVM physical volume (PV).
2343

2344
  @type name: string
2345
  @ivar name: name of the PV
2346
  @type vg_name: string
2347
  @ivar vg_name: name of the volume group containing the PV
2348
  @type size: float
2349
  @ivar size: size of the PV in MiB
2350
  @type free: float
2351
  @ivar free: free space in the PV, in MiB
2352
  @type attributes: string
2353
  @ivar attributes: PV attributes
2354
  @type lv_list: list of strings
2355
  @ivar lv_list: names of the LVs hosted on the PV
2356
  """
2357
  __slots__ = [
2358
    "name",
2359
    "vg_name",
2360
    "size",
2361
    "free",
2362
    "attributes",
2363
    "lv_list"
2364
    ]
2365

    
2366
  def IsEmpty(self):
2367
    """Is this PV empty?
2368

2369
    """
2370
    return self.size <= (self.free + 1)
2371

    
2372
  def IsAllocatable(self):
2373
    """Is this PV allocatable?
2374

2375
    """
2376
    return ("a" in self.attributes)