Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 4e7f986e

History | View | Annotate | Download (69.8 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Transportable objects for Ganeti.
23

24
This module provides small, mostly data-only objects which are safe to
25
pass to and from external parties.
26

27
"""
28

    
29
# pylint: disable=E0203,W0201,R0902
30

    
31
# E0203: Access to member %r before its definition, since we use
32
# objects.py which doesn't explicitly initialise its members
33

    
34
# W0201: Attribute '%s' defined outside __init__
35

    
36
# R0902: Allow instances of these objects to have more than 20 attributes
37

    
38
import ConfigParser
39
import re
40
import copy
41
import logging
42
import time
43
from cStringIO import StringIO
44

    
45
from ganeti import errors
46
from ganeti import constants
47
from ganeti import netutils
48
from ganeti import outils
49
from ganeti import utils
50
from ganeti import serializer
51

    
52
from socket import AF_INET
53

    
54

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

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

    
61

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

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

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

    
83

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

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

    
97

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

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

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

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

    
110

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

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

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

    
127

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

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

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

    
141

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

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

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

    
156
  return result
157

    
158

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

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

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

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

    
177

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

181
  """
182
  return {}
183

    
184

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

188
  It has the following properties:
189

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

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

197
  """
198
  __slots__ = []
199

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

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

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

215
    """
216

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

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

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

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

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

    
243
  __getstate__ = ToDict
244

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

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

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

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

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

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

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

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

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

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

287
    """
288
    pass
289

    
290

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

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

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

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

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

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

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

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

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

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

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

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

349
    This replaces the tags set with a list.
350

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

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

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

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

    
369

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

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

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

    
388

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

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

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

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

    
414
    return mydict
415

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

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

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

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

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

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

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

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

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

    
497

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

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

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

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

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

    
521

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

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

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

    
544
    return tuple(set(nodes))
545

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

671
    This only works for VG-based disks.
672

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
779
    self.dynamic_params = dyn_disk_params
780

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
871
    # add here config upgrade for this disk
872

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

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

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

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

    
896
    assert disk_template in disk_params
897

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

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

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

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

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

    
935
    return result
936

    
937

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1089

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

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

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

1117
    @type lvmap: dict
1118
    @param lvmap: optional dictionary to receive the
1119
        'node' : ['lv', ...] data.
1120
    @type devs: list of L{Disk}
1121
    @param devs: disks to get the LV name for. If None, all disk of this
1122
        instance are used.
1123
    @type node_uuid: string
1124
    @param node_uuid: UUID of the node to get the LV names for. If None, the
1125
        primary node of this instance is used.
1126
    @return: None if lvmap arg is given, otherwise, a dictionary of
1127
        the form { 'node_uuid' : ['volume1', 'volume2', ...], ... };
1128
        volumeN is of the form "vg_name/lv_name", compatible with
1129
        GetVolumeList()
1130

1131
    """
1132
    if node_uuid is None:
1133
      node_uuid = self.primary_node
1134

    
1135
    if lvmap is None:
1136
      lvmap = {
1137
        node_uuid: [],
1138
        }
1139
      ret = lvmap
1140
    else:
1141
      if not node_uuid in lvmap:
1142
        lvmap[node_uuid] = []
1143
      ret = None
1144

    
1145
    if not devs:
1146
      devs = self.disks
1147

    
1148
    for dev in devs:
1149
      if dev.dev_type == constants.DT_PLAIN:
1150
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1151

    
1152
      elif dev.dev_type in constants.DTS_DRBD:
1153
        if dev.children:
1154
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1155
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1156

    
1157
      elif dev.children:
1158
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1159

    
1160
    return ret
1161

    
1162
  def FindDisk(self, idx):
1163
    """Find a disk given having a specified index.
1164

1165
    This is just a wrapper that does validation of the index.
1166

1167
    @type idx: int
1168
    @param idx: the disk index
1169
    @rtype: L{Disk}
1170
    @return: the corresponding disk
1171
    @raise errors.OpPrereqError: when the given index is not valid
1172

1173
    """
1174
    try:
1175
      idx = int(idx)
1176
      return self.disks[idx]
1177
    except (TypeError, ValueError), err:
1178
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1179
                                 errors.ECODE_INVAL)
1180
    except IndexError:
1181
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1182
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1183
                                 errors.ECODE_INVAL)
1184

    
1185
  def ToDict(self, _with_private=False):
1186
    """Instance-specific conversion to standard python types.
1187

1188
    This replaces the children lists of objects with lists of standard
1189
    python types.
1190

1191
    """
1192
    bo = super(Instance, self).ToDict(_with_private=_with_private)
1193

    
1194
    if _with_private:
1195
      bo["osparams_private"] = self.osparams_private.Unprivate()
1196

    
1197
    for attr in "nics", "disks":
1198
      alist = bo.get(attr, None)
1199
      if alist:
1200
        nlist = outils.ContainerToDicts(alist)
1201
      else:
1202
        nlist = []
1203
      bo[attr] = nlist
1204
    return bo
1205

    
1206
  @classmethod
1207
  def FromDict(cls, val):
1208
    """Custom function for instances.
1209

1210
    """
1211
    if "admin_state" not in val:
1212
      if val.get("admin_up", False):
1213
        val["admin_state"] = constants.ADMINST_UP
1214
      else:
1215
        val["admin_state"] = constants.ADMINST_DOWN
1216
    if "admin_up" in val:
1217
      del val["admin_up"]
1218
    obj = super(Instance, cls).FromDict(val)
1219
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1220
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1221
    return obj
1222

    
1223
  def UpgradeConfig(self):
1224
    """Fill defaults for missing configuration values.
1225

1226
    """
1227
    for nic in self.nics:
1228
      nic.UpgradeConfig()
1229
    for disk in self.disks:
1230
      disk.UpgradeConfig()
1231
    if self.hvparams:
1232
      for key in constants.HVC_GLOBALS:
1233
        try:
1234
          del self.hvparams[key]
1235
        except KeyError:
1236
          pass
1237
    if self.osparams is None:
1238
      self.osparams = {}
1239
    if self.osparams_private is None:
1240
      self.osparams_private = serializer.PrivateDict()
1241
    UpgradeBeParams(self.beparams)
1242
    if self.disks_active is None:
1243
      self.disks_active = self.admin_state == constants.ADMINST_UP
1244

    
1245

    
1246
class OS(ConfigObject):
1247
  """Config object representing an operating system.
1248

1249
  @type supported_parameters: list
1250
  @ivar supported_parameters: a list of tuples, name and description,
1251
      containing the supported parameters by this OS
1252

1253
  @type VARIANT_DELIM: string
1254
  @cvar VARIANT_DELIM: the variant delimiter
1255

1256
  """
1257
  __slots__ = [
1258
    "name",
1259
    "path",
1260
    "api_versions",
1261
    "create_script",
1262
    "export_script",
1263
    "import_script",
1264
    "rename_script",
1265
    "verify_script",
1266
    "supported_variants",
1267
    "supported_parameters",
1268
    ]
1269

    
1270
  VARIANT_DELIM = "+"
1271

    
1272
  @classmethod
1273
  def SplitNameVariant(cls, name):
1274
    """Splits the name into the proper name and variant.
1275

1276
    @param name: the OS (unprocessed) name
1277
    @rtype: list
1278
    @return: a list of two elements; if the original name didn't
1279
        contain a variant, it's returned as an empty string
1280

1281
    """
1282
    nv = name.split(cls.VARIANT_DELIM, 1)
1283
    if len(nv) == 1:
1284
      nv.append("")
1285
    return nv
1286

    
1287
  @classmethod
1288
  def GetName(cls, name):
1289
    """Returns the proper name of the os (without the variant).
1290

1291
    @param name: the OS (unprocessed) name
1292

1293
    """
1294
    return cls.SplitNameVariant(name)[0]
1295

    
1296
  @classmethod
1297
  def GetVariant(cls, name):
1298
    """Returns the variant the os (without the base name).
1299

1300
    @param name: the OS (unprocessed) name
1301

1302
    """
1303
    return cls.SplitNameVariant(name)[1]
1304

    
1305

    
1306
class ExtStorage(ConfigObject):
1307
  """Config object representing an External Storage Provider.
1308

1309
  """
1310
  __slots__ = [
1311
    "name",
1312
    "path",
1313
    "create_script",
1314
    "remove_script",
1315
    "grow_script",
1316
    "attach_script",
1317
    "detach_script",
1318
    "setinfo_script",
1319
    "verify_script",
1320
    "supported_parameters",
1321
    ]
1322

    
1323

    
1324
class NodeHvState(ConfigObject):
1325
  """Hypvervisor state on a node.
1326

1327
  @ivar mem_total: Total amount of memory
1328
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1329
    available)
1330
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1331
    rounding
1332
  @ivar mem_inst: Memory used by instances living on node
1333
  @ivar cpu_total: Total node CPU core count
1334
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1335

1336
  """
1337
  __slots__ = [
1338
    "mem_total",
1339
    "mem_node",
1340
    "mem_hv",
1341
    "mem_inst",
1342
    "cpu_total",
1343
    "cpu_node",
1344
    ] + _TIMESTAMPS
1345

    
1346

    
1347
class NodeDiskState(ConfigObject):
1348
  """Disk state on a node.
1349

1350
  """
1351
  __slots__ = [
1352
    "total",
1353
    "reserved",
1354
    "overhead",
1355
    ] + _TIMESTAMPS
1356

    
1357

    
1358
class Node(TaggableObject):
1359
  """Config object representing a node.
1360

1361
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1362
  @ivar hv_state_static: Hypervisor state overriden by user
1363
  @ivar disk_state: Disk state (e.g. free space)
1364
  @ivar disk_state_static: Disk state overriden by user
1365

1366
  """
1367
  __slots__ = [
1368
    "name",
1369
    "primary_ip",
1370
    "secondary_ip",
1371
    "serial_no",
1372
    "master_candidate",
1373
    "offline",
1374
    "drained",
1375
    "group",
1376
    "master_capable",
1377
    "vm_capable",
1378
    "ndparams",
1379
    "powered",
1380
    "hv_state",
1381
    "hv_state_static",
1382
    "disk_state",
1383
    "disk_state_static",
1384
    ] + _TIMESTAMPS + _UUID
1385

    
1386
  def UpgradeConfig(self):
1387
    """Fill defaults for missing configuration values.
1388

1389
    """
1390
    # pylint: disable=E0203
1391
    # because these are "defined" via slots, not manually
1392
    if self.master_capable is None:
1393
      self.master_capable = True
1394

    
1395
    if self.vm_capable is None:
1396
      self.vm_capable = True
1397

    
1398
    if self.ndparams is None:
1399
      self.ndparams = {}
1400
    # And remove any global parameter
1401
    for key in constants.NDC_GLOBALS:
1402
      if key in self.ndparams:
1403
        logging.warning("Ignoring %s node parameter for node %s",
1404
                        key, self.name)
1405
        del self.ndparams[key]
1406

    
1407
    if self.powered is None:
1408
      self.powered = True
1409

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

1413
    """
1414
    data = super(Node, self).ToDict(_with_private=_with_private)
1415

    
1416
    hv_state = data.get("hv_state", None)
1417
    if hv_state is not None:
1418
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1419

    
1420
    disk_state = data.get("disk_state", None)
1421
    if disk_state is not None:
1422
      data["disk_state"] = \
1423
        dict((key, outils.ContainerToDicts(value))
1424
             for (key, value) in disk_state.items())
1425

    
1426
    return data
1427

    
1428
  @classmethod
1429
  def FromDict(cls, val):
1430
    """Custom function for deserializing.
1431

1432
    """
1433
    obj = super(Node, cls).FromDict(val)
1434

    
1435
    if obj.hv_state is not None:
1436
      obj.hv_state = \
1437
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1438

    
1439
    if obj.disk_state is not None:
1440
      obj.disk_state = \
1441
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1442
             for (key, value) in obj.disk_state.items())
1443

    
1444
    return obj
1445

    
1446

    
1447
class NodeGroup(TaggableObject):
1448
  """Config object representing a node group."""
1449
  __slots__ = [
1450
    "name",
1451
    "members",
1452
    "ndparams",
1453
    "diskparams",
1454
    "ipolicy",
1455
    "serial_no",
1456
    "hv_state_static",
1457
    "disk_state_static",
1458
    "alloc_policy",
1459
    "networks",
1460
    ] + _TIMESTAMPS + _UUID
1461

    
1462
  def ToDict(self, _with_private=False):
1463
    """Custom function for nodegroup.
1464

1465
    This discards the members object, which gets recalculated and is only kept
1466
    in memory.
1467

1468
    """
1469
    mydict = super(NodeGroup, self).ToDict(_with_private=_with_private)
1470
    del mydict["members"]
1471
    return mydict
1472

    
1473
  @classmethod
1474
  def FromDict(cls, val):
1475
    """Custom function for nodegroup.
1476

1477
    The members slot is initialized to an empty list, upon deserialization.
1478

1479
    """
1480
    obj = super(NodeGroup, cls).FromDict(val)
1481
    obj.members = []
1482
    return obj
1483

    
1484
  def UpgradeConfig(self):
1485
    """Fill defaults for missing configuration values.
1486

1487
    """
1488
    if self.ndparams is None:
1489
      self.ndparams = {}
1490

    
1491
    if self.serial_no is None:
1492
      self.serial_no = 1
1493

    
1494
    if self.alloc_policy is None:
1495
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1496

    
1497
    # We only update mtime, and not ctime, since we would not be able
1498
    # to provide a correct value for creation time.
1499
    if self.mtime is None:
1500
      self.mtime = time.time()
1501

    
1502
    if self.diskparams is None:
1503
      self.diskparams = {}
1504
    if self.ipolicy is None:
1505
      self.ipolicy = MakeEmptyIPolicy()
1506

    
1507
    if self.networks is None:
1508
      self.networks = {}
1509

    
1510
  def FillND(self, node):
1511
    """Return filled out ndparams for L{objects.Node}
1512

1513
    @type node: L{objects.Node}
1514
    @param node: A Node object to fill
1515
    @return a copy of the node's ndparams with defaults filled
1516

1517
    """
1518
    return self.SimpleFillND(node.ndparams)
1519

    
1520
  def SimpleFillND(self, ndparams):
1521
    """Fill a given ndparams dict with defaults.
1522

1523
    @type ndparams: dict
1524
    @param ndparams: the dict to fill
1525
    @rtype: dict
1526
    @return: a copy of the passed in ndparams with missing keys filled
1527
        from the node group defaults
1528

1529
    """
1530
    return FillDict(self.ndparams, ndparams)
1531

    
1532

    
1533
class Cluster(TaggableObject):
1534
  """Config object representing the cluster."""
1535
  __slots__ = [
1536
    "serial_no",
1537
    "rsahostkeypub",
1538
    "dsahostkeypub",
1539
    "highest_used_port",
1540
    "tcpudp_port_pool",
1541
    "mac_prefix",
1542
    "volume_group_name",
1543
    "reserved_lvs",
1544
    "drbd_usermode_helper",
1545
    "default_bridge",
1546
    "default_hypervisor",
1547
    "master_node",
1548
    "master_ip",
1549
    "master_netdev",
1550
    "master_netmask",
1551
    "use_external_mip_script",
1552
    "cluster_name",
1553
    "file_storage_dir",
1554
    "shared_file_storage_dir",
1555
    "gluster_storage_dir",
1556
    "enabled_hypervisors",
1557
    "hvparams",
1558
    "ipolicy",
1559
    "os_hvp",
1560
    "beparams",
1561
    "osparams",
1562
    "osparams_private_cluster",
1563
    "nicparams",
1564
    "ndparams",
1565
    "diskparams",
1566
    "candidate_pool_size",
1567
    "modify_etc_hosts",
1568
    "modify_ssh_setup",
1569
    "maintain_node_health",
1570
    "uid_pool",
1571
    "default_iallocator",
1572
    "default_iallocator_params",
1573
    "hidden_os",
1574
    "blacklisted_os",
1575
    "primary_ip_family",
1576
    "prealloc_wipe_disks",
1577
    "hv_state_static",
1578
    "disk_state_static",
1579
    "enabled_disk_templates",
1580
    "candidate_certs",
1581
    "max_running_jobs",
1582
    "instance_communication_network",
1583
    ] + _TIMESTAMPS + _UUID
1584

    
1585
  def UpgradeConfig(self):
1586
    """Fill defaults for missing configuration values.
1587

1588
    """
1589
    # pylint: disable=E0203
1590
    # because these are "defined" via slots, not manually
1591
    if self.hvparams is None:
1592
      self.hvparams = constants.HVC_DEFAULTS
1593
    else:
1594
      for hypervisor in constants.HYPER_TYPES:
1595
        try:
1596
          existing_params = self.hvparams[hypervisor]
1597
        except KeyError:
1598
          existing_params = {}
1599
        self.hvparams[hypervisor] = FillDict(
1600
            constants.HVC_DEFAULTS[hypervisor], existing_params)
1601

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

    
1605
    if self.osparams is None:
1606
      self.osparams = {}
1607
    # osparams_private_cluster added in 2.12
1608
    if self.osparams_private_cluster is None:
1609
      self.osparams_private_cluster = {}
1610

    
1611
    self.ndparams = UpgradeNDParams(self.ndparams)
1612

    
1613
    self.beparams = UpgradeGroupedParams(self.beparams,
1614
                                         constants.BEC_DEFAULTS)
1615
    for beparams_group in self.beparams:
1616
      UpgradeBeParams(self.beparams[beparams_group])
1617

    
1618
    migrate_default_bridge = not self.nicparams
1619
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1620
                                          constants.NICC_DEFAULTS)
1621
    if migrate_default_bridge:
1622
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1623
        self.default_bridge
1624

    
1625
    if self.modify_etc_hosts is None:
1626
      self.modify_etc_hosts = True
1627

    
1628
    if self.modify_ssh_setup is None:
1629
      self.modify_ssh_setup = True
1630

    
1631
    # default_bridge is no longer used in 2.1. The slot is left there to
1632
    # support auto-upgrading. It can be removed once we decide to deprecate
1633
    # upgrading straight from 2.0.
1634
    if self.default_bridge is not None:
1635
      self.default_bridge = None
1636

    
1637
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1638
    # code can be removed once upgrading straight from 2.0 is deprecated.
1639
    if self.default_hypervisor is not None:
1640
      self.enabled_hypervisors = ([self.default_hypervisor] +
1641
                                  [hvname for hvname in self.enabled_hypervisors
1642
                                   if hvname != self.default_hypervisor])
1643
      self.default_hypervisor = None
1644

    
1645
    # maintain_node_health added after 2.1.1
1646
    if self.maintain_node_health is None:
1647
      self.maintain_node_health = False
1648

    
1649
    if self.uid_pool is None:
1650
      self.uid_pool = []
1651

    
1652
    if self.default_iallocator is None:
1653
      self.default_iallocator = ""
1654

    
1655
    if self.default_iallocator_params is None:
1656
      self.default_iallocator_params = {}
1657

    
1658
    # reserved_lvs added before 2.2
1659
    if self.reserved_lvs is None:
1660
      self.reserved_lvs = []
1661

    
1662
    # hidden and blacklisted operating systems added before 2.2.1
1663
    if self.hidden_os is None:
1664
      self.hidden_os = []
1665

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

    
1669
    # primary_ip_family added before 2.3
1670
    if self.primary_ip_family is None:
1671
      self.primary_ip_family = AF_INET
1672

    
1673
    if self.master_netmask is None:
1674
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1675
      self.master_netmask = ipcls.iplen
1676

    
1677
    if self.prealloc_wipe_disks is None:
1678
      self.prealloc_wipe_disks = False
1679

    
1680
    # shared_file_storage_dir added before 2.5
1681
    if self.shared_file_storage_dir is None:
1682
      self.shared_file_storage_dir = ""
1683

    
1684
    # gluster_storage_dir added in 2.11
1685
    if self.gluster_storage_dir is None:
1686
      self.gluster_storage_dir = ""
1687

    
1688
    if self.use_external_mip_script is None:
1689
      self.use_external_mip_script = False
1690

    
1691
    if self.diskparams:
1692
      self.diskparams = UpgradeDiskParams(self.diskparams)
1693
    else:
1694
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1695

    
1696
    # instance policy added before 2.6
1697
    if self.ipolicy is None:
1698
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1699
    else:
1700
      # we can either make sure to upgrade the ipolicy always, or only
1701
      # do it in some corner cases (e.g. missing keys); note that this
1702
      # will break any removal of keys from the ipolicy dict
1703
      wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1704
      if wrongkeys:
1705
        # These keys would be silently removed by FillIPolicy()
1706
        msg = ("Cluster instance policy contains spurious keys: %s" %
1707
               utils.CommaJoin(wrongkeys))
1708
        raise errors.ConfigurationError(msg)
1709
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1710

    
1711
    if self.candidate_certs is None:
1712
      self.candidate_certs = {}
1713

    
1714
    if self.max_running_jobs is None:
1715
      self.max_running_jobs = constants.LUXID_MAXIMAL_RUNNING_JOBS_DEFAULT
1716

    
1717
    if self.instance_communication_network is None:
1718
      self.instance_communication_network = ""
1719

    
1720
  @property
1721
  def primary_hypervisor(self):
1722
    """The first hypervisor is the primary.
1723

1724
    Useful, for example, for L{Node}'s hv/disk state.
1725

1726
    """
1727
    return self.enabled_hypervisors[0]
1728

    
1729
  def ToDict(self, _with_private=False):
1730
    """Custom function for cluster.
1731

1732
    """
1733
    mydict = super(Cluster, self).ToDict(_with_private=_with_private)
1734

    
1735
    # Explicitly save private parameters.
1736
    if _with_private:
1737
      for os in mydict["osparams_private_cluster"]:
1738
        mydict["osparams_private_cluster"][os] = \
1739
          self.osparams_private_cluster[os].Unprivate()
1740

    
1741
    if self.tcpudp_port_pool is None:
1742
      tcpudp_port_pool = []
1743
    else:
1744
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1745

    
1746
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1747

    
1748
    return mydict
1749

    
1750
  @classmethod
1751
  def FromDict(cls, val):
1752
    """Custom function for cluster.
1753

1754
    """
1755
    obj = super(Cluster, cls).FromDict(val)
1756

    
1757
    if obj.tcpudp_port_pool is None:
1758
      obj.tcpudp_port_pool = set()
1759
    elif not isinstance(obj.tcpudp_port_pool, set):
1760
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1761

    
1762
    return obj
1763

    
1764
  def SimpleFillDP(self, diskparams):
1765
    """Fill a given diskparams dict with cluster defaults.
1766

1767
    @param diskparams: The diskparams
1768
    @return: The defaults dict
1769

1770
    """
1771
    return FillDiskParams(self.diskparams, diskparams)
1772

    
1773
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1774
    """Get the default hypervisor parameters for the cluster.
1775

1776
    @param hypervisor: the hypervisor name
1777
    @param os_name: if specified, we'll also update the defaults for this OS
1778
    @param skip_keys: if passed, list of keys not to use
1779
    @return: the defaults dict
1780

1781
    """
1782
    if skip_keys is None:
1783
      skip_keys = []
1784

    
1785
    fill_stack = [self.hvparams.get(hypervisor, {})]
1786
    if os_name is not None:
1787
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1788
      fill_stack.append(os_hvp)
1789

    
1790
    ret_dict = {}
1791
    for o_dict in fill_stack:
1792
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1793

    
1794
    return ret_dict
1795

    
1796
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1797
    """Fill a given hvparams dict with cluster defaults.
1798

1799
    @type hv_name: string
1800
    @param hv_name: the hypervisor to use
1801
    @type os_name: string
1802
    @param os_name: the OS to use for overriding the hypervisor defaults
1803
    @type skip_globals: boolean
1804
    @param skip_globals: if True, the global hypervisor parameters will
1805
        not be filled
1806
    @rtype: dict
1807
    @return: a copy of the given hvparams with missing keys filled from
1808
        the cluster defaults
1809

1810
    """
1811
    if skip_globals:
1812
      skip_keys = constants.HVC_GLOBALS
1813
    else:
1814
      skip_keys = []
1815

    
1816
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1817
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1818

    
1819
  def FillHV(self, instance, skip_globals=False):
1820
    """Fill an instance's hvparams dict with cluster defaults.
1821

1822
    @type instance: L{objects.Instance}
1823
    @param instance: the instance parameter to fill
1824
    @type skip_globals: boolean
1825
    @param skip_globals: if True, the global hypervisor parameters will
1826
        not be filled
1827
    @rtype: dict
1828
    @return: a copy of the instance's hvparams with missing keys filled from
1829
        the cluster defaults
1830

1831
    """
1832
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1833
                             instance.hvparams, skip_globals)
1834

    
1835
  def SimpleFillBE(self, beparams):
1836
    """Fill a given beparams dict with cluster defaults.
1837

1838
    @type beparams: dict
1839
    @param beparams: the dict to fill
1840
    @rtype: dict
1841
    @return: a copy of the passed in beparams with missing keys filled
1842
        from the cluster defaults
1843

1844
    """
1845
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1846

    
1847
  def FillBE(self, instance):
1848
    """Fill an instance's beparams dict with cluster defaults.
1849

1850
    @type instance: L{objects.Instance}
1851
    @param instance: the instance parameter to fill
1852
    @rtype: dict
1853
    @return: a copy of the instance's beparams with missing keys filled from
1854
        the cluster defaults
1855

1856
    """
1857
    return self.SimpleFillBE(instance.beparams)
1858

    
1859
  def SimpleFillNIC(self, nicparams):
1860
    """Fill a given nicparams dict with cluster defaults.
1861

1862
    @type nicparams: dict
1863
    @param nicparams: the dict to fill
1864
    @rtype: dict
1865
    @return: a copy of the passed in nicparams with missing keys filled
1866
        from the cluster defaults
1867

1868
    """
1869
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1870

    
1871
  def SimpleFillOS(self, os_name,
1872
                    os_params_public,
1873
                    os_params_private=None,
1874
                    os_params_secret=None):
1875
    """Fill an instance's osparams dict with cluster defaults.
1876

1877
    @type os_name: string
1878
    @param os_name: the OS name to use
1879
    @type os_params_public: dict
1880
    @param os_params_public: the dict to fill with default values
1881
    @type os_params_private: dict
1882
    @param os_params_private: the dict with private fields to fill
1883
                              with default values. Not passing this field
1884
                              results in no private fields being added to the
1885
                              return value. Private fields will be wrapped in
1886
                              L{Private} objects.
1887
    @type os_params_secret: dict
1888
    @param os_params_secret: the dict with secret fields to fill
1889
                             with default values. Not passing this field
1890
                             results in no secret fields being added to the
1891
                             return value. Private fields will be wrapped in
1892
                             L{Private} objects.
1893
    @rtype: dict
1894
    @return: a copy of the instance's osparams with missing keys filled from
1895
        the cluster defaults. Private and secret parameters are not included
1896
        unless the respective optional parameters are supplied.
1897

1898
    """
1899
    name_only = os_name.split("+", 1)[0]
1900

    
1901
    defaults_base_public = self.osparams.get(name_only, {})
1902
    defaults_public = FillDict(defaults_base_public,
1903
                               self.osparams.get(os_name, {}))
1904
    params_public = FillDict(defaults_public, os_params_public)
1905

    
1906
    if os_params_private is not None:
1907
      defaults_base_private = self.osparams_private_cluster.get(name_only, {})
1908
      defaults_private = FillDict(defaults_base_private,
1909
                                  self.osparams_private_cluster.get(os_name,
1910
                                                                    {}))
1911
      params_private = FillDict(defaults_private, os_params_private)
1912
    else:
1913
      params_private = {}
1914

    
1915
    if os_params_secret is not None:
1916
      # There can't be default secret settings, so there's nothing to be done.
1917
      params_secret = os_params_secret
1918
    else:
1919
      params_secret = {}
1920

    
1921
    # Enforce that the set of keys be distinct:
1922
    duplicate_keys = utils.GetRepeatedKeys(params_public,
1923
                                           params_private,
1924
                                           params_secret)
1925
    if not duplicate_keys:
1926

    
1927
      # Actually update them:
1928
      params_public.update(params_private)
1929
      params_public.update(params_secret)
1930

    
1931
      return params_public
1932

    
1933
    else:
1934

    
1935
      def formatter(keys):
1936
        return utils.CommaJoin(sorted(map(repr, keys))) if keys else "(none)"
1937

    
1938
      #Lose the values.
1939
      params_public = set(params_public)
1940
      params_private = set(params_private)
1941
      params_secret = set(params_secret)
1942

    
1943
      msg = """Cannot assign multiple values to OS parameters.
1944

1945
      Conflicting OS parameters that would have been set by this operation:
1946
      - at public visibility:  {public}
1947
      - at private visibility: {private}
1948
      - at secret visibility:  {secret}
1949
      """.format(dupes=formatter(duplicate_keys),
1950
                 public=formatter(params_public & duplicate_keys),
1951
                 private=formatter(params_private & duplicate_keys),
1952
                 secret=formatter(params_secret & duplicate_keys))
1953
      raise errors.OpPrereqError(msg)
1954

    
1955
  @staticmethod
1956
  def SimpleFillHvState(hv_state):
1957
    """Fill an hv_state sub dict with cluster defaults.
1958

1959
    """
1960
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1961

    
1962
  @staticmethod
1963
  def SimpleFillDiskState(disk_state):
1964
    """Fill an disk_state sub dict with cluster defaults.
1965

1966
    """
1967
    return FillDict(constants.DS_DEFAULTS, disk_state)
1968

    
1969
  def FillND(self, node, nodegroup):
1970
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1971

1972
    @type node: L{objects.Node}
1973
    @param node: A Node object to fill
1974
    @type nodegroup: L{objects.NodeGroup}
1975
    @param nodegroup: A Node object to fill
1976
    @return a copy of the node's ndparams with defaults filled
1977

1978
    """
1979
    return self.SimpleFillND(nodegroup.FillND(node))
1980

    
1981
  def FillNDGroup(self, nodegroup):
1982
    """Return filled out ndparams for just L{objects.NodeGroup}
1983

1984
    @type nodegroup: L{objects.NodeGroup}
1985
    @param nodegroup: A Node object to fill
1986
    @return a copy of the node group's ndparams with defaults filled
1987

1988
    """
1989
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
1990

    
1991
  def SimpleFillND(self, ndparams):
1992
    """Fill a given ndparams dict with defaults.
1993

1994
    @type ndparams: dict
1995
    @param ndparams: the dict to fill
1996
    @rtype: dict
1997
    @return: a copy of the passed in ndparams with missing keys filled
1998
        from the cluster defaults
1999

2000
    """
2001
    return FillDict(self.ndparams, ndparams)
2002

    
2003
  def SimpleFillIPolicy(self, ipolicy):
2004
    """ Fill instance policy dict with defaults.
2005

2006
    @type ipolicy: dict
2007
    @param ipolicy: the dict to fill
2008
    @rtype: dict
2009
    @return: a copy of passed ipolicy with missing keys filled from
2010
      the cluster defaults
2011

2012
    """
2013
    return FillIPolicy(self.ipolicy, ipolicy)
2014

    
2015
  def IsDiskTemplateEnabled(self, disk_template):
2016
    """Checks if a particular disk template is enabled.
2017

2018
    """
2019
    return utils.storage.IsDiskTemplateEnabled(
2020
        disk_template, self.enabled_disk_templates)
2021

    
2022
  def IsFileStorageEnabled(self):
2023
    """Checks if file storage is enabled.
2024

2025
    """
2026
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
2027

    
2028
  def IsSharedFileStorageEnabled(self):
2029
    """Checks if shared file storage is enabled.
2030

2031
    """
2032
    return utils.storage.IsSharedFileStorageEnabled(
2033
        self.enabled_disk_templates)
2034

    
2035

    
2036
class BlockDevStatus(ConfigObject):
2037
  """Config object representing the status of a block device."""
2038
  __slots__ = [
2039
    "dev_path",
2040
    "major",
2041
    "minor",
2042
    "sync_percent",
2043
    "estimated_time",
2044
    "is_degraded",
2045
    "ldisk_status",
2046
    ]
2047

    
2048

    
2049
class ImportExportStatus(ConfigObject):
2050
  """Config object representing the status of an import or export."""
2051
  __slots__ = [
2052
    "recent_output",
2053
    "listen_port",
2054
    "connected",
2055
    "progress_mbytes",
2056
    "progress_throughput",
2057
    "progress_eta",
2058
    "progress_percent",
2059
    "exit_status",
2060
    "error_message",
2061
    ] + _TIMESTAMPS
2062

    
2063

    
2064
class ImportExportOptions(ConfigObject):
2065
  """Options for import/export daemon
2066

2067
  @ivar key_name: X509 key name (None for cluster certificate)
2068
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
2069
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
2070
  @ivar magic: Used to ensure the connection goes to the right disk
2071
  @ivar ipv6: Whether to use IPv6
2072
  @ivar connect_timeout: Number of seconds for establishing connection
2073

2074
  """
2075
  __slots__ = [
2076
    "key_name",
2077
    "ca_pem",
2078
    "compress",
2079
    "magic",
2080
    "ipv6",
2081
    "connect_timeout",
2082
    ]
2083

    
2084

    
2085
class ConfdRequest(ConfigObject):
2086
  """Object holding a confd request.
2087

2088
  @ivar protocol: confd protocol version
2089
  @ivar type: confd query type
2090
  @ivar query: query request
2091
  @ivar rsalt: requested reply salt
2092

2093
  """
2094
  __slots__ = [
2095
    "protocol",
2096
    "type",
2097
    "query",
2098
    "rsalt",
2099
    ]
2100

    
2101

    
2102
class ConfdReply(ConfigObject):
2103
  """Object holding a confd reply.
2104

2105
  @ivar protocol: confd protocol version
2106
  @ivar status: reply status code (ok, error)
2107
  @ivar answer: confd query reply
2108
  @ivar serial: configuration serial number
2109

2110
  """
2111
  __slots__ = [
2112
    "protocol",
2113
    "status",
2114
    "answer",
2115
    "serial",
2116
    ]
2117

    
2118

    
2119
class QueryFieldDefinition(ConfigObject):
2120
  """Object holding a query field definition.
2121

2122
  @ivar name: Field name
2123
  @ivar title: Human-readable title
2124
  @ivar kind: Field type
2125
  @ivar doc: Human-readable description
2126

2127
  """
2128
  __slots__ = [
2129
    "name",
2130
    "title",
2131
    "kind",
2132
    "doc",
2133
    ]
2134

    
2135

    
2136
class _QueryResponseBase(ConfigObject):
2137
  __slots__ = [
2138
    "fields",
2139
    ]
2140

    
2141
  def ToDict(self, _with_private=False):
2142
    """Custom function for serializing.
2143

2144
    """
2145
    mydict = super(_QueryResponseBase, self).ToDict()
2146
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2147
    return mydict
2148

    
2149
  @classmethod
2150
  def FromDict(cls, val):
2151
    """Custom function for de-serializing.
2152

2153
    """
2154
    obj = super(_QueryResponseBase, cls).FromDict(val)
2155
    obj.fields = \
2156
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2157
    return obj
2158

    
2159

    
2160
class QueryResponse(_QueryResponseBase):
2161
  """Object holding the response to a query.
2162

2163
  @ivar fields: List of L{QueryFieldDefinition} objects
2164
  @ivar data: Requested data
2165

2166
  """
2167
  __slots__ = [
2168
    "data",
2169
    ]
2170

    
2171

    
2172
class QueryFieldsRequest(ConfigObject):
2173
  """Object holding a request for querying available fields.
2174

2175
  """
2176
  __slots__ = [
2177
    "what",
2178
    "fields",
2179
    ]
2180

    
2181

    
2182
class QueryFieldsResponse(_QueryResponseBase):
2183
  """Object holding the response to a query for fields.
2184

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

2187
  """
2188
  __slots__ = []
2189

    
2190

    
2191
class MigrationStatus(ConfigObject):
2192
  """Object holding the status of a migration.
2193

2194
  """
2195
  __slots__ = [
2196
    "status",
2197
    "transferred_ram",
2198
    "total_ram",
2199
    ]
2200

    
2201

    
2202
class InstanceConsole(ConfigObject):
2203
  """Object describing how to access the console of an instance.
2204

2205
  """
2206
  __slots__ = [
2207
    "instance",
2208
    "kind",
2209
    "message",
2210
    "host",
2211
    "port",
2212
    "user",
2213
    "command",
2214
    "display",
2215
    ]
2216

    
2217
  def Validate(self):
2218
    """Validates contents of this object.
2219

2220
    """
2221
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2222
    assert self.instance, "Missing instance name"
2223
    assert self.message or self.kind in [constants.CONS_SSH,
2224
                                         constants.CONS_SPICE,
2225
                                         constants.CONS_VNC]
2226
    assert self.host or self.kind == constants.CONS_MESSAGE
2227
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2228
                                      constants.CONS_SSH]
2229
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2230
                                      constants.CONS_SPICE,
2231
                                      constants.CONS_VNC]
2232
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2233
                                         constants.CONS_SPICE,
2234
                                         constants.CONS_VNC]
2235
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2236
                                         constants.CONS_SPICE,
2237
                                         constants.CONS_SSH]
2238
    return True
2239

    
2240

    
2241
class Network(TaggableObject):
2242
  """Object representing a network definition for ganeti.
2243

2244
  """
2245
  __slots__ = [
2246
    "name",
2247
    "serial_no",
2248
    "mac_prefix",
2249
    "network",
2250
    "network6",
2251
    "gateway",
2252
    "gateway6",
2253
    "reservations",
2254
    "ext_reservations",
2255
    ] + _TIMESTAMPS + _UUID
2256

    
2257
  def HooksDict(self, prefix=""):
2258
    """Export a dictionary used by hooks with a network's information.
2259

2260
    @type prefix: String
2261
    @param prefix: Prefix to prepend to the dict entries
2262

2263
    """
2264
    result = {
2265
      "%sNETWORK_NAME" % prefix: self.name,
2266
      "%sNETWORK_UUID" % prefix: self.uuid,
2267
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2268
    }
2269
    if self.network:
2270
      result["%sNETWORK_SUBNET" % prefix] = self.network
2271
    if self.gateway:
2272
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2273
    if self.network6:
2274
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2275
    if self.gateway6:
2276
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2277
    if self.mac_prefix:
2278
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2279

    
2280
    return result
2281

    
2282
  @classmethod
2283
  def FromDict(cls, val):
2284
    """Custom function for networks.
2285

2286
    Remove deprecated network_type and family.
2287

2288
    """
2289
    if "network_type" in val:
2290
      del val["network_type"]
2291
    if "family" in val:
2292
      del val["family"]
2293
    obj = super(Network, cls).FromDict(val)
2294
    return obj
2295

    
2296

    
2297
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2298
  """Simple wrapper over ConfigParse that allows serialization.
2299

2300
  This class is basically ConfigParser.SafeConfigParser with two
2301
  additional methods that allow it to serialize/unserialize to/from a
2302
  buffer.
2303

2304
  """
2305
  def Dumps(self):
2306
    """Dump this instance and return the string representation."""
2307
    buf = StringIO()
2308
    self.write(buf)
2309
    return buf.getvalue()
2310

    
2311
  @classmethod
2312
  def Loads(cls, data):
2313
    """Load data from a string."""
2314
    buf = StringIO(data)
2315
    cfp = cls()
2316
    cfp.readfp(buf)
2317
    return cfp
2318

    
2319

    
2320
class LvmPvInfo(ConfigObject):
2321
  """Information about an LVM physical volume (PV).
2322

2323
  @type name: string
2324
  @ivar name: name of the PV
2325
  @type vg_name: string
2326
  @ivar vg_name: name of the volume group containing the PV
2327
  @type size: float
2328
  @ivar size: size of the PV in MiB
2329
  @type free: float
2330
  @ivar free: free space in the PV, in MiB
2331
  @type attributes: string
2332
  @ivar attributes: PV attributes
2333
  @type lv_list: list of strings
2334
  @ivar lv_list: names of the LVs hosted on the PV
2335
  """
2336
  __slots__ = [
2337
    "name",
2338
    "vg_name",
2339
    "size",
2340
    "free",
2341
    "attributes",
2342
    "lv_list"
2343
    ]
2344

    
2345
  def IsEmpty(self):
2346
    """Is this PV empty?
2347

2348
    """
2349
    return self.size <= (self.free + 1)
2350

    
2351
  def IsAllocatable(self):
2352
    """Is this PV allocatable?
2353

2354
    """
2355
    return ("a" in self.attributes)