Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 93f1e606

History | View | Annotate | Download (70.3 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
    all_nodes.add(self.primary_node)
1121
    for device in self.disks:
1122
      _Helper(all_nodes, device)
1123
    return tuple(all_nodes)
1124

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

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

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

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

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

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

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

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

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

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

    
1177
    return ret
1178

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1262

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

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

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

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

    
1287
  VARIANT_DELIM = "+"
1288

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

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

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

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

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

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

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

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

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

    
1322

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

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

    
1340

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

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

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

    
1363

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

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

    
1374

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

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

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

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

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

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

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

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

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

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

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

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

    
1443
    return data
1444

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

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

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

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

    
1461
    return obj
1462

    
1463

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1549

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1763
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1764

    
1765
    return mydict
1766

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

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

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

    
1779
    return obj
1780

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

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

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

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

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

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

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

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

    
1811
    return ret_dict
1812

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1948
      return params_public
1949

    
1950
    else:
1951

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2052

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

    
2065

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

    
2080

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

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

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

    
2101

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

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

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

    
2118

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

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

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

    
2135

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

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

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

    
2152

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

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

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

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

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

    
2176

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

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

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

    
2188

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

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

    
2198

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

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

2204
  """
2205
  __slots__ = []
2206

    
2207

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

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

    
2218

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

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

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

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

    
2257

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

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

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

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

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

    
2297
    return result
2298

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

2303
    Remove deprecated network_type and family.
2304

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

    
2313

    
2314
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2315
  """Simple wrapper over ConfigParse that allows serialization.
2316

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

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

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

    
2336

    
2337
class LvmPvInfo(ConfigObject):
2338
  """Information about an LVM physical volume (PV).
2339

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

    
2362
  def IsEmpty(self):
2363
    """Is this PV empty?
2364

2365
    """
2366
    return self.size <= (self.free + 1)
2367

    
2368
  def IsAllocatable(self):
2369
    """Is this PV allocatable?
2370

2371
    """
2372
    return ("a" in self.attributes)