Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 9e8ff434

History | View | Annotate | Download (71 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
               + _UUID +
527
               # dynamic_params is special. It depends on the node this instance
528
               # is sent to, and should not be persisted.
529
               ["dynamic_params"])
530

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

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

    
543
    return tuple(set(nodes))
544

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

670
    This only works for VG-based disks.
671

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
778
    self.dynamic_params = dyn_disk_params
779

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
870
    # add here config upgrade for this disk
871

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

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

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

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

    
895
    assert disk_template in disk_params
896

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

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

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

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

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

    
934
    return result
935

    
936

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1088

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

    
1109
  def _ComputeSecondaryNodes(self):
1110
    """Compute the list of secondary nodes.
1111

1112
    This is a simple wrapper over _ComputeAllNodes.
1113

1114
    """
1115
    all_nodes = set(self._ComputeAllNodes())
1116
    all_nodes.discard(self.primary_node)
1117
    return tuple(all_nodes)
1118

    
1119
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1120
                             "List of names of secondary nodes")
1121

    
1122
  def _ComputeAllNodes(self):
1123
    """Compute the list of all nodes.
1124

1125
    Since the data is already there (in the drbd disks), keeping it as
1126
    a separate normal attribute is redundant and if not properly
1127
    synchronised can cause problems. Thus it's better to compute it
1128
    dynamically.
1129

1130
    """
1131
    def _Helper(nodes, device):
1132
      """Recursively computes nodes given a top device."""
1133
      if device.dev_type in constants.DTS_DRBD:
1134
        nodea, nodeb = device.logical_id[:2]
1135
        nodes.add(nodea)
1136
        nodes.add(nodeb)
1137
      if device.children:
1138
        for child in device.children:
1139
          _Helper(nodes, child)
1140

    
1141
    all_nodes = set()
1142
    all_nodes.add(self.primary_node)
1143
    for device in self.disks:
1144
      _Helper(all_nodes, device)
1145
    return tuple(all_nodes)
1146

    
1147
  all_nodes = property(_ComputeAllNodes, None, None,
1148
                       "List of names of all the nodes of the instance")
1149

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

1153
    This function figures out what logical volumes should belong on
1154
    which nodes, recursing through a device tree.
1155

1156
    @type lvmap: dict
1157
    @param lvmap: optional dictionary to receive the
1158
        'node' : ['lv', ...] data.
1159
    @type devs: list of L{Disk}
1160
    @param devs: disks to get the LV name for. If None, all disk of this
1161
        instance are used.
1162
    @type node_uuid: string
1163
    @param node_uuid: UUID of the node to get the LV names for. If None, the
1164
        primary node of this instance is used.
1165
    @return: None if lvmap arg is given, otherwise, a dictionary of
1166
        the form { 'node_uuid' : ['volume1', 'volume2', ...], ... };
1167
        volumeN is of the form "vg_name/lv_name", compatible with
1168
        GetVolumeList()
1169

1170
    """
1171
    if node_uuid is None:
1172
      node_uuid = self.primary_node
1173

    
1174
    if lvmap is None:
1175
      lvmap = {
1176
        node_uuid: [],
1177
        }
1178
      ret = lvmap
1179
    else:
1180
      if not node_uuid in lvmap:
1181
        lvmap[node_uuid] = []
1182
      ret = None
1183

    
1184
    if not devs:
1185
      devs = self.disks
1186

    
1187
    for dev in devs:
1188
      if dev.dev_type == constants.DT_PLAIN:
1189
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1190

    
1191
      elif dev.dev_type in constants.DTS_DRBD:
1192
        if dev.children:
1193
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1194
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1195

    
1196
      elif dev.children:
1197
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1198

    
1199
    return ret
1200

    
1201
  def FindDisk(self, idx):
1202
    """Find a disk given having a specified index.
1203

1204
    This is just a wrapper that does validation of the index.
1205

1206
    @type idx: int
1207
    @param idx: the disk index
1208
    @rtype: L{Disk}
1209
    @return: the corresponding disk
1210
    @raise errors.OpPrereqError: when the given index is not valid
1211

1212
    """
1213
    try:
1214
      idx = int(idx)
1215
      return self.disks[idx]
1216
    except (TypeError, ValueError), err:
1217
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1218
                                 errors.ECODE_INVAL)
1219
    except IndexError:
1220
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1221
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1222
                                 errors.ECODE_INVAL)
1223

    
1224
  def ToDict(self, _with_private=False):
1225
    """Instance-specific conversion to standard python types.
1226

1227
    This replaces the children lists of objects with lists of standard
1228
    python types.
1229

1230
    """
1231
    bo = super(Instance, self).ToDict(_with_private=_with_private)
1232

    
1233
    if _with_private:
1234
      bo["osparams_private"] = self.osparams_private.Unprivate()
1235

    
1236
    for attr in "nics", "disks":
1237
      alist = bo.get(attr, None)
1238
      if alist:
1239
        nlist = outils.ContainerToDicts(alist)
1240
      else:
1241
        nlist = []
1242
      bo[attr] = nlist
1243
    return bo
1244

    
1245
  @classmethod
1246
  def FromDict(cls, val):
1247
    """Custom function for instances.
1248

1249
    """
1250
    if "admin_state" not in val:
1251
      if val.get("admin_up", False):
1252
        val["admin_state"] = constants.ADMINST_UP
1253
      else:
1254
        val["admin_state"] = constants.ADMINST_DOWN
1255
    if "admin_up" in val:
1256
      del val["admin_up"]
1257
    obj = super(Instance, cls).FromDict(val)
1258
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1259
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1260
    return obj
1261

    
1262
  def UpgradeConfig(self):
1263
    """Fill defaults for missing configuration values.
1264

1265
    """
1266
    for nic in self.nics:
1267
      nic.UpgradeConfig()
1268
    for disk in self.disks:
1269
      disk.UpgradeConfig()
1270
    if self.hvparams:
1271
      for key in constants.HVC_GLOBALS:
1272
        try:
1273
          del self.hvparams[key]
1274
        except KeyError:
1275
          pass
1276
    if self.osparams is None:
1277
      self.osparams = {}
1278
    if self.osparams_private is None:
1279
      self.osparams_private = serializer.PrivateDict()
1280
    UpgradeBeParams(self.beparams)
1281
    if self.disks_active is None:
1282
      self.disks_active = self.admin_state == constants.ADMINST_UP
1283

    
1284

    
1285
class OS(ConfigObject):
1286
  """Config object representing an operating system.
1287

1288
  @type supported_parameters: list
1289
  @ivar supported_parameters: a list of tuples, name and description,
1290
      containing the supported parameters by this OS
1291

1292
  @type VARIANT_DELIM: string
1293
  @cvar VARIANT_DELIM: the variant delimiter
1294

1295
  """
1296
  __slots__ = [
1297
    "name",
1298
    "path",
1299
    "api_versions",
1300
    "create_script",
1301
    "export_script",
1302
    "import_script",
1303
    "rename_script",
1304
    "verify_script",
1305
    "supported_variants",
1306
    "supported_parameters",
1307
    ]
1308

    
1309
  VARIANT_DELIM = "+"
1310

    
1311
  @classmethod
1312
  def SplitNameVariant(cls, name):
1313
    """Splits the name into the proper name and variant.
1314

1315
    @param name: the OS (unprocessed) name
1316
    @rtype: list
1317
    @return: a list of two elements; if the original name didn't
1318
        contain a variant, it's returned as an empty string
1319

1320
    """
1321
    nv = name.split(cls.VARIANT_DELIM, 1)
1322
    if len(nv) == 1:
1323
      nv.append("")
1324
    return nv
1325

    
1326
  @classmethod
1327
  def GetName(cls, name):
1328
    """Returns the proper name of the os (without the variant).
1329

1330
    @param name: the OS (unprocessed) name
1331

1332
    """
1333
    return cls.SplitNameVariant(name)[0]
1334

    
1335
  @classmethod
1336
  def GetVariant(cls, name):
1337
    """Returns the variant the os (without the base name).
1338

1339
    @param name: the OS (unprocessed) name
1340

1341
    """
1342
    return cls.SplitNameVariant(name)[1]
1343

    
1344

    
1345
class ExtStorage(ConfigObject):
1346
  """Config object representing an External Storage Provider.
1347

1348
  """
1349
  __slots__ = [
1350
    "name",
1351
    "path",
1352
    "create_script",
1353
    "remove_script",
1354
    "grow_script",
1355
    "attach_script",
1356
    "detach_script",
1357
    "setinfo_script",
1358
    "verify_script",
1359
    "supported_parameters",
1360
    ]
1361

    
1362

    
1363
class NodeHvState(ConfigObject):
1364
  """Hypvervisor state on a node.
1365

1366
  @ivar mem_total: Total amount of memory
1367
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1368
    available)
1369
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1370
    rounding
1371
  @ivar mem_inst: Memory used by instances living on node
1372
  @ivar cpu_total: Total node CPU core count
1373
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1374

1375
  """
1376
  __slots__ = [
1377
    "mem_total",
1378
    "mem_node",
1379
    "mem_hv",
1380
    "mem_inst",
1381
    "cpu_total",
1382
    "cpu_node",
1383
    ] + _TIMESTAMPS
1384

    
1385

    
1386
class NodeDiskState(ConfigObject):
1387
  """Disk state on a node.
1388

1389
  """
1390
  __slots__ = [
1391
    "total",
1392
    "reserved",
1393
    "overhead",
1394
    ] + _TIMESTAMPS
1395

    
1396

    
1397
class Node(TaggableObject):
1398
  """Config object representing a node.
1399

1400
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1401
  @ivar hv_state_static: Hypervisor state overriden by user
1402
  @ivar disk_state: Disk state (e.g. free space)
1403
  @ivar disk_state_static: Disk state overriden by user
1404

1405
  """
1406
  __slots__ = [
1407
    "name",
1408
    "primary_ip",
1409
    "secondary_ip",
1410
    "serial_no",
1411
    "master_candidate",
1412
    "offline",
1413
    "drained",
1414
    "group",
1415
    "master_capable",
1416
    "vm_capable",
1417
    "ndparams",
1418
    "powered",
1419
    "hv_state",
1420
    "hv_state_static",
1421
    "disk_state",
1422
    "disk_state_static",
1423
    ] + _TIMESTAMPS + _UUID
1424

    
1425
  def UpgradeConfig(self):
1426
    """Fill defaults for missing configuration values.
1427

1428
    """
1429
    # pylint: disable=E0203
1430
    # because these are "defined" via slots, not manually
1431
    if self.master_capable is None:
1432
      self.master_capable = True
1433

    
1434
    if self.vm_capable is None:
1435
      self.vm_capable = True
1436

    
1437
    if self.ndparams is None:
1438
      self.ndparams = {}
1439
    # And remove any global parameter
1440
    for key in constants.NDC_GLOBALS:
1441
      if key in self.ndparams:
1442
        logging.warning("Ignoring %s node parameter for node %s",
1443
                        key, self.name)
1444
        del self.ndparams[key]
1445

    
1446
    if self.powered is None:
1447
      self.powered = True
1448

    
1449
  def ToDict(self, _with_private=False):
1450
    """Custom function for serializing.
1451

1452
    """
1453
    data = super(Node, self).ToDict(_with_private=_with_private)
1454

    
1455
    hv_state = data.get("hv_state", None)
1456
    if hv_state is not None:
1457
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1458

    
1459
    disk_state = data.get("disk_state", None)
1460
    if disk_state is not None:
1461
      data["disk_state"] = \
1462
        dict((key, outils.ContainerToDicts(value))
1463
             for (key, value) in disk_state.items())
1464

    
1465
    return data
1466

    
1467
  @classmethod
1468
  def FromDict(cls, val):
1469
    """Custom function for deserializing.
1470

1471
    """
1472
    obj = super(Node, cls).FromDict(val)
1473

    
1474
    if obj.hv_state is not None:
1475
      obj.hv_state = \
1476
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1477

    
1478
    if obj.disk_state is not None:
1479
      obj.disk_state = \
1480
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1481
             for (key, value) in obj.disk_state.items())
1482

    
1483
    return obj
1484

    
1485

    
1486
class NodeGroup(TaggableObject):
1487
  """Config object representing a node group."""
1488
  __slots__ = [
1489
    "name",
1490
    "members",
1491
    "ndparams",
1492
    "diskparams",
1493
    "ipolicy",
1494
    "serial_no",
1495
    "hv_state_static",
1496
    "disk_state_static",
1497
    "alloc_policy",
1498
    "networks",
1499
    ] + _TIMESTAMPS + _UUID
1500

    
1501
  def ToDict(self, _with_private=False):
1502
    """Custom function for nodegroup.
1503

1504
    This discards the members object, which gets recalculated and is only kept
1505
    in memory.
1506

1507
    """
1508
    mydict = super(NodeGroup, self).ToDict(_with_private=_with_private)
1509
    del mydict["members"]
1510
    return mydict
1511

    
1512
  @classmethod
1513
  def FromDict(cls, val):
1514
    """Custom function for nodegroup.
1515

1516
    The members slot is initialized to an empty list, upon deserialization.
1517

1518
    """
1519
    obj = super(NodeGroup, cls).FromDict(val)
1520
    obj.members = []
1521
    return obj
1522

    
1523
  def UpgradeConfig(self):
1524
    """Fill defaults for missing configuration values.
1525

1526
    """
1527
    if self.ndparams is None:
1528
      self.ndparams = {}
1529

    
1530
    if self.serial_no is None:
1531
      self.serial_no = 1
1532

    
1533
    if self.alloc_policy is None:
1534
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1535

    
1536
    # We only update mtime, and not ctime, since we would not be able
1537
    # to provide a correct value for creation time.
1538
    if self.mtime is None:
1539
      self.mtime = time.time()
1540

    
1541
    if self.diskparams is None:
1542
      self.diskparams = {}
1543
    if self.ipolicy is None:
1544
      self.ipolicy = MakeEmptyIPolicy()
1545

    
1546
    if self.networks is None:
1547
      self.networks = {}
1548

    
1549
  def FillND(self, node):
1550
    """Return filled out ndparams for L{objects.Node}
1551

1552
    @type node: L{objects.Node}
1553
    @param node: A Node object to fill
1554
    @return a copy of the node's ndparams with defaults filled
1555

1556
    """
1557
    return self.SimpleFillND(node.ndparams)
1558

    
1559
  def SimpleFillND(self, ndparams):
1560
    """Fill a given ndparams dict with defaults.
1561

1562
    @type ndparams: dict
1563
    @param ndparams: the dict to fill
1564
    @rtype: dict
1565
    @return: a copy of the passed in ndparams with missing keys filled
1566
        from the node group defaults
1567

1568
    """
1569
    return FillDict(self.ndparams, ndparams)
1570

    
1571

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

    
1624
  def UpgradeConfig(self):
1625
    """Fill defaults for missing configuration values.
1626

1627
    """
1628
    # pylint: disable=E0203
1629
    # because these are "defined" via slots, not manually
1630
    if self.hvparams is None:
1631
      self.hvparams = constants.HVC_DEFAULTS
1632
    else:
1633
      for hypervisor in constants.HYPER_TYPES:
1634
        try:
1635
          existing_params = self.hvparams[hypervisor]
1636
        except KeyError:
1637
          existing_params = {}
1638
        self.hvparams[hypervisor] = FillDict(
1639
            constants.HVC_DEFAULTS[hypervisor], existing_params)
1640

    
1641
    if self.os_hvp is None:
1642
      self.os_hvp = {}
1643

    
1644
    if self.osparams is None:
1645
      self.osparams = {}
1646
    # osparams_private_cluster added in 2.12
1647
    if self.osparams_private_cluster is None:
1648
      self.osparams_private_cluster = {}
1649

    
1650
    self.ndparams = UpgradeNDParams(self.ndparams)
1651

    
1652
    self.beparams = UpgradeGroupedParams(self.beparams,
1653
                                         constants.BEC_DEFAULTS)
1654
    for beparams_group in self.beparams:
1655
      UpgradeBeParams(self.beparams[beparams_group])
1656

    
1657
    migrate_default_bridge = not self.nicparams
1658
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1659
                                          constants.NICC_DEFAULTS)
1660
    if migrate_default_bridge:
1661
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1662
        self.default_bridge
1663

    
1664
    if self.modify_etc_hosts is None:
1665
      self.modify_etc_hosts = True
1666

    
1667
    if self.modify_ssh_setup is None:
1668
      self.modify_ssh_setup = True
1669

    
1670
    # default_bridge is no longer used in 2.1. The slot is left there to
1671
    # support auto-upgrading. It can be removed once we decide to deprecate
1672
    # upgrading straight from 2.0.
1673
    if self.default_bridge is not None:
1674
      self.default_bridge = None
1675

    
1676
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1677
    # code can be removed once upgrading straight from 2.0 is deprecated.
1678
    if self.default_hypervisor is not None:
1679
      self.enabled_hypervisors = ([self.default_hypervisor] +
1680
                                  [hvname for hvname in self.enabled_hypervisors
1681
                                   if hvname != self.default_hypervisor])
1682
      self.default_hypervisor = None
1683

    
1684
    # maintain_node_health added after 2.1.1
1685
    if self.maintain_node_health is None:
1686
      self.maintain_node_health = False
1687

    
1688
    if self.uid_pool is None:
1689
      self.uid_pool = []
1690

    
1691
    if self.default_iallocator is None:
1692
      self.default_iallocator = ""
1693

    
1694
    if self.default_iallocator_params is None:
1695
      self.default_iallocator_params = {}
1696

    
1697
    # reserved_lvs added before 2.2
1698
    if self.reserved_lvs is None:
1699
      self.reserved_lvs = []
1700

    
1701
    # hidden and blacklisted operating systems added before 2.2.1
1702
    if self.hidden_os is None:
1703
      self.hidden_os = []
1704

    
1705
    if self.blacklisted_os is None:
1706
      self.blacklisted_os = []
1707

    
1708
    # primary_ip_family added before 2.3
1709
    if self.primary_ip_family is None:
1710
      self.primary_ip_family = AF_INET
1711

    
1712
    if self.master_netmask is None:
1713
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1714
      self.master_netmask = ipcls.iplen
1715

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

    
1719
    # shared_file_storage_dir added before 2.5
1720
    if self.shared_file_storage_dir is None:
1721
      self.shared_file_storage_dir = ""
1722

    
1723
    # gluster_storage_dir added in 2.11
1724
    if self.gluster_storage_dir is None:
1725
      self.gluster_storage_dir = ""
1726

    
1727
    if self.use_external_mip_script is None:
1728
      self.use_external_mip_script = False
1729

    
1730
    if self.diskparams:
1731
      self.diskparams = UpgradeDiskParams(self.diskparams)
1732
    else:
1733
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1734

    
1735
    # instance policy added before 2.6
1736
    if self.ipolicy is None:
1737
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1738
    else:
1739
      # we can either make sure to upgrade the ipolicy always, or only
1740
      # do it in some corner cases (e.g. missing keys); note that this
1741
      # will break any removal of keys from the ipolicy dict
1742
      wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1743
      if wrongkeys:
1744
        # These keys would be silently removed by FillIPolicy()
1745
        msg = ("Cluster instance policy contains spurious keys: %s" %
1746
               utils.CommaJoin(wrongkeys))
1747
        raise errors.ConfigurationError(msg)
1748
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1749

    
1750
    if self.candidate_certs is None:
1751
      self.candidate_certs = {}
1752

    
1753
    if self.max_running_jobs is None:
1754
      self.max_running_jobs = constants.LUXID_MAXIMAL_RUNNING_JOBS_DEFAULT
1755

    
1756
    if self.instance_communication_network is None:
1757
      self.instance_communication_network = ""
1758

    
1759
  @property
1760
  def primary_hypervisor(self):
1761
    """The first hypervisor is the primary.
1762

1763
    Useful, for example, for L{Node}'s hv/disk state.
1764

1765
    """
1766
    return self.enabled_hypervisors[0]
1767

    
1768
  def ToDict(self, _with_private=False):
1769
    """Custom function for cluster.
1770

1771
    """
1772
    mydict = super(Cluster, self).ToDict(_with_private=_with_private)
1773

    
1774
    # Explicitly save private parameters.
1775
    if _with_private:
1776
      for os in mydict["osparams_private_cluster"]:
1777
        mydict["osparams_private_cluster"][os] = \
1778
          self.osparams_private_cluster[os].Unprivate()
1779

    
1780
    if self.tcpudp_port_pool is None:
1781
      tcpudp_port_pool = []
1782
    else:
1783
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1784

    
1785
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1786

    
1787
    return mydict
1788

    
1789
  @classmethod
1790
  def FromDict(cls, val):
1791
    """Custom function for cluster.
1792

1793
    """
1794
    obj = super(Cluster, cls).FromDict(val)
1795

    
1796
    if obj.tcpudp_port_pool is None:
1797
      obj.tcpudp_port_pool = set()
1798
    elif not isinstance(obj.tcpudp_port_pool, set):
1799
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1800

    
1801
    return obj
1802

    
1803
  def SimpleFillDP(self, diskparams):
1804
    """Fill a given diskparams dict with cluster defaults.
1805

1806
    @param diskparams: The diskparams
1807
    @return: The defaults dict
1808

1809
    """
1810
    return FillDiskParams(self.diskparams, diskparams)
1811

    
1812
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1813
    """Get the default hypervisor parameters for the cluster.
1814

1815
    @param hypervisor: the hypervisor name
1816
    @param os_name: if specified, we'll also update the defaults for this OS
1817
    @param skip_keys: if passed, list of keys not to use
1818
    @return: the defaults dict
1819

1820
    """
1821
    if skip_keys is None:
1822
      skip_keys = []
1823

    
1824
    fill_stack = [self.hvparams.get(hypervisor, {})]
1825
    if os_name is not None:
1826
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1827
      fill_stack.append(os_hvp)
1828

    
1829
    ret_dict = {}
1830
    for o_dict in fill_stack:
1831
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1832

    
1833
    return ret_dict
1834

    
1835
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1836
    """Fill a given hvparams dict with cluster defaults.
1837

1838
    @type hv_name: string
1839
    @param hv_name: the hypervisor to use
1840
    @type os_name: string
1841
    @param os_name: the OS to use for overriding the hypervisor defaults
1842
    @type skip_globals: boolean
1843
    @param skip_globals: if True, the global hypervisor parameters will
1844
        not be filled
1845
    @rtype: dict
1846
    @return: a copy of the given hvparams with missing keys filled from
1847
        the cluster defaults
1848

1849
    """
1850
    if skip_globals:
1851
      skip_keys = constants.HVC_GLOBALS
1852
    else:
1853
      skip_keys = []
1854

    
1855
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1856
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1857

    
1858
  def FillHV(self, instance, skip_globals=False):
1859
    """Fill an instance's hvparams dict with cluster defaults.
1860

1861
    @type instance: L{objects.Instance}
1862
    @param instance: the instance parameter to fill
1863
    @type skip_globals: boolean
1864
    @param skip_globals: if True, the global hypervisor parameters will
1865
        not be filled
1866
    @rtype: dict
1867
    @return: a copy of the instance's hvparams with missing keys filled from
1868
        the cluster defaults
1869

1870
    """
1871
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1872
                             instance.hvparams, skip_globals)
1873

    
1874
  def SimpleFillBE(self, beparams):
1875
    """Fill a given beparams dict with cluster defaults.
1876

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

1883
    """
1884
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1885

    
1886
  def FillBE(self, instance):
1887
    """Fill an instance's beparams dict with cluster defaults.
1888

1889
    @type instance: L{objects.Instance}
1890
    @param instance: the instance parameter to fill
1891
    @rtype: dict
1892
    @return: a copy of the instance's beparams with missing keys filled from
1893
        the cluster defaults
1894

1895
    """
1896
    return self.SimpleFillBE(instance.beparams)
1897

    
1898
  def SimpleFillNIC(self, nicparams):
1899
    """Fill a given nicparams dict with cluster defaults.
1900

1901
    @type nicparams: dict
1902
    @param nicparams: the dict to fill
1903
    @rtype: dict
1904
    @return: a copy of the passed in nicparams with missing keys filled
1905
        from the cluster defaults
1906

1907
    """
1908
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1909

    
1910
  def SimpleFillOS(self, os_name,
1911
                    os_params_public,
1912
                    os_params_private=None,
1913
                    os_params_secret=None):
1914
    """Fill an instance's osparams dict with cluster defaults.
1915

1916
    @type os_name: string
1917
    @param os_name: the OS name to use
1918
    @type os_params_public: dict
1919
    @param os_params_public: the dict to fill with default values
1920
    @type os_params_private: dict
1921
    @param os_params_private: the dict with private fields to fill
1922
                              with default values. Not passing this field
1923
                              results in no private fields being added to the
1924
                              return value. Private fields will be wrapped in
1925
                              L{Private} objects.
1926
    @type os_params_secret: dict
1927
    @param os_params_secret: the dict with secret fields to fill
1928
                             with default values. Not passing this field
1929
                             results in no secret fields being added to the
1930
                             return value. Private fields will be wrapped in
1931
                             L{Private} objects.
1932
    @rtype: dict
1933
    @return: a copy of the instance's osparams with missing keys filled from
1934
        the cluster defaults. Private and secret parameters are not included
1935
        unless the respective optional parameters are supplied.
1936

1937
    """
1938
    name_only = os_name.split("+", 1)[0]
1939

    
1940
    defaults_base_public = self.osparams.get(name_only, {})
1941
    defaults_public = FillDict(defaults_base_public,
1942
                               self.osparams.get(os_name, {}))
1943
    params_public = FillDict(defaults_public, os_params_public)
1944

    
1945
    if os_params_private is not None:
1946
      defaults_base_private = self.osparams_private_cluster.get(name_only, {})
1947
      defaults_private = FillDict(defaults_base_private,
1948
                                  self.osparams_private_cluster.get(os_name,
1949
                                                                    {}))
1950
      params_private = FillDict(defaults_private, os_params_private)
1951
    else:
1952
      params_private = {}
1953

    
1954
    if os_params_secret is not None:
1955
      # There can't be default secret settings, so there's nothing to be done.
1956
      params_secret = os_params_secret
1957
    else:
1958
      params_secret = {}
1959

    
1960
    # Enforce that the set of keys be distinct:
1961
    duplicate_keys = utils.GetRepeatedKeys(params_public,
1962
                                           params_private,
1963
                                           params_secret)
1964
    if not duplicate_keys:
1965

    
1966
      # Actually update them:
1967
      params_public.update(params_private)
1968
      params_public.update(params_secret)
1969

    
1970
      return params_public
1971

    
1972
    else:
1973

    
1974
      def formatter(keys):
1975
        return utils.CommaJoin(sorted(map(repr, keys))) if keys else "(none)"
1976

    
1977
      #Lose the values.
1978
      params_public = set(params_public)
1979
      params_private = set(params_private)
1980
      params_secret = set(params_secret)
1981

    
1982
      msg = """Cannot assign multiple values to OS parameters.
1983

1984
      Conflicting OS parameters that would have been set by this operation:
1985
      - at public visibility:  {public}
1986
      - at private visibility: {private}
1987
      - at secret visibility:  {secret}
1988
      """.format(dupes=formatter(duplicate_keys),
1989
                 public=formatter(params_public & duplicate_keys),
1990
                 private=formatter(params_private & duplicate_keys),
1991
                 secret=formatter(params_secret & duplicate_keys))
1992
      raise errors.OpPrereqError(msg)
1993

    
1994
  @staticmethod
1995
  def SimpleFillHvState(hv_state):
1996
    """Fill an hv_state sub dict with cluster defaults.
1997

1998
    """
1999
    return FillDict(constants.HVST_DEFAULTS, hv_state)
2000

    
2001
  @staticmethod
2002
  def SimpleFillDiskState(disk_state):
2003
    """Fill an disk_state sub dict with cluster defaults.
2004

2005
    """
2006
    return FillDict(constants.DS_DEFAULTS, disk_state)
2007

    
2008
  def FillND(self, node, nodegroup):
2009
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
2010

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

2017
    """
2018
    return self.SimpleFillND(nodegroup.FillND(node))
2019

    
2020
  def FillNDGroup(self, nodegroup):
2021
    """Return filled out ndparams for just L{objects.NodeGroup}
2022

2023
    @type nodegroup: L{objects.NodeGroup}
2024
    @param nodegroup: A Node object to fill
2025
    @return a copy of the node group's ndparams with defaults filled
2026

2027
    """
2028
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
2029

    
2030
  def SimpleFillND(self, ndparams):
2031
    """Fill a given ndparams dict with defaults.
2032

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

2039
    """
2040
    return FillDict(self.ndparams, ndparams)
2041

    
2042
  def SimpleFillIPolicy(self, ipolicy):
2043
    """ Fill instance policy dict with defaults.
2044

2045
    @type ipolicy: dict
2046
    @param ipolicy: the dict to fill
2047
    @rtype: dict
2048
    @return: a copy of passed ipolicy with missing keys filled from
2049
      the cluster defaults
2050

2051
    """
2052
    return FillIPolicy(self.ipolicy, ipolicy)
2053

    
2054
  def IsDiskTemplateEnabled(self, disk_template):
2055
    """Checks if a particular disk template is enabled.
2056

2057
    """
2058
    return utils.storage.IsDiskTemplateEnabled(
2059
        disk_template, self.enabled_disk_templates)
2060

    
2061
  def IsFileStorageEnabled(self):
2062
    """Checks if file storage is enabled.
2063

2064
    """
2065
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
2066

    
2067
  def IsSharedFileStorageEnabled(self):
2068
    """Checks if shared file storage is enabled.
2069

2070
    """
2071
    return utils.storage.IsSharedFileStorageEnabled(
2072
        self.enabled_disk_templates)
2073

    
2074

    
2075
class BlockDevStatus(ConfigObject):
2076
  """Config object representing the status of a block device."""
2077
  __slots__ = [
2078
    "dev_path",
2079
    "major",
2080
    "minor",
2081
    "sync_percent",
2082
    "estimated_time",
2083
    "is_degraded",
2084
    "ldisk_status",
2085
    ]
2086

    
2087

    
2088
class ImportExportStatus(ConfigObject):
2089
  """Config object representing the status of an import or export."""
2090
  __slots__ = [
2091
    "recent_output",
2092
    "listen_port",
2093
    "connected",
2094
    "progress_mbytes",
2095
    "progress_throughput",
2096
    "progress_eta",
2097
    "progress_percent",
2098
    "exit_status",
2099
    "error_message",
2100
    ] + _TIMESTAMPS
2101

    
2102

    
2103
class ImportExportOptions(ConfigObject):
2104
  """Options for import/export daemon
2105

2106
  @ivar key_name: X509 key name (None for cluster certificate)
2107
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
2108
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
2109
  @ivar magic: Used to ensure the connection goes to the right disk
2110
  @ivar ipv6: Whether to use IPv6
2111
  @ivar connect_timeout: Number of seconds for establishing connection
2112

2113
  """
2114
  __slots__ = [
2115
    "key_name",
2116
    "ca_pem",
2117
    "compress",
2118
    "magic",
2119
    "ipv6",
2120
    "connect_timeout",
2121
    ]
2122

    
2123

    
2124
class ConfdRequest(ConfigObject):
2125
  """Object holding a confd request.
2126

2127
  @ivar protocol: confd protocol version
2128
  @ivar type: confd query type
2129
  @ivar query: query request
2130
  @ivar rsalt: requested reply salt
2131

2132
  """
2133
  __slots__ = [
2134
    "protocol",
2135
    "type",
2136
    "query",
2137
    "rsalt",
2138
    ]
2139

    
2140

    
2141
class ConfdReply(ConfigObject):
2142
  """Object holding a confd reply.
2143

2144
  @ivar protocol: confd protocol version
2145
  @ivar status: reply status code (ok, error)
2146
  @ivar answer: confd query reply
2147
  @ivar serial: configuration serial number
2148

2149
  """
2150
  __slots__ = [
2151
    "protocol",
2152
    "status",
2153
    "answer",
2154
    "serial",
2155
    ]
2156

    
2157

    
2158
class QueryFieldDefinition(ConfigObject):
2159
  """Object holding a query field definition.
2160

2161
  @ivar name: Field name
2162
  @ivar title: Human-readable title
2163
  @ivar kind: Field type
2164
  @ivar doc: Human-readable description
2165

2166
  """
2167
  __slots__ = [
2168
    "name",
2169
    "title",
2170
    "kind",
2171
    "doc",
2172
    ]
2173

    
2174

    
2175
class _QueryResponseBase(ConfigObject):
2176
  __slots__ = [
2177
    "fields",
2178
    ]
2179

    
2180
  def ToDict(self, _with_private=False):
2181
    """Custom function for serializing.
2182

2183
    """
2184
    mydict = super(_QueryResponseBase, self).ToDict()
2185
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2186
    return mydict
2187

    
2188
  @classmethod
2189
  def FromDict(cls, val):
2190
    """Custom function for de-serializing.
2191

2192
    """
2193
    obj = super(_QueryResponseBase, cls).FromDict(val)
2194
    obj.fields = \
2195
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2196
    return obj
2197

    
2198

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

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

2205
  """
2206
  __slots__ = [
2207
    "data",
2208
    ]
2209

    
2210

    
2211
class QueryFieldsRequest(ConfigObject):
2212
  """Object holding a request for querying available fields.
2213

2214
  """
2215
  __slots__ = [
2216
    "what",
2217
    "fields",
2218
    ]
2219

    
2220

    
2221
class QueryFieldsResponse(_QueryResponseBase):
2222
  """Object holding the response to a query for fields.
2223

2224
  @ivar fields: List of L{QueryFieldDefinition} objects
2225

2226
  """
2227
  __slots__ = []
2228

    
2229

    
2230
class MigrationStatus(ConfigObject):
2231
  """Object holding the status of a migration.
2232

2233
  """
2234
  __slots__ = [
2235
    "status",
2236
    "transferred_ram",
2237
    "total_ram",
2238
    ]
2239

    
2240

    
2241
class InstanceConsole(ConfigObject):
2242
  """Object describing how to access the console of an instance.
2243

2244
  """
2245
  __slots__ = [
2246
    "instance",
2247
    "kind",
2248
    "message",
2249
    "host",
2250
    "port",
2251
    "user",
2252
    "command",
2253
    "display",
2254
    ]
2255

    
2256
  def Validate(self):
2257
    """Validates contents of this object.
2258

2259
    """
2260
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2261
    assert self.instance, "Missing instance name"
2262
    assert self.message or self.kind in [constants.CONS_SSH,
2263
                                         constants.CONS_SPICE,
2264
                                         constants.CONS_VNC]
2265
    assert self.host or self.kind == constants.CONS_MESSAGE
2266
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2267
                                      constants.CONS_SSH]
2268
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2269
                                      constants.CONS_SPICE,
2270
                                      constants.CONS_VNC]
2271
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2272
                                         constants.CONS_SPICE,
2273
                                         constants.CONS_VNC]
2274
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2275
                                         constants.CONS_SPICE,
2276
                                         constants.CONS_SSH]
2277
    return True
2278

    
2279

    
2280
class Network(TaggableObject):
2281
  """Object representing a network definition for ganeti.
2282

2283
  """
2284
  __slots__ = [
2285
    "name",
2286
    "serial_no",
2287
    "mac_prefix",
2288
    "network",
2289
    "network6",
2290
    "gateway",
2291
    "gateway6",
2292
    "reservations",
2293
    "ext_reservations",
2294
    ] + _TIMESTAMPS + _UUID
2295

    
2296
  def HooksDict(self, prefix=""):
2297
    """Export a dictionary used by hooks with a network's information.
2298

2299
    @type prefix: String
2300
    @param prefix: Prefix to prepend to the dict entries
2301

2302
    """
2303
    result = {
2304
      "%sNETWORK_NAME" % prefix: self.name,
2305
      "%sNETWORK_UUID" % prefix: self.uuid,
2306
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2307
    }
2308
    if self.network:
2309
      result["%sNETWORK_SUBNET" % prefix] = self.network
2310
    if self.gateway:
2311
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2312
    if self.network6:
2313
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2314
    if self.gateway6:
2315
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2316
    if self.mac_prefix:
2317
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2318

    
2319
    return result
2320

    
2321
  @classmethod
2322
  def FromDict(cls, val):
2323
    """Custom function for networks.
2324

2325
    Remove deprecated network_type and family.
2326

2327
    """
2328
    if "network_type" in val:
2329
      del val["network_type"]
2330
    if "family" in val:
2331
      del val["family"]
2332
    obj = super(Network, cls).FromDict(val)
2333
    return obj
2334

    
2335

    
2336
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2337
  """Simple wrapper over ConfigParse that allows serialization.
2338

2339
  This class is basically ConfigParser.SafeConfigParser with two
2340
  additional methods that allow it to serialize/unserialize to/from a
2341
  buffer.
2342

2343
  """
2344
  def Dumps(self):
2345
    """Dump this instance and return the string representation."""
2346
    buf = StringIO()
2347
    self.write(buf)
2348
    return buf.getvalue()
2349

    
2350
  @classmethod
2351
  def Loads(cls, data):
2352
    """Load data from a string."""
2353
    buf = StringIO(data)
2354
    cfp = cls()
2355
    cfp.readfp(buf)
2356
    return cfp
2357

    
2358

    
2359
class LvmPvInfo(ConfigObject):
2360
  """Information about an LVM physical volume (PV).
2361

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

    
2384
  def IsEmpty(self):
2385
    """Is this PV empty?
2386

2387
    """
2388
    return self.size <= (self.free + 1)
2389

    
2390
  def IsAllocatable(self):
2391
    """Is this PV allocatable?
2392

2393
    """
2394
    return ("a" in self.attributes)