Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 5349519d

History | View | Annotate | Download (70.9 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
    "serial_no",
399
    ] + _TIMESTAMPS
400

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

404
    This just replaces the list of instances, nodes and the cluster
405
    with standard python types.
406

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

    
413
    return mydict
414

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

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

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

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

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

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

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

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

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

    
493

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

    
499
  @classmethod
500
  def CheckParameterSyntax(cls, nicparams):
501
    """Check the given parameters for validity.
502

503
    @type nicparams:  dict
504
    @param nicparams: dictionary with parameter names/value
505
    @raise errors.ConfigurationError: when a parameter is not valid
506

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

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

    
517

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

    
526
  def CreateOnSecondary(self):
527
    """Test if this device needs to be created on a secondary node."""
528
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
529

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

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

    
538
  def StaticDevPath(self):
539
    """Return the device path if this device type has a static one.
540

541
    Some devices (LVM for example) live always at the same /dev/ path,
542
    irrespective of their status. For such devices, we return this
543
    path, for others we return None.
544

545
    @warning: The path returned is not a normalized pathname; callers
546
        should check that it is a valid path.
547

548
    """
549
    if self.dev_type == constants.DT_PLAIN:
550
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
551
    elif self.dev_type == constants.DT_BLOCK:
552
      return self.logical_id[1]
553
    elif self.dev_type == constants.DT_RBD:
554
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
555
    return None
556

    
557
  def ChildrenNeeded(self):
558
    """Compute the needed number of children for activation.
559

560
    This method will return either -1 (all children) or a positive
561
    number denoting the minimum number of children needed for
562
    activation (only mirrored devices will usually return >=0).
563

564
    Currently, only DRBD8 supports diskless activation (therefore we
565
    return 0), for all other we keep the previous semantics and return
566
    -1.
567

568
    """
569
    if self.dev_type == constants.DT_DRBD8:
570
      return 0
571
    return -1
572

    
573
  def IsBasedOnDiskType(self, dev_type):
574
    """Check if the disk or its children are based on the given type.
575

576
    @type dev_type: L{constants.DTS_BLOCK}
577
    @param dev_type: the type to look for
578
    @rtype: boolean
579
    @return: boolean indicating if a device of the given type was found or not
580

581
    """
582
    if self.children:
583
      for child in self.children:
584
        if child.IsBasedOnDiskType(dev_type):
585
          return True
586
    return self.dev_type == dev_type
587

    
588
  def GetNodes(self, node_uuid):
589
    """This function returns the nodes this device lives on.
590

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

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

    
610
  def ComputeNodeTree(self, parent_node_uuid):
611
    """Compute the node/disk tree for this disk and its children.
612

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

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

    
645
  def ComputeGrowth(self, amount):
646
    """Compute the per-VG growth requirements.
647

648
    This only works for VG-based disks.
649

650
    @type amount: integer
651
    @param amount: the desired increase in (user-visible) disk space
652
    @rtype: dict
653
    @return: a dictionary of volume-groups and the required size
654

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

    
667
  def RecordGrow(self, amount):
668
    """Update the size of this disk after growth.
669

670
    This method recurses over the disks's children and updates their
671
    size correspondigly. The method needs to be kept in sync with the
672
    actual algorithms from bdev.
673

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

    
687
  def Update(self, size=None, mode=None, spindles=None):
688
    """Apply changes to size, spindles and mode.
689

690
    """
691
    if self.dev_type == constants.DT_DRBD8:
692
      if self.children:
693
        self.children[0].Update(size=size, mode=mode)
694
    else:
695
      assert not self.children
696

    
697
    if size is not None:
698
      self.size = size
699
    if mode is not None:
700
      self.mode = mode
701
    if spindles is not None:
702
      self.spindles = spindles
703

    
704
  def UnsetSize(self):
705
    """Sets recursively the size to zero for the disk and its children.
706

707
    """
708
    if self.children:
709
      for child in self.children:
710
        child.UnsetSize()
711
    self.size = 0
712

    
713
  def UpdateDynamicDiskParams(self, target_node_uuid, nodes_ip):
714
    """Updates the dynamic disk params for the given node.
715

716
    This is mainly used for drbd, which needs ip/port configuration.
717

718
    Arguments:
719
      - target_node_uuid: the node UUID we wish to configure for
720
      - nodes_ip: a mapping of node name to ip
721

722
    The target_node must exist in nodes_ip, and should be one of the
723
    nodes in the logical ID if this device is a DRBD device.
724

725
    """
726
    if self.children:
727
      for child in self.children:
728
        child.UpdateDynamicDiskParams(target_node_uuid, nodes_ip)
729

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

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

    
756
    self.dynamic_params = dyn_disk_params
757

    
758
  # pylint: disable=W0221
759
  def ToDict(self, include_dynamic_params=False,
760
             _with_private=False):
761
    """Disk-specific conversion to standard python types.
762

763
    This replaces the children lists of objects with lists of
764
    standard python types.
765

766
    """
767
    bo = super(Disk, self).ToDict()
768
    if not include_dynamic_params and "dynamic_params" in bo:
769
      del bo["dynamic_params"]
770

    
771
    for attr in ("children",):
772
      alist = bo.get(attr, None)
773
      if alist:
774
        bo[attr] = outils.ContainerToDicts(alist)
775
    return bo
776

    
777
  @classmethod
778
  def FromDict(cls, val):
779
    """Custom function for Disks
780

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

    
793
  def __str__(self):
794
    """Custom str() formatter for disks.
795

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

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

    
824
  def Verify(self):
825
    """Checks that this disk is correctly configured.
826

827
    """
828
    all_errors = []
829
    if self.mode not in constants.DISK_ACCESS_SET:
830
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
831
    return all_errors
832

    
833
  def UpgradeConfig(self):
834
    """Fill defaults for missing configuration values.
835

836
    """
837
    if self.children:
838
      for child in self.children:
839
        child.UpgradeConfig()
840

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

    
848
    # add here config upgrade for this disk
849

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

    
856
  @staticmethod
857
  def ComputeLDParams(disk_template, disk_params):
858
    """Computes Logical Disk parameters from Disk Template parameters.
859

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

869
    """
870
    if disk_template not in constants.DISK_TEMPLATES:
871
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
872

    
873
    assert disk_template in disk_params
874

    
875
    result = list()
876
    dt_params = disk_params[disk_template]
877

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

    
895
      # data LV
896
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
897
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
898
        }))
899

    
900
      # metadata LV
901
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
902
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
903
        }))
904

    
905
    else:
906
      defaults = constants.DISK_LD_DEFAULTS[disk_template]
907
      values = {}
908
      for field in defaults:
909
        values[field] = dt_params[field]
910
      result.append(FillDict(defaults, values))
911

    
912
    return result
913

    
914

    
915
class InstancePolicy(ConfigObject):
916
  """Config object representing instance policy limits dictionary.
917

918
  Note that this object is not actually used in the config, it's just
919
  used as a placeholder for a few functions.
920

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

    
931
  @classmethod
932
  def CheckParameterSyntax(cls, ipolicy, check_std):
933
    """ Check the instance policy for validity.
934

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

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

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

    
961
  @classmethod
962
  def CheckISpecSyntax(cls, ipolicy, check_std):
963
    """Check the instance policy specs for validity.
964

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

971
    """
972
    if constants.ISPECS_MINMAX not in ipolicy:
973
      # Nothing to check
974
      return
975

    
976
    if check_std and constants.ISPECS_STD not in ipolicy:
977
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
978
      raise errors.ConfigurationError(msg)
979
    stdspec = ipolicy.get(constants.ISPECS_STD)
980
    if check_std:
981
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
982

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

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

    
1003
  @classmethod
1004
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
1005
    """Check the instance policy specs for validity on a given key.
1006

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

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

1024
    """
1025
    minspec = minmaxspecs[constants.ISPECS_MIN]
1026
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1027
    min_v = minspec[name]
1028
    max_v = maxspec[name]
1029

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

    
1040
  @classmethod
1041
  def CheckDiskTemplates(cls, disk_templates):
1042
    """Checks the disk templates for validity.
1043

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

    
1053
  @classmethod
1054
  def CheckParameter(cls, key, value):
1055
    """Checks a parameter.
1056

1057
    Currently we expect all parameters to be float values.
1058

1059
    """
1060
    try:
1061
      float(value)
1062
    except (TypeError, ValueError), err:
1063
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1064
                                      " '%s', error: %s" % (key, value, err))
1065

    
1066

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

    
1087
  def _ComputeSecondaryNodes(self):
1088
    """Compute the list of secondary nodes.
1089

1090
    This is a simple wrapper over _ComputeAllNodes.
1091

1092
    """
1093
    all_nodes = set(self._ComputeAllNodes())
1094
    all_nodes.discard(self.primary_node)
1095
    return tuple(all_nodes)
1096

    
1097
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1098
                             "List of names of secondary nodes")
1099

    
1100
  def _ComputeAllNodes(self):
1101
    """Compute the list of all nodes.
1102

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

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

    
1119
    all_nodes = set()
1120
    for device in self.disks:
1121
      _Helper(all_nodes, device)
1122
    # ensure that the primary node is always the first
1123
    all_nodes.discard(self.primary_node)
1124
    return (self.primary_node, ) + tuple(all_nodes)
1125

    
1126
  all_nodes = property(_ComputeAllNodes, None, None,
1127
                       "List of names of all the nodes of the instance")
1128

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

1132
    This function figures out what logical volumes should belong on
1133
    which nodes, recursing through a device tree.
1134

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

1149
    """
1150
    if node_uuid is None:
1151
      node_uuid = self.primary_node
1152

    
1153
    if lvmap is None:
1154
      lvmap = {
1155
        node_uuid: [],
1156
        }
1157
      ret = lvmap
1158
    else:
1159
      if not node_uuid in lvmap:
1160
        lvmap[node_uuid] = []
1161
      ret = None
1162

    
1163
    if not devs:
1164
      devs = self.disks
1165

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

    
1170
      elif dev.dev_type in constants.DTS_DRBD:
1171
        if dev.children:
1172
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1173
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1174

    
1175
      elif dev.children:
1176
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1177

    
1178
    return ret
1179

    
1180
  def FindDisk(self, idx):
1181
    """Find a disk given having a specified index.
1182

1183
    This is just a wrapper that does validation of the index.
1184

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

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

    
1203
  def ToDict(self, _with_private=False):
1204
    """Instance-specific conversion to standard python types.
1205

1206
    This replaces the children lists of objects with lists of standard
1207
    python types.
1208

1209
    """
1210
    bo = super(Instance, self).ToDict(_with_private=_with_private)
1211

    
1212
    if _with_private:
1213
      bo["osparams_private"] = self.osparams_private.Unprivate()
1214

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

    
1224
  @classmethod
1225
  def FromDict(cls, val):
1226
    """Custom function for instances.
1227

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

    
1241
  def UpgradeConfig(self):
1242
    """Fill defaults for missing configuration values.
1243

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

    
1263

    
1264
class OS(ConfigObject):
1265
  """Config object representing an operating system.
1266

1267
  @type supported_parameters: list
1268
  @ivar supported_parameters: a list of tuples, name and description,
1269
      containing the supported parameters by this OS
1270

1271
  @type VARIANT_DELIM: string
1272
  @cvar VARIANT_DELIM: the variant delimiter
1273

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

    
1288
  VARIANT_DELIM = "+"
1289

    
1290
  @classmethod
1291
  def SplitNameVariant(cls, name):
1292
    """Splits the name into the proper name and variant.
1293

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

1299
    """
1300
    nv = name.split(cls.VARIANT_DELIM, 1)
1301
    if len(nv) == 1:
1302
      nv.append("")
1303
    return nv
1304

    
1305
  @classmethod
1306
  def GetName(cls, name):
1307
    """Returns the proper name of the os (without the variant).
1308

1309
    @param name: the OS (unprocessed) name
1310

1311
    """
1312
    return cls.SplitNameVariant(name)[0]
1313

    
1314
  @classmethod
1315
  def GetVariant(cls, name):
1316
    """Returns the variant the os (without the base name).
1317

1318
    @param name: the OS (unprocessed) name
1319

1320
    """
1321
    return cls.SplitNameVariant(name)[1]
1322

    
1323

    
1324
class ExtStorage(ConfigObject):
1325
  """Config object representing an External Storage Provider.
1326

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

    
1341

    
1342
class NodeHvState(ConfigObject):
1343
  """Hypvervisor state on a node.
1344

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

1354
  """
1355
  __slots__ = [
1356
    "mem_total",
1357
    "mem_node",
1358
    "mem_hv",
1359
    "mem_inst",
1360
    "cpu_total",
1361
    "cpu_node",
1362
    ] + _TIMESTAMPS
1363

    
1364

    
1365
class NodeDiskState(ConfigObject):
1366
  """Disk state on a node.
1367

1368
  """
1369
  __slots__ = [
1370
    "total",
1371
    "reserved",
1372
    "overhead",
1373
    ] + _TIMESTAMPS
1374

    
1375

    
1376
class Node(TaggableObject):
1377
  """Config object representing a node.
1378

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

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

    
1404
  def UpgradeConfig(self):
1405
    """Fill defaults for missing configuration values.
1406

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

    
1413
    if self.vm_capable is None:
1414
      self.vm_capable = True
1415

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

    
1425
    if self.powered is None:
1426
      self.powered = True
1427

    
1428
  def ToDict(self, _with_private=False):
1429
    """Custom function for serializing.
1430

1431
    """
1432
    data = super(Node, self).ToDict(_with_private=_with_private)
1433

    
1434
    hv_state = data.get("hv_state", None)
1435
    if hv_state is not None:
1436
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1437

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

    
1444
    return data
1445

    
1446
  @classmethod
1447
  def FromDict(cls, val):
1448
    """Custom function for deserializing.
1449

1450
    """
1451
    obj = super(Node, cls).FromDict(val)
1452

    
1453
    if obj.hv_state is not None:
1454
      obj.hv_state = \
1455
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1456

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

    
1462
    return obj
1463

    
1464

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

    
1480
  def ToDict(self, _with_private=False):
1481
    """Custom function for nodegroup.
1482

1483
    This discards the members object, which gets recalculated and is only kept
1484
    in memory.
1485

1486
    """
1487
    mydict = super(NodeGroup, self).ToDict(_with_private=_with_private)
1488
    del mydict["members"]
1489
    return mydict
1490

    
1491
  @classmethod
1492
  def FromDict(cls, val):
1493
    """Custom function for nodegroup.
1494

1495
    The members slot is initialized to an empty list, upon deserialization.
1496

1497
    """
1498
    obj = super(NodeGroup, cls).FromDict(val)
1499
    obj.members = []
1500
    return obj
1501

    
1502
  def UpgradeConfig(self):
1503
    """Fill defaults for missing configuration values.
1504

1505
    """
1506
    if self.ndparams is None:
1507
      self.ndparams = {}
1508

    
1509
    if self.serial_no is None:
1510
      self.serial_no = 1
1511

    
1512
    if self.alloc_policy is None:
1513
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1514

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

    
1520
    if self.diskparams is None:
1521
      self.diskparams = {}
1522
    if self.ipolicy is None:
1523
      self.ipolicy = MakeEmptyIPolicy()
1524

    
1525
    if self.networks is None:
1526
      self.networks = {}
1527

    
1528
  def FillND(self, node):
1529
    """Return filled out ndparams for L{objects.Node}
1530

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

1535
    """
1536
    return self.SimpleFillND(node.ndparams)
1537

    
1538
  def SimpleFillND(self, ndparams):
1539
    """Fill a given ndparams dict with defaults.
1540

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

1547
    """
1548
    return FillDict(self.ndparams, ndparams)
1549

    
1550

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

    
1603
  def UpgradeConfig(self):
1604
    """Fill defaults for missing configuration values.
1605

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

    
1620
    if self.os_hvp is None:
1621
      self.os_hvp = {}
1622

    
1623
    if self.osparams is None:
1624
      self.osparams = {}
1625
    # osparams_private_cluster added in 2.12
1626
    if self.osparams_private_cluster is None:
1627
      self.osparams_private_cluster = {}
1628

    
1629
    self.ndparams = UpgradeNDParams(self.ndparams)
1630

    
1631
    self.beparams = UpgradeGroupedParams(self.beparams,
1632
                                         constants.BEC_DEFAULTS)
1633
    for beparams_group in self.beparams:
1634
      UpgradeBeParams(self.beparams[beparams_group])
1635

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

    
1643
    if self.modify_etc_hosts is None:
1644
      self.modify_etc_hosts = True
1645

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

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

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

    
1663
    # maintain_node_health added after 2.1.1
1664
    if self.maintain_node_health is None:
1665
      self.maintain_node_health = False
1666

    
1667
    if self.uid_pool is None:
1668
      self.uid_pool = []
1669

    
1670
    if self.default_iallocator is None:
1671
      self.default_iallocator = ""
1672

    
1673
    if self.default_iallocator_params is None:
1674
      self.default_iallocator_params = {}
1675

    
1676
    # reserved_lvs added before 2.2
1677
    if self.reserved_lvs is None:
1678
      self.reserved_lvs = []
1679

    
1680
    # hidden and blacklisted operating systems added before 2.2.1
1681
    if self.hidden_os is None:
1682
      self.hidden_os = []
1683

    
1684
    if self.blacklisted_os is None:
1685
      self.blacklisted_os = []
1686

    
1687
    # primary_ip_family added before 2.3
1688
    if self.primary_ip_family is None:
1689
      self.primary_ip_family = AF_INET
1690

    
1691
    if self.master_netmask is None:
1692
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1693
      self.master_netmask = ipcls.iplen
1694

    
1695
    if self.prealloc_wipe_disks is None:
1696
      self.prealloc_wipe_disks = False
1697

    
1698
    # shared_file_storage_dir added before 2.5
1699
    if self.shared_file_storage_dir is None:
1700
      self.shared_file_storage_dir = ""
1701

    
1702
    # gluster_storage_dir added in 2.11
1703
    if self.gluster_storage_dir is None:
1704
      self.gluster_storage_dir = ""
1705

    
1706
    if self.use_external_mip_script is None:
1707
      self.use_external_mip_script = False
1708

    
1709
    if self.diskparams:
1710
      self.diskparams = UpgradeDiskParams(self.diskparams)
1711
    else:
1712
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1713

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

    
1729
    if self.candidate_certs is None:
1730
      self.candidate_certs = {}
1731

    
1732
    if self.max_running_jobs is None:
1733
      self.max_running_jobs = constants.LUXID_MAXIMAL_RUNNING_JOBS_DEFAULT
1734

    
1735
    if self.instance_communication_network is None:
1736
      self.instance_communication_network = ""
1737

    
1738
  @property
1739
  def primary_hypervisor(self):
1740
    """The first hypervisor is the primary.
1741

1742
    Useful, for example, for L{Node}'s hv/disk state.
1743

1744
    """
1745
    return self.enabled_hypervisors[0]
1746

    
1747
  def ToDict(self, _with_private=False):
1748
    """Custom function for cluster.
1749

1750
    """
1751
    mydict = super(Cluster, self).ToDict(_with_private=_with_private)
1752

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

    
1759
    if self.tcpudp_port_pool is None:
1760
      tcpudp_port_pool = []
1761
    else:
1762
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1763

    
1764
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1765

    
1766
    return mydict
1767

    
1768
  @classmethod
1769
  def FromDict(cls, val):
1770
    """Custom function for cluster.
1771

1772
    """
1773
    obj = super(Cluster, cls).FromDict(val)
1774

    
1775
    if obj.tcpudp_port_pool is None:
1776
      obj.tcpudp_port_pool = set()
1777
    elif not isinstance(obj.tcpudp_port_pool, set):
1778
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1779

    
1780
    return obj
1781

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

1785
    @param diskparams: The diskparams
1786
    @return: The defaults dict
1787

1788
    """
1789
    return FillDiskParams(self.diskparams, diskparams)
1790

    
1791
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1792
    """Get the default hypervisor parameters for the cluster.
1793

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

1799
    """
1800
    if skip_keys is None:
1801
      skip_keys = []
1802

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

    
1808
    ret_dict = {}
1809
    for o_dict in fill_stack:
1810
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1811

    
1812
    return ret_dict
1813

    
1814
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1815
    """Fill a given hvparams dict with cluster defaults.
1816

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

1828
    """
1829
    if skip_globals:
1830
      skip_keys = constants.HVC_GLOBALS
1831
    else:
1832
      skip_keys = []
1833

    
1834
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1835
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1836

    
1837
  def FillHV(self, instance, skip_globals=False):
1838
    """Fill an instance's hvparams dict with cluster defaults.
1839

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

1849
    """
1850
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1851
                             instance.hvparams, skip_globals)
1852

    
1853
  def SimpleFillBE(self, beparams):
1854
    """Fill a given beparams dict with cluster defaults.
1855

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

1862
    """
1863
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1864

    
1865
  def FillBE(self, instance):
1866
    """Fill an instance's beparams dict with cluster defaults.
1867

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

1874
    """
1875
    return self.SimpleFillBE(instance.beparams)
1876

    
1877
  def SimpleFillNIC(self, nicparams):
1878
    """Fill a given nicparams dict with cluster defaults.
1879

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

1886
    """
1887
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1888

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

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

1916
    """
1917
    name_only = os_name.split("+", 1)[0]
1918

    
1919
    defaults_base_public = self.osparams.get(name_only, {})
1920
    defaults_public = FillDict(defaults_base_public,
1921
                               self.osparams.get(os_name, {}))
1922
    params_public = FillDict(defaults_public, os_params_public)
1923

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

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

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

    
1945
      # Actually update them:
1946
      params_public.update(params_private)
1947
      params_public.update(params_secret)
1948

    
1949
      return params_public
1950

    
1951
    else:
1952

    
1953
      def formatter(keys):
1954
        return utils.CommaJoin(sorted(map(repr, keys))) if keys else "(none)"
1955

    
1956
      #Lose the values.
1957
      params_public = set(params_public)
1958
      params_private = set(params_private)
1959
      params_secret = set(params_secret)
1960

    
1961
      msg = """Cannot assign multiple values to OS parameters.
1962

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

    
1973
  @staticmethod
1974
  def SimpleFillHvState(hv_state):
1975
    """Fill an hv_state sub dict with cluster defaults.
1976

1977
    """
1978
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1979

    
1980
  @staticmethod
1981
  def SimpleFillDiskState(disk_state):
1982
    """Fill an disk_state sub dict with cluster defaults.
1983

1984
    """
1985
    return FillDict(constants.DS_DEFAULTS, disk_state)
1986

    
1987
  def FillND(self, node, nodegroup):
1988
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1989

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

1996
    """
1997
    return self.SimpleFillND(nodegroup.FillND(node))
1998

    
1999
  def FillNDGroup(self, nodegroup):
2000
    """Return filled out ndparams for just L{objects.NodeGroup}
2001

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

2006
    """
2007
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
2008

    
2009
  def SimpleFillND(self, ndparams):
2010
    """Fill a given ndparams dict with defaults.
2011

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

2018
    """
2019
    return FillDict(self.ndparams, ndparams)
2020

    
2021
  def SimpleFillIPolicy(self, ipolicy):
2022
    """ Fill instance policy dict with defaults.
2023

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

2030
    """
2031
    return FillIPolicy(self.ipolicy, ipolicy)
2032

    
2033
  def IsDiskTemplateEnabled(self, disk_template):
2034
    """Checks if a particular disk template is enabled.
2035

2036
    """
2037
    return utils.storage.IsDiskTemplateEnabled(
2038
        disk_template, self.enabled_disk_templates)
2039

    
2040
  def IsFileStorageEnabled(self):
2041
    """Checks if file storage is enabled.
2042

2043
    """
2044
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
2045

    
2046
  def IsSharedFileStorageEnabled(self):
2047
    """Checks if shared file storage is enabled.
2048

2049
    """
2050
    return utils.storage.IsSharedFileStorageEnabled(
2051
        self.enabled_disk_templates)
2052

    
2053

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

    
2066

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

    
2081

    
2082
class ImportExportOptions(ConfigObject):
2083
  """Options for import/export daemon
2084

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

2092
  """
2093
  __slots__ = [
2094
    "key_name",
2095
    "ca_pem",
2096
    "compress",
2097
    "magic",
2098
    "ipv6",
2099
    "connect_timeout",
2100
    ]
2101

    
2102

    
2103
class ConfdRequest(ConfigObject):
2104
  """Object holding a confd request.
2105

2106
  @ivar protocol: confd protocol version
2107
  @ivar type: confd query type
2108
  @ivar query: query request
2109
  @ivar rsalt: requested reply salt
2110

2111
  """
2112
  __slots__ = [
2113
    "protocol",
2114
    "type",
2115
    "query",
2116
    "rsalt",
2117
    ]
2118

    
2119

    
2120
class ConfdReply(ConfigObject):
2121
  """Object holding a confd reply.
2122

2123
  @ivar protocol: confd protocol version
2124
  @ivar status: reply status code (ok, error)
2125
  @ivar answer: confd query reply
2126
  @ivar serial: configuration serial number
2127

2128
  """
2129
  __slots__ = [
2130
    "protocol",
2131
    "status",
2132
    "answer",
2133
    "serial",
2134
    ]
2135

    
2136

    
2137
class QueryFieldDefinition(ConfigObject):
2138
  """Object holding a query field definition.
2139

2140
  @ivar name: Field name
2141
  @ivar title: Human-readable title
2142
  @ivar kind: Field type
2143
  @ivar doc: Human-readable description
2144

2145
  """
2146
  __slots__ = [
2147
    "name",
2148
    "title",
2149
    "kind",
2150
    "doc",
2151
    ]
2152

    
2153

    
2154
class _QueryResponseBase(ConfigObject):
2155
  __slots__ = [
2156
    "fields",
2157
    ]
2158

    
2159
  def ToDict(self, _with_private=False):
2160
    """Custom function for serializing.
2161

2162
    """
2163
    mydict = super(_QueryResponseBase, self).ToDict()
2164
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2165
    return mydict
2166

    
2167
  @classmethod
2168
  def FromDict(cls, val):
2169
    """Custom function for de-serializing.
2170

2171
    """
2172
    obj = super(_QueryResponseBase, cls).FromDict(val)
2173
    obj.fields = \
2174
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2175
    return obj
2176

    
2177

    
2178
class QueryResponse(_QueryResponseBase):
2179
  """Object holding the response to a query.
2180

2181
  @ivar fields: List of L{QueryFieldDefinition} objects
2182
  @ivar data: Requested data
2183

2184
  """
2185
  __slots__ = [
2186
    "data",
2187
    ]
2188

    
2189

    
2190
class QueryFieldsRequest(ConfigObject):
2191
  """Object holding a request for querying available fields.
2192

2193
  """
2194
  __slots__ = [
2195
    "what",
2196
    "fields",
2197
    ]
2198

    
2199

    
2200
class QueryFieldsResponse(_QueryResponseBase):
2201
  """Object holding the response to a query for fields.
2202

2203
  @ivar fields: List of L{QueryFieldDefinition} objects
2204

2205
  """
2206
  __slots__ = []
2207

    
2208

    
2209
class MigrationStatus(ConfigObject):
2210
  """Object holding the status of a migration.
2211

2212
  """
2213
  __slots__ = [
2214
    "status",
2215
    "transferred_ram",
2216
    "total_ram",
2217
    ]
2218

    
2219

    
2220
class InstanceConsole(ConfigObject):
2221
  """Object describing how to access the console of an instance.
2222

2223
  """
2224
  __slots__ = [
2225
    "instance",
2226
    "kind",
2227
    "message",
2228
    "host",
2229
    "port",
2230
    "user",
2231
    "command",
2232
    "display",
2233
    ]
2234

    
2235
  def Validate(self):
2236
    """Validates contents of this object.
2237

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

    
2258

    
2259
class Network(TaggableObject):
2260
  """Object representing a network definition for ganeti.
2261

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

    
2275
  def HooksDict(self, prefix=""):
2276
    """Export a dictionary used by hooks with a network's information.
2277

2278
    @type prefix: String
2279
    @param prefix: Prefix to prepend to the dict entries
2280

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

    
2298
    return result
2299

    
2300
  @classmethod
2301
  def FromDict(cls, val):
2302
    """Custom function for networks.
2303

2304
    Remove deprecated network_type and family.
2305

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

    
2314

    
2315
# need to inherit object in order to use super()
2316
class SerializableConfigParser(ConfigParser.SafeConfigParser, object):
2317
  """Simple wrapper over ConfigParse that allows serialization.
2318

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

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

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

    
2338
  def get(self, section, option, **kwargs):
2339
    value = None
2340
    try:
2341
      value = super(SerializableConfigParser, self).get(section, option,
2342
                                                        **kwargs)
2343
      if value.lower() == constants.VALUE_NONE:
2344
        value = None
2345
    except ConfigParser.NoOptionError:
2346
      r = re.compile(r"(disk|nic)\d+_name|nic\d+_(network|vlan)")
2347
      match = r.match(option)
2348
      if match:
2349
        pass
2350
      else:
2351
        raise
2352

    
2353
    return value
2354

    
2355

    
2356
class LvmPvInfo(ConfigObject):
2357
  """Information about an LVM physical volume (PV).
2358

2359
  @type name: string
2360
  @ivar name: name of the PV
2361
  @type vg_name: string
2362
  @ivar vg_name: name of the volume group containing the PV
2363
  @type size: float
2364
  @ivar size: size of the PV in MiB
2365
  @type free: float
2366
  @ivar free: free space in the PV, in MiB
2367
  @type attributes: string
2368
  @ivar attributes: PV attributes
2369
  @type lv_list: list of strings
2370
  @ivar lv_list: names of the LVs hosted on the PV
2371
  """
2372
  __slots__ = [
2373
    "name",
2374
    "vg_name",
2375
    "size",
2376
    "free",
2377
    "attributes",
2378
    "lv_list"
2379
    ]
2380

    
2381
  def IsEmpty(self):
2382
    """Is this PV empty?
2383

2384
    """
2385
    return self.size <= (self.free + 1)
2386

    
2387
  def IsAllocatable(self):
2388
    """Is this PV allocatable?
2389

2390
    """
2391
    return ("a" in self.attributes)