Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 26e1312d

History | View | Annotate | Download (70.5 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 CreateOnSecondary(self):
532
    """Test if this device needs to be created on a secondary node."""
533
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
534

    
535
  def AssembleOnSecondary(self):
536
    """Test if this device needs to be assembled on a secondary node."""
537
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
538

    
539
  def OpenOnSecondary(self):
540
    """Test if this device needs to be opened on a secondary node."""
541
    return self.dev_type in (constants.DT_PLAIN,)
542

    
543
  def StaticDevPath(self):
544
    """Return the device path if this device type has a static one.
545

546
    Some devices (LVM for example) live always at the same /dev/ path,
547
    irrespective of their status. For such devices, we return this
548
    path, for others we return None.
549

550
    @warning: The path returned is not a normalized pathname; callers
551
        should check that it is a valid path.
552

553
    """
554
    if self.dev_type == constants.DT_PLAIN:
555
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
556
    elif self.dev_type == constants.DT_BLOCK:
557
      return self.logical_id[1]
558
    elif self.dev_type == constants.DT_RBD:
559
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
560
    return None
561

    
562
  def ChildrenNeeded(self):
563
    """Compute the needed number of children for activation.
564

565
    This method will return either -1 (all children) or a positive
566
    number denoting the minimum number of children needed for
567
    activation (only mirrored devices will usually return >=0).
568

569
    Currently, only DRBD8 supports diskless activation (therefore we
570
    return 0), for all other we keep the previous semantics and return
571
    -1.
572

573
    """
574
    if self.dev_type == constants.DT_DRBD8:
575
      return 0
576
    return -1
577

    
578
  def IsBasedOnDiskType(self, dev_type):
579
    """Check if the disk or its children are based on the given type.
580

581
    @type dev_type: L{constants.DTS_BLOCK}
582
    @param dev_type: the type to look for
583
    @rtype: boolean
584
    @return: boolean indicating if a device of the given type was found or not
585

586
    """
587
    if self.children:
588
      for child in self.children:
589
        if child.IsBasedOnDiskType(dev_type):
590
          return True
591
    return self.dev_type == dev_type
592

    
593
  def GetNodes(self, node_uuid):
594
    """This function returns the nodes this device lives on.
595

596
    Given the node on which the parent of the device lives on (or, in
597
    case of a top-level device, the primary node of the devices'
598
    instance), this function will return a list of nodes on which this
599
    devices needs to (or can) be assembled.
600

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

    
615
  def ComputeNodeTree(self, parent_node_uuid):
616
    """Compute the node/disk tree for this disk and its children.
617

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

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

    
650
  def ComputeGrowth(self, amount):
651
    """Compute the per-VG growth requirements.
652

653
    This only works for VG-based disks.
654

655
    @type amount: integer
656
    @param amount: the desired increase in (user-visible) disk space
657
    @rtype: dict
658
    @return: a dictionary of volume-groups and the required size
659

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

    
672
  def RecordGrow(self, amount):
673
    """Update the size of this disk after growth.
674

675
    This method recurses over the disks's children and updates their
676
    size correspondigly. The method needs to be kept in sync with the
677
    actual algorithms from bdev.
678

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

    
692
  def Update(self, size=None, mode=None, spindles=None):
693
    """Apply changes to size, spindles and mode.
694

695
    """
696
    if self.dev_type == constants.DT_DRBD8:
697
      if self.children:
698
        self.children[0].Update(size=size, mode=mode)
699
    else:
700
      assert not self.children
701

    
702
    if size is not None:
703
      self.size = size
704
    if mode is not None:
705
      self.mode = mode
706
    if spindles is not None:
707
      self.spindles = spindles
708

    
709
  def UnsetSize(self):
710
    """Sets recursively the size to zero for the disk and its children.
711

712
    """
713
    if self.children:
714
      for child in self.children:
715
        child.UnsetSize()
716
    self.size = 0
717

    
718
  def UpdateDynamicDiskParams(self, target_node_uuid, nodes_ip):
719
    """Updates the dynamic disk params for the given node.
720

721
    This is mainly used for drbd, which needs ip/port configuration.
722

723
    Arguments:
724
      - target_node_uuid: the node UUID we wish to configure for
725
      - nodes_ip: a mapping of node name to ip
726

727
    The target_node must exist in nodes_ip, and should be one of the
728
    nodes in the logical ID if this device is a DRBD device.
729

730
    """
731
    if self.children:
732
      for child in self.children:
733
        child.UpdateDynamicDiskParams(target_node_uuid, nodes_ip)
734

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

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

    
761
    self.dynamic_params = dyn_disk_params
762

    
763
  # pylint: disable=W0221
764
  def ToDict(self, include_dynamic_params=False,
765
             _with_private=False):
766
    """Disk-specific conversion to standard python types.
767

768
    This replaces the children lists of objects with lists of
769
    standard python types.
770

771
    """
772
    bo = super(Disk, self).ToDict()
773
    if not include_dynamic_params and "dynamic_params" in bo:
774
      del bo["dynamic_params"]
775

    
776
    for attr in ("children",):
777
      alist = bo.get(attr, None)
778
      if alist:
779
        bo[attr] = outils.ContainerToDicts(alist)
780
    return bo
781

    
782
  @classmethod
783
  def FromDict(cls, val):
784
    """Custom function for Disks
785

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

    
798
  def __str__(self):
799
    """Custom str() formatter for disks.
800

801
    """
802
    if self.dev_type == constants.DT_PLAIN:
803
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
804
    elif self.dev_type in constants.DTS_DRBD:
805
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
806
      val = "<DRBD8("
807

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

    
829
  def Verify(self):
830
    """Checks that this disk is correctly configured.
831

832
    """
833
    all_errors = []
834
    if self.mode not in constants.DISK_ACCESS_SET:
835
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
836
    return all_errors
837

    
838
  def UpgradeConfig(self):
839
    """Fill defaults for missing configuration values.
840

841
    """
842
    if self.children:
843
      for child in self.children:
844
        child.UpgradeConfig()
845

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

    
853
    # add here config upgrade for this disk
854

    
855
    # map of legacy device types (mapping differing LD constants to new
856
    # DT constants)
857
    LEG_DEV_TYPE_MAP = {"lvm": constants.DT_PLAIN, "drbd8": constants.DT_DRBD8}
858
    if self.dev_type in LEG_DEV_TYPE_MAP:
859
      self.dev_type = LEG_DEV_TYPE_MAP[self.dev_type]
860

    
861
  @staticmethod
862
  def ComputeLDParams(disk_template, disk_params):
863
    """Computes Logical Disk parameters from Disk Template parameters.
864

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

874
    """
875
    if disk_template not in constants.DISK_TEMPLATES:
876
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
877

    
878
    assert disk_template in disk_params
879

    
880
    result = list()
881
    dt_params = disk_params[disk_template]
882

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

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

    
905
      # metadata LV
906
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
907
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
908
        }))
909

    
910
    else:
911
      defaults = constants.DISK_LD_DEFAULTS[disk_template]
912
      values = {}
913
      for field in defaults:
914
        values[field] = dt_params[field]
915
      result.append(FillDict(defaults, values))
916

    
917
    return result
918

    
919

    
920
class InstancePolicy(ConfigObject):
921
  """Config object representing instance policy limits dictionary.
922

923
  Note that this object is not actually used in the config, it's just
924
  used as a placeholder for a few functions.
925

926
  """
927
  @classmethod
928
  def UpgradeDiskTemplates(cls, ipolicy, enabled_disk_templates):
929
    """Upgrades the ipolicy configuration."""
930
    if constants.IPOLICY_DTS in ipolicy:
931
      if not set(ipolicy[constants.IPOLICY_DTS]).issubset(
932
        set(enabled_disk_templates)):
933
        ipolicy[constants.IPOLICY_DTS] = list(
934
          set(ipolicy[constants.IPOLICY_DTS]) & set(enabled_disk_templates))
935

    
936
  @classmethod
937
  def CheckParameterSyntax(cls, ipolicy, check_std):
938
    """ Check the instance policy for validity.
939

940
    @type ipolicy: dict
941
    @param ipolicy: dictionary with min/max/std specs and policies
942
    @type check_std: bool
943
    @param check_std: Whether to check std value or just assume compliance
944
    @raise errors.ConfigurationError: when the policy is not legal
945

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

    
958
  @classmethod
959
  def _CheckIncompleteSpec(cls, spec, keyname):
960
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
961
    if missing_params:
962
      msg = ("Missing instance specs parameters for %s: %s" %
963
             (keyname, utils.CommaJoin(missing_params)))
964
      raise errors.ConfigurationError(msg)
965

    
966
  @classmethod
967
  def CheckISpecSyntax(cls, ipolicy, check_std):
968
    """Check the instance policy specs for validity.
969

970
    @type ipolicy: dict
971
    @param ipolicy: dictionary with min/max/std specs
972
    @type check_std: bool
973
    @param check_std: Whether to check std value or just assume compliance
974
    @raise errors.ConfigurationError: when specs are not valid
975

976
    """
977
    if constants.ISPECS_MINMAX not in ipolicy:
978
      # Nothing to check
979
      return
980

    
981
    if check_std and constants.ISPECS_STD not in ipolicy:
982
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
983
      raise errors.ConfigurationError(msg)
984
    stdspec = ipolicy.get(constants.ISPECS_STD)
985
    if check_std:
986
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
987

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

    
999
      spec_std_ok = True
1000
      for param in constants.ISPECS_PARAMETERS:
1001
        par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
1002
                                                           param, check_std)
1003
        spec_std_ok = spec_std_ok and par_std_ok
1004
      std_is_good = std_is_good or spec_std_ok
1005
    if not std_is_good:
1006
      raise errors.ConfigurationError("Invalid std specifications")
1007

    
1008
  @classmethod
1009
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
1010
    """Check the instance policy specs for validity on a given key.
1011

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

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

1029
    """
1030
    minspec = minmaxspecs[constants.ISPECS_MIN]
1031
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1032
    min_v = minspec[name]
1033
    max_v = maxspec[name]
1034

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

    
1045
  @classmethod
1046
  def CheckDiskTemplates(cls, disk_templates):
1047
    """Checks the disk templates for validity.
1048

1049
    """
1050
    if not disk_templates:
1051
      raise errors.ConfigurationError("Instance policy must contain" +
1052
                                      " at least one disk template")
1053
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1054
    if wrong:
1055
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1056
                                      utils.CommaJoin(wrong))
1057

    
1058
  @classmethod
1059
  def CheckParameter(cls, key, value):
1060
    """Checks a parameter.
1061

1062
    Currently we expect all parameters to be float values.
1063

1064
    """
1065
    try:
1066
      float(value)
1067
    except (TypeError, ValueError), err:
1068
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1069
                                      " '%s', error: %s" % (key, value, err))
1070

    
1071

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

    
1092
  def _ComputeSecondaryNodes(self):
1093
    """Compute the list of secondary nodes.
1094

1095
    This is a simple wrapper over _ComputeAllNodes.
1096

1097
    """
1098
    all_nodes = set(self._ComputeAllNodes())
1099
    all_nodes.discard(self.primary_node)
1100
    return tuple(all_nodes)
1101

    
1102
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1103
                             "List of names of secondary nodes")
1104

    
1105
  def _ComputeAllNodes(self):
1106
    """Compute the list of all nodes.
1107

1108
    Since the data is already there (in the drbd disks), keeping it as
1109
    a separate normal attribute is redundant and if not properly
1110
    synchronised can cause problems. Thus it's better to compute it
1111
    dynamically.
1112

1113
    """
1114
    def _Helper(nodes, device):
1115
      """Recursively computes nodes given a top device."""
1116
      if device.dev_type in constants.DTS_DRBD:
1117
        nodea, nodeb = device.logical_id[:2]
1118
        nodes.add(nodea)
1119
        nodes.add(nodeb)
1120
      if device.children:
1121
        for child in device.children:
1122
          _Helper(nodes, child)
1123

    
1124
    all_nodes = set()
1125
    all_nodes.add(self.primary_node)
1126
    for device in self.disks:
1127
      _Helper(all_nodes, device)
1128
    return tuple(all_nodes)
1129

    
1130
  all_nodes = property(_ComputeAllNodes, None, None,
1131
                       "List of names of all the nodes of the instance")
1132

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

1136
    This function figures out what logical volumes should belong on
1137
    which nodes, recursing through a device tree.
1138

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

1153
    """
1154
    if node_uuid is None:
1155
      node_uuid = self.primary_node
1156

    
1157
    if lvmap is None:
1158
      lvmap = {
1159
        node_uuid: [],
1160
        }
1161
      ret = lvmap
1162
    else:
1163
      if not node_uuid in lvmap:
1164
        lvmap[node_uuid] = []
1165
      ret = None
1166

    
1167
    if not devs:
1168
      devs = self.disks
1169

    
1170
    for dev in devs:
1171
      if dev.dev_type == constants.DT_PLAIN:
1172
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1173

    
1174
      elif dev.dev_type in constants.DTS_DRBD:
1175
        if dev.children:
1176
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1177
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1178

    
1179
      elif dev.children:
1180
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1181

    
1182
    return ret
1183

    
1184
  def FindDisk(self, idx):
1185
    """Find a disk given having a specified index.
1186

1187
    This is just a wrapper that does validation of the index.
1188

1189
    @type idx: int
1190
    @param idx: the disk index
1191
    @rtype: L{Disk}
1192
    @return: the corresponding disk
1193
    @raise errors.OpPrereqError: when the given index is not valid
1194

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

    
1207
  def ToDict(self, _with_private=False):
1208
    """Instance-specific conversion to standard python types.
1209

1210
    This replaces the children lists of objects with lists of standard
1211
    python types.
1212

1213
    """
1214
    bo = super(Instance, self).ToDict(_with_private=_with_private)
1215

    
1216
    if _with_private:
1217
      bo["osparams_private"] = self.osparams_private.Unprivate()
1218

    
1219
    for attr in "nics", "disks":
1220
      alist = bo.get(attr, None)
1221
      if alist:
1222
        nlist = outils.ContainerToDicts(alist)
1223
      else:
1224
        nlist = []
1225
      bo[attr] = nlist
1226
    return bo
1227

    
1228
  @classmethod
1229
  def FromDict(cls, val):
1230
    """Custom function for instances.
1231

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

    
1245
  def UpgradeConfig(self):
1246
    """Fill defaults for missing configuration values.
1247

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

    
1267

    
1268
class OS(ConfigObject):
1269
  """Config object representing an operating system.
1270

1271
  @type supported_parameters: list
1272
  @ivar supported_parameters: a list of tuples, name and description,
1273
      containing the supported parameters by this OS
1274

1275
  @type VARIANT_DELIM: string
1276
  @cvar VARIANT_DELIM: the variant delimiter
1277

1278
  """
1279
  __slots__ = [
1280
    "name",
1281
    "path",
1282
    "api_versions",
1283
    "create_script",
1284
    "export_script",
1285
    "import_script",
1286
    "rename_script",
1287
    "verify_script",
1288
    "supported_variants",
1289
    "supported_parameters",
1290
    ]
1291

    
1292
  VARIANT_DELIM = "+"
1293

    
1294
  @classmethod
1295
  def SplitNameVariant(cls, name):
1296
    """Splits the name into the proper name and variant.
1297

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

1303
    """
1304
    nv = name.split(cls.VARIANT_DELIM, 1)
1305
    if len(nv) == 1:
1306
      nv.append("")
1307
    return nv
1308

    
1309
  @classmethod
1310
  def GetName(cls, name):
1311
    """Returns the proper name of the os (without the variant).
1312

1313
    @param name: the OS (unprocessed) name
1314

1315
    """
1316
    return cls.SplitNameVariant(name)[0]
1317

    
1318
  @classmethod
1319
  def GetVariant(cls, name):
1320
    """Returns the variant the os (without the base name).
1321

1322
    @param name: the OS (unprocessed) name
1323

1324
    """
1325
    return cls.SplitNameVariant(name)[1]
1326

    
1327

    
1328
class ExtStorage(ConfigObject):
1329
  """Config object representing an External Storage Provider.
1330

1331
  """
1332
  __slots__ = [
1333
    "name",
1334
    "path",
1335
    "create_script",
1336
    "remove_script",
1337
    "grow_script",
1338
    "attach_script",
1339
    "detach_script",
1340
    "setinfo_script",
1341
    "verify_script",
1342
    "supported_parameters",
1343
    ]
1344

    
1345

    
1346
class NodeHvState(ConfigObject):
1347
  """Hypvervisor state on a node.
1348

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

1358
  """
1359
  __slots__ = [
1360
    "mem_total",
1361
    "mem_node",
1362
    "mem_hv",
1363
    "mem_inst",
1364
    "cpu_total",
1365
    "cpu_node",
1366
    ] + _TIMESTAMPS
1367

    
1368

    
1369
class NodeDiskState(ConfigObject):
1370
  """Disk state on a node.
1371

1372
  """
1373
  __slots__ = [
1374
    "total",
1375
    "reserved",
1376
    "overhead",
1377
    ] + _TIMESTAMPS
1378

    
1379

    
1380
class Node(TaggableObject):
1381
  """Config object representing a node.
1382

1383
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1384
  @ivar hv_state_static: Hypervisor state overriden by user
1385
  @ivar disk_state: Disk state (e.g. free space)
1386
  @ivar disk_state_static: Disk state overriden by user
1387

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

    
1408
  def UpgradeConfig(self):
1409
    """Fill defaults for missing configuration values.
1410

1411
    """
1412
    # pylint: disable=E0203
1413
    # because these are "defined" via slots, not manually
1414
    if self.master_capable is None:
1415
      self.master_capable = True
1416

    
1417
    if self.vm_capable is None:
1418
      self.vm_capable = True
1419

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

    
1429
    if self.powered is None:
1430
      self.powered = True
1431

    
1432
  def ToDict(self, _with_private=False):
1433
    """Custom function for serializing.
1434

1435
    """
1436
    data = super(Node, self).ToDict(_with_private=_with_private)
1437

    
1438
    hv_state = data.get("hv_state", None)
1439
    if hv_state is not None:
1440
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1441

    
1442
    disk_state = data.get("disk_state", None)
1443
    if disk_state is not None:
1444
      data["disk_state"] = \
1445
        dict((key, outils.ContainerToDicts(value))
1446
             for (key, value) in disk_state.items())
1447

    
1448
    return data
1449

    
1450
  @classmethod
1451
  def FromDict(cls, val):
1452
    """Custom function for deserializing.
1453

1454
    """
1455
    obj = super(Node, cls).FromDict(val)
1456

    
1457
    if obj.hv_state is not None:
1458
      obj.hv_state = \
1459
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1460

    
1461
    if obj.disk_state is not None:
1462
      obj.disk_state = \
1463
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1464
             for (key, value) in obj.disk_state.items())
1465

    
1466
    return obj
1467

    
1468

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

    
1484
  def ToDict(self, _with_private=False):
1485
    """Custom function for nodegroup.
1486

1487
    This discards the members object, which gets recalculated and is only kept
1488
    in memory.
1489

1490
    """
1491
    mydict = super(NodeGroup, self).ToDict(_with_private=_with_private)
1492
    del mydict["members"]
1493
    return mydict
1494

    
1495
  @classmethod
1496
  def FromDict(cls, val):
1497
    """Custom function for nodegroup.
1498

1499
    The members slot is initialized to an empty list, upon deserialization.
1500

1501
    """
1502
    obj = super(NodeGroup, cls).FromDict(val)
1503
    obj.members = []
1504
    return obj
1505

    
1506
  def UpgradeConfig(self):
1507
    """Fill defaults for missing configuration values.
1508

1509
    """
1510
    if self.ndparams is None:
1511
      self.ndparams = {}
1512

    
1513
    if self.serial_no is None:
1514
      self.serial_no = 1
1515

    
1516
    if self.alloc_policy is None:
1517
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1518

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

    
1524
    if self.diskparams is None:
1525
      self.diskparams = {}
1526
    if self.ipolicy is None:
1527
      self.ipolicy = MakeEmptyIPolicy()
1528

    
1529
    if self.networks is None:
1530
      self.networks = {}
1531

    
1532
  def FillND(self, node):
1533
    """Return filled out ndparams for L{objects.Node}
1534

1535
    @type node: L{objects.Node}
1536
    @param node: A Node object to fill
1537
    @return a copy of the node's ndparams with defaults filled
1538

1539
    """
1540
    return self.SimpleFillND(node.ndparams)
1541

    
1542
  def SimpleFillND(self, ndparams):
1543
    """Fill a given ndparams dict with defaults.
1544

1545
    @type ndparams: dict
1546
    @param ndparams: the dict to fill
1547
    @rtype: dict
1548
    @return: a copy of the passed in ndparams with missing keys filled
1549
        from the node group defaults
1550

1551
    """
1552
    return FillDict(self.ndparams, ndparams)
1553

    
1554

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

    
1607
  def UpgradeConfig(self):
1608
    """Fill defaults for missing configuration values.
1609

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

    
1624
    if self.os_hvp is None:
1625
      self.os_hvp = {}
1626

    
1627
    if self.osparams is None:
1628
      self.osparams = {}
1629
    # osparams_private_cluster added in 2.12
1630
    if self.osparams_private_cluster is None:
1631
      self.osparams_private_cluster = {}
1632

    
1633
    self.ndparams = UpgradeNDParams(self.ndparams)
1634

    
1635
    self.beparams = UpgradeGroupedParams(self.beparams,
1636
                                         constants.BEC_DEFAULTS)
1637
    for beparams_group in self.beparams:
1638
      UpgradeBeParams(self.beparams[beparams_group])
1639

    
1640
    migrate_default_bridge = not self.nicparams
1641
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1642
                                          constants.NICC_DEFAULTS)
1643
    if migrate_default_bridge:
1644
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1645
        self.default_bridge
1646

    
1647
    if self.modify_etc_hosts is None:
1648
      self.modify_etc_hosts = True
1649

    
1650
    if self.modify_ssh_setup is None:
1651
      self.modify_ssh_setup = True
1652

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

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

    
1667
    # maintain_node_health added after 2.1.1
1668
    if self.maintain_node_health is None:
1669
      self.maintain_node_health = False
1670

    
1671
    if self.uid_pool is None:
1672
      self.uid_pool = []
1673

    
1674
    if self.default_iallocator is None:
1675
      self.default_iallocator = ""
1676

    
1677
    if self.default_iallocator_params is None:
1678
      self.default_iallocator_params = {}
1679

    
1680
    # reserved_lvs added before 2.2
1681
    if self.reserved_lvs is None:
1682
      self.reserved_lvs = []
1683

    
1684
    # hidden and blacklisted operating systems added before 2.2.1
1685
    if self.hidden_os is None:
1686
      self.hidden_os = []
1687

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

    
1691
    # primary_ip_family added before 2.3
1692
    if self.primary_ip_family is None:
1693
      self.primary_ip_family = AF_INET
1694

    
1695
    if self.master_netmask is None:
1696
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1697
      self.master_netmask = ipcls.iplen
1698

    
1699
    if self.prealloc_wipe_disks is None:
1700
      self.prealloc_wipe_disks = False
1701

    
1702
    # shared_file_storage_dir added before 2.5
1703
    if self.shared_file_storage_dir is None:
1704
      self.shared_file_storage_dir = ""
1705

    
1706
    # gluster_storage_dir added in 2.11
1707
    if self.gluster_storage_dir is None:
1708
      self.gluster_storage_dir = ""
1709

    
1710
    if self.use_external_mip_script is None:
1711
      self.use_external_mip_script = False
1712

    
1713
    if self.diskparams:
1714
      self.diskparams = UpgradeDiskParams(self.diskparams)
1715
    else:
1716
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1717

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

    
1733
    if self.candidate_certs is None:
1734
      self.candidate_certs = {}
1735

    
1736
    if self.max_running_jobs is None:
1737
      self.max_running_jobs = constants.LUXID_MAXIMAL_RUNNING_JOBS_DEFAULT
1738

    
1739
    if self.instance_communication_network is None:
1740
      self.instance_communication_network = ""
1741

    
1742
  @property
1743
  def primary_hypervisor(self):
1744
    """The first hypervisor is the primary.
1745

1746
    Useful, for example, for L{Node}'s hv/disk state.
1747

1748
    """
1749
    return self.enabled_hypervisors[0]
1750

    
1751
  def ToDict(self, _with_private=False):
1752
    """Custom function for cluster.
1753

1754
    """
1755
    mydict = super(Cluster, self).ToDict(_with_private=_with_private)
1756

    
1757
    # Explicitly save private parameters.
1758
    if _with_private:
1759
      for os in mydict["osparams_private_cluster"]:
1760
        mydict["osparams_private_cluster"][os] = \
1761
          self.osparams_private_cluster[os].Unprivate()
1762

    
1763
    if self.tcpudp_port_pool is None:
1764
      tcpudp_port_pool = []
1765
    else:
1766
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1767

    
1768
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1769

    
1770
    return mydict
1771

    
1772
  @classmethod
1773
  def FromDict(cls, val):
1774
    """Custom function for cluster.
1775

1776
    """
1777
    obj = super(Cluster, cls).FromDict(val)
1778

    
1779
    if obj.tcpudp_port_pool is None:
1780
      obj.tcpudp_port_pool = set()
1781
    elif not isinstance(obj.tcpudp_port_pool, set):
1782
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1783

    
1784
    return obj
1785

    
1786
  def SimpleFillDP(self, diskparams):
1787
    """Fill a given diskparams dict with cluster defaults.
1788

1789
    @param diskparams: The diskparams
1790
    @return: The defaults dict
1791

1792
    """
1793
    return FillDiskParams(self.diskparams, diskparams)
1794

    
1795
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1796
    """Get the default hypervisor parameters for the cluster.
1797

1798
    @param hypervisor: the hypervisor name
1799
    @param os_name: if specified, we'll also update the defaults for this OS
1800
    @param skip_keys: if passed, list of keys not to use
1801
    @return: the defaults dict
1802

1803
    """
1804
    if skip_keys is None:
1805
      skip_keys = []
1806

    
1807
    fill_stack = [self.hvparams.get(hypervisor, {})]
1808
    if os_name is not None:
1809
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1810
      fill_stack.append(os_hvp)
1811

    
1812
    ret_dict = {}
1813
    for o_dict in fill_stack:
1814
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1815

    
1816
    return ret_dict
1817

    
1818
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1819
    """Fill a given hvparams dict with cluster defaults.
1820

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

1832
    """
1833
    if skip_globals:
1834
      skip_keys = constants.HVC_GLOBALS
1835
    else:
1836
      skip_keys = []
1837

    
1838
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1839
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1840

    
1841
  def FillHV(self, instance, skip_globals=False):
1842
    """Fill an instance's hvparams dict with cluster defaults.
1843

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

1853
    """
1854
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1855
                             instance.hvparams, skip_globals)
1856

    
1857
  def SimpleFillBE(self, beparams):
1858
    """Fill a given beparams dict with cluster defaults.
1859

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

1866
    """
1867
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1868

    
1869
  def FillBE(self, instance):
1870
    """Fill an instance's beparams dict with cluster defaults.
1871

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

1878
    """
1879
    return self.SimpleFillBE(instance.beparams)
1880

    
1881
  def SimpleFillNIC(self, nicparams):
1882
    """Fill a given nicparams dict with cluster defaults.
1883

1884
    @type nicparams: dict
1885
    @param nicparams: the dict to fill
1886
    @rtype: dict
1887
    @return: a copy of the passed in nicparams with missing keys filled
1888
        from the cluster defaults
1889

1890
    """
1891
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1892

    
1893
  def SimpleFillOS(self, os_name,
1894
                    os_params_public,
1895
                    os_params_private=None,
1896
                    os_params_secret=None):
1897
    """Fill an instance's osparams dict with cluster defaults.
1898

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

1920
    """
1921
    name_only = os_name.split("+", 1)[0]
1922

    
1923
    defaults_base_public = self.osparams.get(name_only, {})
1924
    defaults_public = FillDict(defaults_base_public,
1925
                               self.osparams.get(os_name, {}))
1926
    params_public = FillDict(defaults_public, os_params_public)
1927

    
1928
    if os_params_private is not None:
1929
      defaults_base_private = self.osparams_private_cluster.get(name_only, {})
1930
      defaults_private = FillDict(defaults_base_private,
1931
                                  self.osparams_private_cluster.get(os_name,
1932
                                                                    {}))
1933
      params_private = FillDict(defaults_private, os_params_private)
1934
    else:
1935
      params_private = {}
1936

    
1937
    if os_params_secret is not None:
1938
      # There can't be default secret settings, so there's nothing to be done.
1939
      params_secret = os_params_secret
1940
    else:
1941
      params_secret = {}
1942

    
1943
    # Enforce that the set of keys be distinct:
1944
    duplicate_keys = utils.GetRepeatedKeys(params_public,
1945
                                           params_private,
1946
                                           params_secret)
1947
    if not duplicate_keys:
1948

    
1949
      # Actually update them:
1950
      params_public.update(params_private)
1951
      params_public.update(params_secret)
1952

    
1953
      return params_public
1954

    
1955
    else:
1956

    
1957
      def formatter(keys):
1958
        return utils.CommaJoin(sorted(map(repr, keys))) if keys else "(none)"
1959

    
1960
      #Lose the values.
1961
      params_public = set(params_public)
1962
      params_private = set(params_private)
1963
      params_secret = set(params_secret)
1964

    
1965
      msg = """Cannot assign multiple values to OS parameters.
1966

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

    
1977
  @staticmethod
1978
  def SimpleFillHvState(hv_state):
1979
    """Fill an hv_state sub dict with cluster defaults.
1980

1981
    """
1982
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1983

    
1984
  @staticmethod
1985
  def SimpleFillDiskState(disk_state):
1986
    """Fill an disk_state sub dict with cluster defaults.
1987

1988
    """
1989
    return FillDict(constants.DS_DEFAULTS, disk_state)
1990

    
1991
  def FillND(self, node, nodegroup):
1992
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1993

1994
    @type node: L{objects.Node}
1995
    @param node: A Node object to fill
1996
    @type nodegroup: L{objects.NodeGroup}
1997
    @param nodegroup: A Node object to fill
1998
    @return a copy of the node's ndparams with defaults filled
1999

2000
    """
2001
    return self.SimpleFillND(nodegroup.FillND(node))
2002

    
2003
  def FillNDGroup(self, nodegroup):
2004
    """Return filled out ndparams for just L{objects.NodeGroup}
2005

2006
    @type nodegroup: L{objects.NodeGroup}
2007
    @param nodegroup: A Node object to fill
2008
    @return a copy of the node group's ndparams with defaults filled
2009

2010
    """
2011
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
2012

    
2013
  def SimpleFillND(self, ndparams):
2014
    """Fill a given ndparams dict with defaults.
2015

2016
    @type ndparams: dict
2017
    @param ndparams: the dict to fill
2018
    @rtype: dict
2019
    @return: a copy of the passed in ndparams with missing keys filled
2020
        from the cluster defaults
2021

2022
    """
2023
    return FillDict(self.ndparams, ndparams)
2024

    
2025
  def SimpleFillIPolicy(self, ipolicy):
2026
    """ Fill instance policy dict with defaults.
2027

2028
    @type ipolicy: dict
2029
    @param ipolicy: the dict to fill
2030
    @rtype: dict
2031
    @return: a copy of passed ipolicy with missing keys filled from
2032
      the cluster defaults
2033

2034
    """
2035
    return FillIPolicy(self.ipolicy, ipolicy)
2036

    
2037
  def IsDiskTemplateEnabled(self, disk_template):
2038
    """Checks if a particular disk template is enabled.
2039

2040
    """
2041
    return utils.storage.IsDiskTemplateEnabled(
2042
        disk_template, self.enabled_disk_templates)
2043

    
2044
  def IsFileStorageEnabled(self):
2045
    """Checks if file storage is enabled.
2046

2047
    """
2048
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
2049

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

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

    
2057

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

    
2070

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

    
2085

    
2086
class ImportExportOptions(ConfigObject):
2087
  """Options for import/export daemon
2088

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

2096
  """
2097
  __slots__ = [
2098
    "key_name",
2099
    "ca_pem",
2100
    "compress",
2101
    "magic",
2102
    "ipv6",
2103
    "connect_timeout",
2104
    ]
2105

    
2106

    
2107
class ConfdRequest(ConfigObject):
2108
  """Object holding a confd request.
2109

2110
  @ivar protocol: confd protocol version
2111
  @ivar type: confd query type
2112
  @ivar query: query request
2113
  @ivar rsalt: requested reply salt
2114

2115
  """
2116
  __slots__ = [
2117
    "protocol",
2118
    "type",
2119
    "query",
2120
    "rsalt",
2121
    ]
2122

    
2123

    
2124
class ConfdReply(ConfigObject):
2125
  """Object holding a confd reply.
2126

2127
  @ivar protocol: confd protocol version
2128
  @ivar status: reply status code (ok, error)
2129
  @ivar answer: confd query reply
2130
  @ivar serial: configuration serial number
2131

2132
  """
2133
  __slots__ = [
2134
    "protocol",
2135
    "status",
2136
    "answer",
2137
    "serial",
2138
    ]
2139

    
2140

    
2141
class QueryFieldDefinition(ConfigObject):
2142
  """Object holding a query field definition.
2143

2144
  @ivar name: Field name
2145
  @ivar title: Human-readable title
2146
  @ivar kind: Field type
2147
  @ivar doc: Human-readable description
2148

2149
  """
2150
  __slots__ = [
2151
    "name",
2152
    "title",
2153
    "kind",
2154
    "doc",
2155
    ]
2156

    
2157

    
2158
class _QueryResponseBase(ConfigObject):
2159
  __slots__ = [
2160
    "fields",
2161
    ]
2162

    
2163
  def ToDict(self, _with_private=False):
2164
    """Custom function for serializing.
2165

2166
    """
2167
    mydict = super(_QueryResponseBase, self).ToDict()
2168
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2169
    return mydict
2170

    
2171
  @classmethod
2172
  def FromDict(cls, val):
2173
    """Custom function for de-serializing.
2174

2175
    """
2176
    obj = super(_QueryResponseBase, cls).FromDict(val)
2177
    obj.fields = \
2178
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2179
    return obj
2180

    
2181

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

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

2188
  """
2189
  __slots__ = [
2190
    "data",
2191
    ]
2192

    
2193

    
2194
class QueryFieldsRequest(ConfigObject):
2195
  """Object holding a request for querying available fields.
2196

2197
  """
2198
  __slots__ = [
2199
    "what",
2200
    "fields",
2201
    ]
2202

    
2203

    
2204
class QueryFieldsResponse(_QueryResponseBase):
2205
  """Object holding the response to a query for fields.
2206

2207
  @ivar fields: List of L{QueryFieldDefinition} objects
2208

2209
  """
2210
  __slots__ = []
2211

    
2212

    
2213
class MigrationStatus(ConfigObject):
2214
  """Object holding the status of a migration.
2215

2216
  """
2217
  __slots__ = [
2218
    "status",
2219
    "transferred_ram",
2220
    "total_ram",
2221
    ]
2222

    
2223

    
2224
class InstanceConsole(ConfigObject):
2225
  """Object describing how to access the console of an instance.
2226

2227
  """
2228
  __slots__ = [
2229
    "instance",
2230
    "kind",
2231
    "message",
2232
    "host",
2233
    "port",
2234
    "user",
2235
    "command",
2236
    "display",
2237
    ]
2238

    
2239
  def Validate(self):
2240
    """Validates contents of this object.
2241

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

    
2262

    
2263
class Network(TaggableObject):
2264
  """Object representing a network definition for ganeti.
2265

2266
  """
2267
  __slots__ = [
2268
    "name",
2269
    "serial_no",
2270
    "mac_prefix",
2271
    "network",
2272
    "network6",
2273
    "gateway",
2274
    "gateway6",
2275
    "reservations",
2276
    "ext_reservations",
2277
    ] + _TIMESTAMPS + _UUID
2278

    
2279
  def HooksDict(self, prefix=""):
2280
    """Export a dictionary used by hooks with a network's information.
2281

2282
    @type prefix: String
2283
    @param prefix: Prefix to prepend to the dict entries
2284

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

    
2302
    return result
2303

    
2304
  @classmethod
2305
  def FromDict(cls, val):
2306
    """Custom function for networks.
2307

2308
    Remove deprecated network_type and family.
2309

2310
    """
2311
    if "network_type" in val:
2312
      del val["network_type"]
2313
    if "family" in val:
2314
      del val["family"]
2315
    obj = super(Network, cls).FromDict(val)
2316
    return obj
2317

    
2318

    
2319
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2320
  """Simple wrapper over ConfigParse that allows serialization.
2321

2322
  This class is basically ConfigParser.SafeConfigParser with two
2323
  additional methods that allow it to serialize/unserialize to/from a
2324
  buffer.
2325

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

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

    
2341

    
2342
class LvmPvInfo(ConfigObject):
2343
  """Information about an LVM physical volume (PV).
2344

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

    
2367
  def IsEmpty(self):
2368
    """Is this PV empty?
2369

2370
    """
2371
    return self.size <= (self.free + 1)
2372

    
2373
  def IsAllocatable(self):
2374
    """Is this PV allocatable?
2375

2376
    """
2377
    return ("a" in self.attributes)