Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 6ccce5d4

History | View | Annotate | Download (70.6 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 _ComputeAllNodes(self):
1112
    """Compute the list of all nodes.
1113

1114
    Since the data is already there (in the drbd disks), keeping it as
1115
    a separate normal attribute is redundant and if not properly
1116
    synchronised can cause problems. Thus it's better to compute it
1117
    dynamically.
1118

1119
    """
1120
    def _Helper(nodes, device):
1121
      """Recursively computes nodes given a top device."""
1122
      if device.dev_type in constants.DTS_DRBD:
1123
        nodea, nodeb = device.logical_id[:2]
1124
        nodes.add(nodea)
1125
        nodes.add(nodeb)
1126
      if device.children:
1127
        for child in device.children:
1128
          _Helper(nodes, child)
1129

    
1130
    all_nodes = set()
1131
    all_nodes.add(self.primary_node)
1132
    for device in self.disks:
1133
      _Helper(all_nodes, device)
1134
    return tuple(all_nodes)
1135

    
1136
  all_nodes = property(_ComputeAllNodes, None, None,
1137
                       "List of names of all the nodes of the instance")
1138

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

1142
    This function figures out what logical volumes should belong on
1143
    which nodes, recursing through a device tree.
1144

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

1159
    """
1160
    if node_uuid is None:
1161
      node_uuid = self.primary_node
1162

    
1163
    if lvmap is None:
1164
      lvmap = {
1165
        node_uuid: [],
1166
        }
1167
      ret = lvmap
1168
    else:
1169
      if not node_uuid in lvmap:
1170
        lvmap[node_uuid] = []
1171
      ret = None
1172

    
1173
    if not devs:
1174
      devs = self.disks
1175

    
1176
    for dev in devs:
1177
      if dev.dev_type == constants.DT_PLAIN:
1178
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1179

    
1180
      elif dev.dev_type in constants.DTS_DRBD:
1181
        if dev.children:
1182
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1183
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1184

    
1185
      elif dev.children:
1186
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1187

    
1188
    return ret
1189

    
1190
  def FindDisk(self, idx):
1191
    """Find a disk given having a specified index.
1192

1193
    This is just a wrapper that does validation of the index.
1194

1195
    @type idx: int
1196
    @param idx: the disk index
1197
    @rtype: L{Disk}
1198
    @return: the corresponding disk
1199
    @raise errors.OpPrereqError: when the given index is not valid
1200

1201
    """
1202
    try:
1203
      idx = int(idx)
1204
      return self.disks[idx]
1205
    except (TypeError, ValueError), err:
1206
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1207
                                 errors.ECODE_INVAL)
1208
    except IndexError:
1209
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1210
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1211
                                 errors.ECODE_INVAL)
1212

    
1213
  def ToDict(self, _with_private=False):
1214
    """Instance-specific conversion to standard python types.
1215

1216
    This replaces the children lists of objects with lists of standard
1217
    python types.
1218

1219
    """
1220
    bo = super(Instance, self).ToDict(_with_private=_with_private)
1221

    
1222
    if _with_private:
1223
      bo["osparams_private"] = self.osparams_private.Unprivate()
1224

    
1225
    for attr in "nics", "disks":
1226
      alist = bo.get(attr, None)
1227
      if alist:
1228
        nlist = outils.ContainerToDicts(alist)
1229
      else:
1230
        nlist = []
1231
      bo[attr] = nlist
1232
    return bo
1233

    
1234
  @classmethod
1235
  def FromDict(cls, val):
1236
    """Custom function for instances.
1237

1238
    """
1239
    if "admin_state" not in val:
1240
      if val.get("admin_up", False):
1241
        val["admin_state"] = constants.ADMINST_UP
1242
      else:
1243
        val["admin_state"] = constants.ADMINST_DOWN
1244
    if "admin_up" in val:
1245
      del val["admin_up"]
1246
    obj = super(Instance, cls).FromDict(val)
1247
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1248
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1249
    return obj
1250

    
1251
  def UpgradeConfig(self):
1252
    """Fill defaults for missing configuration values.
1253

1254
    """
1255
    for nic in self.nics:
1256
      nic.UpgradeConfig()
1257
    for disk in self.disks:
1258
      disk.UpgradeConfig()
1259
    if self.hvparams:
1260
      for key in constants.HVC_GLOBALS:
1261
        try:
1262
          del self.hvparams[key]
1263
        except KeyError:
1264
          pass
1265
    if self.osparams is None:
1266
      self.osparams = {}
1267
    if self.osparams_private is None:
1268
      self.osparams_private = serializer.PrivateDict()
1269
    UpgradeBeParams(self.beparams)
1270
    if self.disks_active is None:
1271
      self.disks_active = self.admin_state == constants.ADMINST_UP
1272

    
1273

    
1274
class OS(ConfigObject):
1275
  """Config object representing an operating system.
1276

1277
  @type supported_parameters: list
1278
  @ivar supported_parameters: a list of tuples, name and description,
1279
      containing the supported parameters by this OS
1280

1281
  @type VARIANT_DELIM: string
1282
  @cvar VARIANT_DELIM: the variant delimiter
1283

1284
  """
1285
  __slots__ = [
1286
    "name",
1287
    "path",
1288
    "api_versions",
1289
    "create_script",
1290
    "export_script",
1291
    "import_script",
1292
    "rename_script",
1293
    "verify_script",
1294
    "supported_variants",
1295
    "supported_parameters",
1296
    ]
1297

    
1298
  VARIANT_DELIM = "+"
1299

    
1300
  @classmethod
1301
  def SplitNameVariant(cls, name):
1302
    """Splits the name into the proper name and variant.
1303

1304
    @param name: the OS (unprocessed) name
1305
    @rtype: list
1306
    @return: a list of two elements; if the original name didn't
1307
        contain a variant, it's returned as an empty string
1308

1309
    """
1310
    nv = name.split(cls.VARIANT_DELIM, 1)
1311
    if len(nv) == 1:
1312
      nv.append("")
1313
    return nv
1314

    
1315
  @classmethod
1316
  def GetName(cls, name):
1317
    """Returns the proper name of the os (without the variant).
1318

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

1321
    """
1322
    return cls.SplitNameVariant(name)[0]
1323

    
1324
  @classmethod
1325
  def GetVariant(cls, name):
1326
    """Returns the variant the os (without the base name).
1327

1328
    @param name: the OS (unprocessed) name
1329

1330
    """
1331
    return cls.SplitNameVariant(name)[1]
1332

    
1333

    
1334
class ExtStorage(ConfigObject):
1335
  """Config object representing an External Storage Provider.
1336

1337
  """
1338
  __slots__ = [
1339
    "name",
1340
    "path",
1341
    "create_script",
1342
    "remove_script",
1343
    "grow_script",
1344
    "attach_script",
1345
    "detach_script",
1346
    "setinfo_script",
1347
    "verify_script",
1348
    "supported_parameters",
1349
    ]
1350

    
1351

    
1352
class NodeHvState(ConfigObject):
1353
  """Hypvervisor state on a node.
1354

1355
  @ivar mem_total: Total amount of memory
1356
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1357
    available)
1358
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1359
    rounding
1360
  @ivar mem_inst: Memory used by instances living on node
1361
  @ivar cpu_total: Total node CPU core count
1362
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1363

1364
  """
1365
  __slots__ = [
1366
    "mem_total",
1367
    "mem_node",
1368
    "mem_hv",
1369
    "mem_inst",
1370
    "cpu_total",
1371
    "cpu_node",
1372
    ] + _TIMESTAMPS
1373

    
1374

    
1375
class NodeDiskState(ConfigObject):
1376
  """Disk state on a node.
1377

1378
  """
1379
  __slots__ = [
1380
    "total",
1381
    "reserved",
1382
    "overhead",
1383
    ] + _TIMESTAMPS
1384

    
1385

    
1386
class Node(TaggableObject):
1387
  """Config object representing a node.
1388

1389
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1390
  @ivar hv_state_static: Hypervisor state overriden by user
1391
  @ivar disk_state: Disk state (e.g. free space)
1392
  @ivar disk_state_static: Disk state overriden by user
1393

1394
  """
1395
  __slots__ = [
1396
    "name",
1397
    "primary_ip",
1398
    "secondary_ip",
1399
    "serial_no",
1400
    "master_candidate",
1401
    "offline",
1402
    "drained",
1403
    "group",
1404
    "master_capable",
1405
    "vm_capable",
1406
    "ndparams",
1407
    "powered",
1408
    "hv_state",
1409
    "hv_state_static",
1410
    "disk_state",
1411
    "disk_state_static",
1412
    ] + _TIMESTAMPS + _UUID
1413

    
1414
  def UpgradeConfig(self):
1415
    """Fill defaults for missing configuration values.
1416

1417
    """
1418
    # pylint: disable=E0203
1419
    # because these are "defined" via slots, not manually
1420
    if self.master_capable is None:
1421
      self.master_capable = True
1422

    
1423
    if self.vm_capable is None:
1424
      self.vm_capable = True
1425

    
1426
    if self.ndparams is None:
1427
      self.ndparams = {}
1428
    # And remove any global parameter
1429
    for key in constants.NDC_GLOBALS:
1430
      if key in self.ndparams:
1431
        logging.warning("Ignoring %s node parameter for node %s",
1432
                        key, self.name)
1433
        del self.ndparams[key]
1434

    
1435
    if self.powered is None:
1436
      self.powered = True
1437

    
1438
  def ToDict(self, _with_private=False):
1439
    """Custom function for serializing.
1440

1441
    """
1442
    data = super(Node, self).ToDict(_with_private=_with_private)
1443

    
1444
    hv_state = data.get("hv_state", None)
1445
    if hv_state is not None:
1446
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1447

    
1448
    disk_state = data.get("disk_state", None)
1449
    if disk_state is not None:
1450
      data["disk_state"] = \
1451
        dict((key, outils.ContainerToDicts(value))
1452
             for (key, value) in disk_state.items())
1453

    
1454
    return data
1455

    
1456
  @classmethod
1457
  def FromDict(cls, val):
1458
    """Custom function for deserializing.
1459

1460
    """
1461
    obj = super(Node, cls).FromDict(val)
1462

    
1463
    if obj.hv_state is not None:
1464
      obj.hv_state = \
1465
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1466

    
1467
    if obj.disk_state is not None:
1468
      obj.disk_state = \
1469
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1470
             for (key, value) in obj.disk_state.items())
1471

    
1472
    return obj
1473

    
1474

    
1475
class NodeGroup(TaggableObject):
1476
  """Config object representing a node group."""
1477
  __slots__ = [
1478
    "name",
1479
    "members",
1480
    "ndparams",
1481
    "diskparams",
1482
    "ipolicy",
1483
    "serial_no",
1484
    "hv_state_static",
1485
    "disk_state_static",
1486
    "alloc_policy",
1487
    "networks",
1488
    ] + _TIMESTAMPS + _UUID
1489

    
1490
  def ToDict(self, _with_private=False):
1491
    """Custom function for nodegroup.
1492

1493
    This discards the members object, which gets recalculated and is only kept
1494
    in memory.
1495

1496
    """
1497
    mydict = super(NodeGroup, self).ToDict(_with_private=_with_private)
1498
    del mydict["members"]
1499
    return mydict
1500

    
1501
  @classmethod
1502
  def FromDict(cls, val):
1503
    """Custom function for nodegroup.
1504

1505
    The members slot is initialized to an empty list, upon deserialization.
1506

1507
    """
1508
    obj = super(NodeGroup, cls).FromDict(val)
1509
    obj.members = []
1510
    return obj
1511

    
1512
  def UpgradeConfig(self):
1513
    """Fill defaults for missing configuration values.
1514

1515
    """
1516
    if self.ndparams is None:
1517
      self.ndparams = {}
1518

    
1519
    if self.serial_no is None:
1520
      self.serial_no = 1
1521

    
1522
    if self.alloc_policy is None:
1523
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1524

    
1525
    # We only update mtime, and not ctime, since we would not be able
1526
    # to provide a correct value for creation time.
1527
    if self.mtime is None:
1528
      self.mtime = time.time()
1529

    
1530
    if self.diskparams is None:
1531
      self.diskparams = {}
1532
    if self.ipolicy is None:
1533
      self.ipolicy = MakeEmptyIPolicy()
1534

    
1535
    if self.networks is None:
1536
      self.networks = {}
1537

    
1538
  def FillND(self, node):
1539
    """Return filled out ndparams for L{objects.Node}
1540

1541
    @type node: L{objects.Node}
1542
    @param node: A Node object to fill
1543
    @return a copy of the node's ndparams with defaults filled
1544

1545
    """
1546
    return self.SimpleFillND(node.ndparams)
1547

    
1548
  def SimpleFillND(self, ndparams):
1549
    """Fill a given ndparams dict with defaults.
1550

1551
    @type ndparams: dict
1552
    @param ndparams: the dict to fill
1553
    @rtype: dict
1554
    @return: a copy of the passed in ndparams with missing keys filled
1555
        from the node group defaults
1556

1557
    """
1558
    return FillDict(self.ndparams, ndparams)
1559

    
1560

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

    
1613
  def UpgradeConfig(self):
1614
    """Fill defaults for missing configuration values.
1615

1616
    """
1617
    # pylint: disable=E0203
1618
    # because these are "defined" via slots, not manually
1619
    if self.hvparams is None:
1620
      self.hvparams = constants.HVC_DEFAULTS
1621
    else:
1622
      for hypervisor in constants.HYPER_TYPES:
1623
        try:
1624
          existing_params = self.hvparams[hypervisor]
1625
        except KeyError:
1626
          existing_params = {}
1627
        self.hvparams[hypervisor] = FillDict(
1628
            constants.HVC_DEFAULTS[hypervisor], existing_params)
1629

    
1630
    if self.os_hvp is None:
1631
      self.os_hvp = {}
1632

    
1633
    if self.osparams is None:
1634
      self.osparams = {}
1635
    # osparams_private_cluster added in 2.12
1636
    if self.osparams_private_cluster is None:
1637
      self.osparams_private_cluster = {}
1638

    
1639
    self.ndparams = UpgradeNDParams(self.ndparams)
1640

    
1641
    self.beparams = UpgradeGroupedParams(self.beparams,
1642
                                         constants.BEC_DEFAULTS)
1643
    for beparams_group in self.beparams:
1644
      UpgradeBeParams(self.beparams[beparams_group])
1645

    
1646
    migrate_default_bridge = not self.nicparams
1647
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1648
                                          constants.NICC_DEFAULTS)
1649
    if migrate_default_bridge:
1650
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1651
        self.default_bridge
1652

    
1653
    if self.modify_etc_hosts is None:
1654
      self.modify_etc_hosts = True
1655

    
1656
    if self.modify_ssh_setup is None:
1657
      self.modify_ssh_setup = True
1658

    
1659
    # default_bridge is no longer used in 2.1. The slot is left there to
1660
    # support auto-upgrading. It can be removed once we decide to deprecate
1661
    # upgrading straight from 2.0.
1662
    if self.default_bridge is not None:
1663
      self.default_bridge = None
1664

    
1665
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1666
    # code can be removed once upgrading straight from 2.0 is deprecated.
1667
    if self.default_hypervisor is not None:
1668
      self.enabled_hypervisors = ([self.default_hypervisor] +
1669
                                  [hvname for hvname in self.enabled_hypervisors
1670
                                   if hvname != self.default_hypervisor])
1671
      self.default_hypervisor = None
1672

    
1673
    # maintain_node_health added after 2.1.1
1674
    if self.maintain_node_health is None:
1675
      self.maintain_node_health = False
1676

    
1677
    if self.uid_pool is None:
1678
      self.uid_pool = []
1679

    
1680
    if self.default_iallocator is None:
1681
      self.default_iallocator = ""
1682

    
1683
    if self.default_iallocator_params is None:
1684
      self.default_iallocator_params = {}
1685

    
1686
    # reserved_lvs added before 2.2
1687
    if self.reserved_lvs is None:
1688
      self.reserved_lvs = []
1689

    
1690
    # hidden and blacklisted operating systems added before 2.2.1
1691
    if self.hidden_os is None:
1692
      self.hidden_os = []
1693

    
1694
    if self.blacklisted_os is None:
1695
      self.blacklisted_os = []
1696

    
1697
    # primary_ip_family added before 2.3
1698
    if self.primary_ip_family is None:
1699
      self.primary_ip_family = AF_INET
1700

    
1701
    if self.master_netmask is None:
1702
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1703
      self.master_netmask = ipcls.iplen
1704

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

    
1708
    # shared_file_storage_dir added before 2.5
1709
    if self.shared_file_storage_dir is None:
1710
      self.shared_file_storage_dir = ""
1711

    
1712
    # gluster_storage_dir added in 2.11
1713
    if self.gluster_storage_dir is None:
1714
      self.gluster_storage_dir = ""
1715

    
1716
    if self.use_external_mip_script is None:
1717
      self.use_external_mip_script = False
1718

    
1719
    if self.diskparams:
1720
      self.diskparams = UpgradeDiskParams(self.diskparams)
1721
    else:
1722
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1723

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

    
1739
    if self.candidate_certs is None:
1740
      self.candidate_certs = {}
1741

    
1742
    if self.max_running_jobs is None:
1743
      self.max_running_jobs = constants.LUXID_MAXIMAL_RUNNING_JOBS_DEFAULT
1744

    
1745
    if self.instance_communication_network is None:
1746
      self.instance_communication_network = ""
1747

    
1748
  @property
1749
  def primary_hypervisor(self):
1750
    """The first hypervisor is the primary.
1751

1752
    Useful, for example, for L{Node}'s hv/disk state.
1753

1754
    """
1755
    return self.enabled_hypervisors[0]
1756

    
1757
  def ToDict(self, _with_private=False):
1758
    """Custom function for cluster.
1759

1760
    """
1761
    mydict = super(Cluster, self).ToDict(_with_private=_with_private)
1762

    
1763
    # Explicitly save private parameters.
1764
    if _with_private:
1765
      for os in mydict["osparams_private_cluster"]:
1766
        mydict["osparams_private_cluster"][os] = \
1767
          self.osparams_private_cluster[os].Unprivate()
1768

    
1769
    if self.tcpudp_port_pool is None:
1770
      tcpudp_port_pool = []
1771
    else:
1772
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1773

    
1774
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1775

    
1776
    return mydict
1777

    
1778
  @classmethod
1779
  def FromDict(cls, val):
1780
    """Custom function for cluster.
1781

1782
    """
1783
    obj = super(Cluster, cls).FromDict(val)
1784

    
1785
    if obj.tcpudp_port_pool is None:
1786
      obj.tcpudp_port_pool = set()
1787
    elif not isinstance(obj.tcpudp_port_pool, set):
1788
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1789

    
1790
    return obj
1791

    
1792
  def SimpleFillDP(self, diskparams):
1793
    """Fill a given diskparams dict with cluster defaults.
1794

1795
    @param diskparams: The diskparams
1796
    @return: The defaults dict
1797

1798
    """
1799
    return FillDiskParams(self.diskparams, diskparams)
1800

    
1801
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1802
    """Get the default hypervisor parameters for the cluster.
1803

1804
    @param hypervisor: the hypervisor name
1805
    @param os_name: if specified, we'll also update the defaults for this OS
1806
    @param skip_keys: if passed, list of keys not to use
1807
    @return: the defaults dict
1808

1809
    """
1810
    if skip_keys is None:
1811
      skip_keys = []
1812

    
1813
    fill_stack = [self.hvparams.get(hypervisor, {})]
1814
    if os_name is not None:
1815
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1816
      fill_stack.append(os_hvp)
1817

    
1818
    ret_dict = {}
1819
    for o_dict in fill_stack:
1820
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1821

    
1822
    return ret_dict
1823

    
1824
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1825
    """Fill a given hvparams dict with cluster defaults.
1826

1827
    @type hv_name: string
1828
    @param hv_name: the hypervisor to use
1829
    @type os_name: string
1830
    @param os_name: the OS to use for overriding the hypervisor defaults
1831
    @type skip_globals: boolean
1832
    @param skip_globals: if True, the global hypervisor parameters will
1833
        not be filled
1834
    @rtype: dict
1835
    @return: a copy of the given hvparams with missing keys filled from
1836
        the cluster defaults
1837

1838
    """
1839
    if skip_globals:
1840
      skip_keys = constants.HVC_GLOBALS
1841
    else:
1842
      skip_keys = []
1843

    
1844
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1845
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1846

    
1847
  def FillHV(self, instance, skip_globals=False):
1848
    """Fill an instance's hvparams dict with cluster defaults.
1849

1850
    @type instance: L{objects.Instance}
1851
    @param instance: the instance parameter to fill
1852
    @type skip_globals: boolean
1853
    @param skip_globals: if True, the global hypervisor parameters will
1854
        not be filled
1855
    @rtype: dict
1856
    @return: a copy of the instance's hvparams with missing keys filled from
1857
        the cluster defaults
1858

1859
    """
1860
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1861
                             instance.hvparams, skip_globals)
1862

    
1863
  def SimpleFillBE(self, beparams):
1864
    """Fill a given beparams dict with cluster defaults.
1865

1866
    @type beparams: dict
1867
    @param beparams: the dict to fill
1868
    @rtype: dict
1869
    @return: a copy of the passed in beparams with missing keys filled
1870
        from the cluster defaults
1871

1872
    """
1873
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1874

    
1875
  def FillBE(self, instance):
1876
    """Fill an instance's beparams dict with cluster defaults.
1877

1878
    @type instance: L{objects.Instance}
1879
    @param instance: the instance parameter to fill
1880
    @rtype: dict
1881
    @return: a copy of the instance's beparams with missing keys filled from
1882
        the cluster defaults
1883

1884
    """
1885
    return self.SimpleFillBE(instance.beparams)
1886

    
1887
  def SimpleFillNIC(self, nicparams):
1888
    """Fill a given nicparams dict with cluster defaults.
1889

1890
    @type nicparams: dict
1891
    @param nicparams: the dict to fill
1892
    @rtype: dict
1893
    @return: a copy of the passed in nicparams with missing keys filled
1894
        from the cluster defaults
1895

1896
    """
1897
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1898

    
1899
  def SimpleFillOS(self, os_name,
1900
                    os_params_public,
1901
                    os_params_private=None,
1902
                    os_params_secret=None):
1903
    """Fill an instance's osparams dict with cluster defaults.
1904

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

1926
    """
1927
    name_only = os_name.split("+", 1)[0]
1928

    
1929
    defaults_base_public = self.osparams.get(name_only, {})
1930
    defaults_public = FillDict(defaults_base_public,
1931
                               self.osparams.get(os_name, {}))
1932
    params_public = FillDict(defaults_public, os_params_public)
1933

    
1934
    if os_params_private is not None:
1935
      defaults_base_private = self.osparams_private_cluster.get(name_only, {})
1936
      defaults_private = FillDict(defaults_base_private,
1937
                                  self.osparams_private_cluster.get(os_name,
1938
                                                                    {}))
1939
      params_private = FillDict(defaults_private, os_params_private)
1940
    else:
1941
      params_private = {}
1942

    
1943
    if os_params_secret is not None:
1944
      # There can't be default secret settings, so there's nothing to be done.
1945
      params_secret = os_params_secret
1946
    else:
1947
      params_secret = {}
1948

    
1949
    # Enforce that the set of keys be distinct:
1950
    duplicate_keys = utils.GetRepeatedKeys(params_public,
1951
                                           params_private,
1952
                                           params_secret)
1953
    if not duplicate_keys:
1954

    
1955
      # Actually update them:
1956
      params_public.update(params_private)
1957
      params_public.update(params_secret)
1958

    
1959
      return params_public
1960

    
1961
    else:
1962

    
1963
      def formatter(keys):
1964
        return utils.CommaJoin(sorted(map(repr, keys))) if keys else "(none)"
1965

    
1966
      #Lose the values.
1967
      params_public = set(params_public)
1968
      params_private = set(params_private)
1969
      params_secret = set(params_secret)
1970

    
1971
      msg = """Cannot assign multiple values to OS parameters.
1972

1973
      Conflicting OS parameters that would have been set by this operation:
1974
      - at public visibility:  {public}
1975
      - at private visibility: {private}
1976
      - at secret visibility:  {secret}
1977
      """.format(dupes=formatter(duplicate_keys),
1978
                 public=formatter(params_public & duplicate_keys),
1979
                 private=formatter(params_private & duplicate_keys),
1980
                 secret=formatter(params_secret & duplicate_keys))
1981
      raise errors.OpPrereqError(msg)
1982

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

1987
    """
1988
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1989

    
1990
  @staticmethod
1991
  def SimpleFillDiskState(disk_state):
1992
    """Fill an disk_state sub dict with cluster defaults.
1993

1994
    """
1995
    return FillDict(constants.DS_DEFAULTS, disk_state)
1996

    
1997
  def FillND(self, node, nodegroup):
1998
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1999

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

2006
    """
2007
    return self.SimpleFillND(nodegroup.FillND(node))
2008

    
2009
  def FillNDGroup(self, nodegroup):
2010
    """Return filled out ndparams for just L{objects.NodeGroup}
2011

2012
    @type nodegroup: L{objects.NodeGroup}
2013
    @param nodegroup: A Node object to fill
2014
    @return a copy of the node group's ndparams with defaults filled
2015

2016
    """
2017
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
2018

    
2019
  def SimpleFillND(self, ndparams):
2020
    """Fill a given ndparams dict with defaults.
2021

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

2028
    """
2029
    return FillDict(self.ndparams, ndparams)
2030

    
2031
  def SimpleFillIPolicy(self, ipolicy):
2032
    """ Fill instance policy dict with defaults.
2033

2034
    @type ipolicy: dict
2035
    @param ipolicy: the dict to fill
2036
    @rtype: dict
2037
    @return: a copy of passed ipolicy with missing keys filled from
2038
      the cluster defaults
2039

2040
    """
2041
    return FillIPolicy(self.ipolicy, ipolicy)
2042

    
2043
  def IsDiskTemplateEnabled(self, disk_template):
2044
    """Checks if a particular disk template is enabled.
2045

2046
    """
2047
    return utils.storage.IsDiskTemplateEnabled(
2048
        disk_template, self.enabled_disk_templates)
2049

    
2050
  def IsFileStorageEnabled(self):
2051
    """Checks if file storage is enabled.
2052

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

    
2056
  def IsSharedFileStorageEnabled(self):
2057
    """Checks if shared file storage is enabled.
2058

2059
    """
2060
    return utils.storage.IsSharedFileStorageEnabled(
2061
        self.enabled_disk_templates)
2062

    
2063

    
2064
class BlockDevStatus(ConfigObject):
2065
  """Config object representing the status of a block device."""
2066
  __slots__ = [
2067
    "dev_path",
2068
    "major",
2069
    "minor",
2070
    "sync_percent",
2071
    "estimated_time",
2072
    "is_degraded",
2073
    "ldisk_status",
2074
    ]
2075

    
2076

    
2077
class ImportExportStatus(ConfigObject):
2078
  """Config object representing the status of an import or export."""
2079
  __slots__ = [
2080
    "recent_output",
2081
    "listen_port",
2082
    "connected",
2083
    "progress_mbytes",
2084
    "progress_throughput",
2085
    "progress_eta",
2086
    "progress_percent",
2087
    "exit_status",
2088
    "error_message",
2089
    ] + _TIMESTAMPS
2090

    
2091

    
2092
class ImportExportOptions(ConfigObject):
2093
  """Options for import/export daemon
2094

2095
  @ivar key_name: X509 key name (None for cluster certificate)
2096
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
2097
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
2098
  @ivar magic: Used to ensure the connection goes to the right disk
2099
  @ivar ipv6: Whether to use IPv6
2100
  @ivar connect_timeout: Number of seconds for establishing connection
2101

2102
  """
2103
  __slots__ = [
2104
    "key_name",
2105
    "ca_pem",
2106
    "compress",
2107
    "magic",
2108
    "ipv6",
2109
    "connect_timeout",
2110
    ]
2111

    
2112

    
2113
class ConfdRequest(ConfigObject):
2114
  """Object holding a confd request.
2115

2116
  @ivar protocol: confd protocol version
2117
  @ivar type: confd query type
2118
  @ivar query: query request
2119
  @ivar rsalt: requested reply salt
2120

2121
  """
2122
  __slots__ = [
2123
    "protocol",
2124
    "type",
2125
    "query",
2126
    "rsalt",
2127
    ]
2128

    
2129

    
2130
class ConfdReply(ConfigObject):
2131
  """Object holding a confd reply.
2132

2133
  @ivar protocol: confd protocol version
2134
  @ivar status: reply status code (ok, error)
2135
  @ivar answer: confd query reply
2136
  @ivar serial: configuration serial number
2137

2138
  """
2139
  __slots__ = [
2140
    "protocol",
2141
    "status",
2142
    "answer",
2143
    "serial",
2144
    ]
2145

    
2146

    
2147
class QueryFieldDefinition(ConfigObject):
2148
  """Object holding a query field definition.
2149

2150
  @ivar name: Field name
2151
  @ivar title: Human-readable title
2152
  @ivar kind: Field type
2153
  @ivar doc: Human-readable description
2154

2155
  """
2156
  __slots__ = [
2157
    "name",
2158
    "title",
2159
    "kind",
2160
    "doc",
2161
    ]
2162

    
2163

    
2164
class _QueryResponseBase(ConfigObject):
2165
  __slots__ = [
2166
    "fields",
2167
    ]
2168

    
2169
  def ToDict(self, _with_private=False):
2170
    """Custom function for serializing.
2171

2172
    """
2173
    mydict = super(_QueryResponseBase, self).ToDict()
2174
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2175
    return mydict
2176

    
2177
  @classmethod
2178
  def FromDict(cls, val):
2179
    """Custom function for de-serializing.
2180

2181
    """
2182
    obj = super(_QueryResponseBase, cls).FromDict(val)
2183
    obj.fields = \
2184
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2185
    return obj
2186

    
2187

    
2188
class QueryResponse(_QueryResponseBase):
2189
  """Object holding the response to a query.
2190

2191
  @ivar fields: List of L{QueryFieldDefinition} objects
2192
  @ivar data: Requested data
2193

2194
  """
2195
  __slots__ = [
2196
    "data",
2197
    ]
2198

    
2199

    
2200
class QueryFieldsRequest(ConfigObject):
2201
  """Object holding a request for querying available fields.
2202

2203
  """
2204
  __slots__ = [
2205
    "what",
2206
    "fields",
2207
    ]
2208

    
2209

    
2210
class QueryFieldsResponse(_QueryResponseBase):
2211
  """Object holding the response to a query for fields.
2212

2213
  @ivar fields: List of L{QueryFieldDefinition} objects
2214

2215
  """
2216
  __slots__ = []
2217

    
2218

    
2219
class MigrationStatus(ConfigObject):
2220
  """Object holding the status of a migration.
2221

2222
  """
2223
  __slots__ = [
2224
    "status",
2225
    "transferred_ram",
2226
    "total_ram",
2227
    ]
2228

    
2229

    
2230
class InstanceConsole(ConfigObject):
2231
  """Object describing how to access the console of an instance.
2232

2233
  """
2234
  __slots__ = [
2235
    "instance",
2236
    "kind",
2237
    "message",
2238
    "host",
2239
    "port",
2240
    "user",
2241
    "command",
2242
    "display",
2243
    ]
2244

    
2245
  def Validate(self):
2246
    """Validates contents of this object.
2247

2248
    """
2249
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2250
    assert self.instance, "Missing instance name"
2251
    assert self.message or self.kind in [constants.CONS_SSH,
2252
                                         constants.CONS_SPICE,
2253
                                         constants.CONS_VNC]
2254
    assert self.host or self.kind == constants.CONS_MESSAGE
2255
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2256
                                      constants.CONS_SSH]
2257
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2258
                                      constants.CONS_SPICE,
2259
                                      constants.CONS_VNC]
2260
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2261
                                         constants.CONS_SPICE,
2262
                                         constants.CONS_VNC]
2263
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2264
                                         constants.CONS_SPICE,
2265
                                         constants.CONS_SSH]
2266
    return True
2267

    
2268

    
2269
class Network(TaggableObject):
2270
  """Object representing a network definition for ganeti.
2271

2272
  """
2273
  __slots__ = [
2274
    "name",
2275
    "serial_no",
2276
    "mac_prefix",
2277
    "network",
2278
    "network6",
2279
    "gateway",
2280
    "gateway6",
2281
    "reservations",
2282
    "ext_reservations",
2283
    ] + _TIMESTAMPS + _UUID
2284

    
2285
  def HooksDict(self, prefix=""):
2286
    """Export a dictionary used by hooks with a network's information.
2287

2288
    @type prefix: String
2289
    @param prefix: Prefix to prepend to the dict entries
2290

2291
    """
2292
    result = {
2293
      "%sNETWORK_NAME" % prefix: self.name,
2294
      "%sNETWORK_UUID" % prefix: self.uuid,
2295
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2296
    }
2297
    if self.network:
2298
      result["%sNETWORK_SUBNET" % prefix] = self.network
2299
    if self.gateway:
2300
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2301
    if self.network6:
2302
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2303
    if self.gateway6:
2304
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2305
    if self.mac_prefix:
2306
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2307

    
2308
    return result
2309

    
2310
  @classmethod
2311
  def FromDict(cls, val):
2312
    """Custom function for networks.
2313

2314
    Remove deprecated network_type and family.
2315

2316
    """
2317
    if "network_type" in val:
2318
      del val["network_type"]
2319
    if "family" in val:
2320
      del val["family"]
2321
    obj = super(Network, cls).FromDict(val)
2322
    return obj
2323

    
2324

    
2325
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2326
  """Simple wrapper over ConfigParse that allows serialization.
2327

2328
  This class is basically ConfigParser.SafeConfigParser with two
2329
  additional methods that allow it to serialize/unserialize to/from a
2330
  buffer.
2331

2332
  """
2333
  def Dumps(self):
2334
    """Dump this instance and return the string representation."""
2335
    buf = StringIO()
2336
    self.write(buf)
2337
    return buf.getvalue()
2338

    
2339
  @classmethod
2340
  def Loads(cls, data):
2341
    """Load data from a string."""
2342
    buf = StringIO(data)
2343
    cfp = cls()
2344
    cfp.readfp(buf)
2345
    return cfp
2346

    
2347

    
2348
class LvmPvInfo(ConfigObject):
2349
  """Information about an LVM physical volume (PV).
2350

2351
  @type name: string
2352
  @ivar name: name of the PV
2353
  @type vg_name: string
2354
  @ivar vg_name: name of the volume group containing the PV
2355
  @type size: float
2356
  @ivar size: size of the PV in MiB
2357
  @type free: float
2358
  @ivar free: free space in the PV, in MiB
2359
  @type attributes: string
2360
  @ivar attributes: PV attributes
2361
  @type lv_list: list of strings
2362
  @ivar lv_list: names of the LVs hosted on the PV
2363
  """
2364
  __slots__ = [
2365
    "name",
2366
    "vg_name",
2367
    "size",
2368
    "free",
2369
    "attributes",
2370
    "lv_list"
2371
    ]
2372

    
2373
  def IsEmpty(self):
2374
    """Is this PV empty?
2375

2376
    """
2377
    return self.size <= (self.free + 1)
2378

    
2379
  def IsAllocatable(self):
2380
    """Is this PV allocatable?
2381

2382
    """
2383
    return ("a" in self.attributes)