Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 31d3b918

History | View | Annotate | Download (70.1 kB)

1
#
2
#
3

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

    
21

    
22
"""Transportable objects for Ganeti.
23

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

27
"""
28

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

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

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

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

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

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

    
52
from socket import AF_INET
53

    
54

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

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

    
61

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

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

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

    
83

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

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

    
97

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

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

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

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

    
110

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

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

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

    
127

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

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

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

    
141

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

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

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

    
156
  return result
157

    
158

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

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

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

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

    
177

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

181
  """
182
  return {}
183

    
184

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

188
  It has the following properties:
189

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

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

197
  """
198
  __slots__ = []
199

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

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

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

215
    """
216

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

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

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

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

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

    
243
  __getstate__ = ToDict
244

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

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

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

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

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

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

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

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

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

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

287
    """
288
    pass
289

    
290

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

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

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

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

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

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

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

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

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

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

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

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

349
    This replaces the tags set with a list.
350

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

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

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

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

    
369

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

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

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

    
388

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

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

404
    This just replaces the list of instances, nodes and the cluster
405
    with standard python types.
406

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

    
413
    return mydict
414

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

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

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

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

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

    
445
  def UpgradeConfig(self):
446
    """Fill defaults for missing configuration values.
447

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

    
469
  def _UpgradeEnabledDiskTemplates(self):
470
    """Upgrade the cluster's enabled disk templates by inspecting the currently
471
       enabled and/or used disk templates.
472

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

    
493

    
494
class NIC(ConfigObject):
495
  """Config object representing a network card."""
496
  __slots__ = ["name", "mac", "ip", "network",
497
               "nicparams", "netinfo", "pci"] + _UUID
498

    
499
  @classmethod
500
  def CheckParameterSyntax(cls, nicparams):
501
    """Check the given parameters for validity.
502

503
    @type nicparams:  dict
504
    @param nicparams: dictionary with parameter names/value
505
    @raise errors.ConfigurationError: when a parameter is not valid
506

507
    """
508
    mode = nicparams[constants.NIC_MODE]
509
    if (mode not in constants.NIC_VALID_MODES and
510
        mode != constants.VALUE_AUTO):
511
      raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
512

    
513
    if (mode == constants.NIC_MODE_BRIDGED and
514
        not nicparams[constants.NIC_LINK]):
515
      raise errors.ConfigurationError("Missing bridged NIC link")
516

    
517

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

    
526
  def CreateOnSecondary(self):
527
    """Test if this device needs to be created on a secondary node."""
528
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
529

    
530
  def AssembleOnSecondary(self):
531
    """Test if this device needs to be assembled on a secondary node."""
532
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
533

    
534
  def OpenOnSecondary(self):
535
    """Test if this device needs to be opened on a secondary node."""
536
    return self.dev_type in (constants.DT_PLAIN,)
537

    
538
  def StaticDevPath(self):
539
    """Return the device path if this device type has a static one.
540

541
    Some devices (LVM for example) live always at the same /dev/ path,
542
    irrespective of their status. For such devices, we return this
543
    path, for others we return None.
544

545
    @warning: The path returned is not a normalized pathname; callers
546
        should check that it is a valid path.
547

548
    """
549
    if self.dev_type == constants.DT_PLAIN:
550
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
551
    elif self.dev_type == constants.DT_BLOCK:
552
      return self.logical_id[1]
553
    elif self.dev_type == constants.DT_RBD:
554
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
555
    return None
556

    
557
  def ChildrenNeeded(self):
558
    """Compute the needed number of children for activation.
559

560
    This method will return either -1 (all children) or a positive
561
    number denoting the minimum number of children needed for
562
    activation (only mirrored devices will usually return >=0).
563

564
    Currently, only DRBD8 supports diskless activation (therefore we
565
    return 0), for all other we keep the previous semantics and return
566
    -1.
567

568
    """
569
    if self.dev_type == constants.DT_DRBD8:
570
      return 0
571
    return -1
572

    
573
  def IsBasedOnDiskType(self, dev_type):
574
    """Check if the disk or its children are based on the given type.
575

576
    @type dev_type: L{constants.DTS_BLOCK}
577
    @param dev_type: the type to look for
578
    @rtype: boolean
579
    @return: boolean indicating if a device of the given type was found or not
580

581
    """
582
    if self.children:
583
      for child in self.children:
584
        if child.IsBasedOnDiskType(dev_type):
585
          return True
586
    return self.dev_type == dev_type
587

    
588
  def GetNodes(self, node_uuid):
589
    """This function returns the nodes this device lives on.
590

591
    Given the node on which the parent of the device lives on (or, in
592
    case of a top-level device, the primary node of the devices'
593
    instance), this function will return a list of nodes on which this
594
    devices needs to (or can) be assembled.
595

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

    
610
  def ComputeNodeTree(self, parent_node_uuid):
611
    """Compute the node/disk tree for this disk and its children.
612

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

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

    
645
  def ComputeGrowth(self, amount):
646
    """Compute the per-VG growth requirements.
647

648
    This only works for VG-based disks.
649

650
    @type amount: integer
651
    @param amount: the desired increase in (user-visible) disk space
652
    @rtype: dict
653
    @return: a dictionary of volume-groups and the required size
654

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

    
667
  def RecordGrow(self, amount):
668
    """Update the size of this disk after growth.
669

670
    This method recurses over the disks's children and updates their
671
    size correspondigly. The method needs to be kept in sync with the
672
    actual algorithms from bdev.
673

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

    
687
  def Update(self, size=None, mode=None, spindles=None):
688
    """Apply changes to size, spindles and mode.
689

690
    """
691
    if self.dev_type == constants.DT_DRBD8:
692
      if self.children:
693
        self.children[0].Update(size=size, mode=mode)
694
    else:
695
      assert not self.children
696

    
697
    if size is not None:
698
      self.size = size
699
    if mode is not None:
700
      self.mode = mode
701
    if spindles is not None:
702
      self.spindles = spindles
703

    
704
  def UnsetSize(self):
705
    """Sets recursively the size to zero for the disk and its children.
706

707
    """
708
    if self.children:
709
      for child in self.children:
710
        child.UnsetSize()
711
    self.size = 0
712

    
713
  def UpdateDynamicDiskParams(self, target_node_uuid, nodes_ip):
714
    """Updates the dynamic disk params for the given node.
715

716
    This is mainly used for drbd, which needs ip/port configuration.
717

718
    Arguments:
719
      - target_node_uuid: the node UUID we wish to configure for
720
      - nodes_ip: a mapping of node name to ip
721

722
    The target_node must exist in nodes_ip, and should be one of the
723
    nodes in the logical ID if this device is a DRBD device.
724

725
    """
726
    if self.children:
727
      for child in self.children:
728
        child.UpdateDynamicDiskParams(target_node_uuid, nodes_ip)
729

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

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

    
756
    self.dynamic_params = dyn_disk_params
757

    
758
  # pylint: disable=W0221
759
  def ToDict(self, include_dynamic_params=False,
760
             _with_private=False):
761
    """Disk-specific conversion to standard python types.
762

763
    This replaces the children lists of objects with lists of
764
    standard python types.
765

766
    """
767
    bo = super(Disk, self).ToDict()
768
    if not include_dynamic_params and "dynamic_params" in bo:
769
      del bo["dynamic_params"]
770

    
771
    for attr in ("children",):
772
      alist = bo.get(attr, None)
773
      if alist:
774
        bo[attr] = outils.ContainerToDicts(alist)
775
    return bo
776

    
777
  @classmethod
778
  def FromDict(cls, val):
779
    """Custom function for Disks
780

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

    
793
  def __str__(self):
794
    """Custom str() formatter for disks.
795

796
    """
797
    if self.dev_type == constants.DT_PLAIN:
798
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
799
    elif self.dev_type in constants.DTS_DRBD:
800
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
801
      val = "<DRBD8("
802

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

    
824
  def Verify(self):
825
    """Checks that this disk is correctly configured.
826

827
    """
828
    all_errors = []
829
    if self.mode not in constants.DISK_ACCESS_SET:
830
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
831
    return all_errors
832

    
833
  def UpgradeConfig(self):
834
    """Fill defaults for missing configuration values.
835

836
    """
837
    if self.children:
838
      for child in self.children:
839
        child.UpgradeConfig()
840

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

    
848
    # add here config upgrade for this disk
849

    
850
    # map of legacy device types (mapping differing LD constants to new
851
    # DT constants)
852
    LEG_DEV_TYPE_MAP = {"lvm": constants.DT_PLAIN, "drbd8": constants.DT_DRBD8}
853
    if self.dev_type in LEG_DEV_TYPE_MAP:
854
      self.dev_type = LEG_DEV_TYPE_MAP[self.dev_type]
855

    
856
  @staticmethod
857
  def ComputeLDParams(disk_template, disk_params):
858
    """Computes Logical Disk parameters from Disk Template parameters.
859

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

869
    """
870
    if disk_template not in constants.DISK_TEMPLATES:
871
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
872

    
873
    assert disk_template in disk_params
874

    
875
    result = list()
876
    dt_params = disk_params[disk_template]
877

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

    
895
      # data LV
896
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
897
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
898
        }))
899

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

    
905
    else:
906
      defaults = constants.DISK_LD_DEFAULTS[disk_template]
907
      values = {}
908
      for field in defaults:
909
        values[field] = dt_params[field]
910
      result.append(FillDict(defaults, values))
911

    
912
    return result
913

    
914

    
915
class InstancePolicy(ConfigObject):
916
  """Config object representing instance policy limits dictionary.
917

918
  Note that this object is not actually used in the config, it's just
919
  used as a placeholder for a few functions.
920

921
  """
922
  @classmethod
923
  def UpgradeDiskTemplates(cls, ipolicy, enabled_disk_templates):
924
    """Upgrades the ipolicy configuration."""
925
    if constants.IPOLICY_DTS in ipolicy:
926
      if not set(ipolicy[constants.IPOLICY_DTS]).issubset(
927
        set(enabled_disk_templates)):
928
        ipolicy[constants.IPOLICY_DTS] = list(
929
          set(ipolicy[constants.IPOLICY_DTS]) & set(enabled_disk_templates))
930

    
931
  @classmethod
932
  def CheckParameterSyntax(cls, ipolicy, check_std):
933
    """ Check the instance policy for validity.
934

935
    @type ipolicy: dict
936
    @param ipolicy: dictionary with min/max/std specs and policies
937
    @type check_std: bool
938
    @param check_std: Whether to check std value or just assume compliance
939
    @raise errors.ConfigurationError: when the policy is not legal
940

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

    
953
  @classmethod
954
  def _CheckIncompleteSpec(cls, spec, keyname):
955
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
956
    if missing_params:
957
      msg = ("Missing instance specs parameters for %s: %s" %
958
             (keyname, utils.CommaJoin(missing_params)))
959
      raise errors.ConfigurationError(msg)
960

    
961
  @classmethod
962
  def CheckISpecSyntax(cls, ipolicy, check_std):
963
    """Check the instance policy specs for validity.
964

965
    @type ipolicy: dict
966
    @param ipolicy: dictionary with min/max/std specs
967
    @type check_std: bool
968
    @param check_std: Whether to check std value or just assume compliance
969
    @raise errors.ConfigurationError: when specs are not valid
970

971
    """
972
    if constants.ISPECS_MINMAX not in ipolicy:
973
      # Nothing to check
974
      return
975

    
976
    if check_std and constants.ISPECS_STD not in ipolicy:
977
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
978
      raise errors.ConfigurationError(msg)
979
    stdspec = ipolicy.get(constants.ISPECS_STD)
980
    if check_std:
981
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
982

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

    
994
      spec_std_ok = True
995
      for param in constants.ISPECS_PARAMETERS:
996
        par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
997
                                                           param, check_std)
998
        spec_std_ok = spec_std_ok and par_std_ok
999
      std_is_good = std_is_good or spec_std_ok
1000
    if not std_is_good:
1001
      raise errors.ConfigurationError("Invalid std specifications")
1002

    
1003
  @classmethod
1004
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
1005
    """Check the instance policy specs for validity on a given key.
1006

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

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

1024
    """
1025
    minspec = minmaxspecs[constants.ISPECS_MIN]
1026
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1027
    min_v = minspec[name]
1028
    max_v = maxspec[name]
1029

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

    
1040
  @classmethod
1041
  def CheckDiskTemplates(cls, disk_templates):
1042
    """Checks the disk templates for validity.
1043

1044
    """
1045
    if not disk_templates:
1046
      raise errors.ConfigurationError("Instance policy must contain" +
1047
                                      " at least one disk template")
1048
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1049
    if wrong:
1050
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1051
                                      utils.CommaJoin(wrong))
1052

    
1053
  @classmethod
1054
  def CheckParameter(cls, key, value):
1055
    """Checks a parameter.
1056

1057
    Currently we expect all parameters to be float values.
1058

1059
    """
1060
    try:
1061
      float(value)
1062
    except (TypeError, ValueError), err:
1063
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1064
                                      " '%s', error: %s" % (key, value, err))
1065

    
1066

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

    
1087
  def _ComputeSecondaryNodes(self):
1088
    """Compute the list of secondary nodes.
1089

1090
    This is a simple wrapper over _ComputeAllNodes.
1091

1092
    """
1093
    all_nodes = set(self._ComputeAllNodes())
1094
    all_nodes.discard(self.primary_node)
1095
    return tuple(all_nodes)
1096

    
1097
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1098
                             "List of names of secondary nodes")
1099

    
1100
  def _ComputeAllNodes(self):
1101
    """Compute the list of all nodes.
1102

1103
    Since the data is already there (in the drbd disks), keeping it as
1104
    a separate normal attribute is redundant and if not properly
1105
    synchronised can cause problems. Thus it's better to compute it
1106
    dynamically.
1107

1108
    """
1109
    def _Helper(nodes, device):
1110
      """Recursively computes nodes given a top device."""
1111
      if device.dev_type in constants.DTS_DRBD:
1112
        nodea, nodeb = device.logical_id[:2]
1113
        nodes.add(nodea)
1114
        nodes.add(nodeb)
1115
      if device.children:
1116
        for child in device.children:
1117
          _Helper(nodes, child)
1118

    
1119
    all_nodes = set()
1120
    all_nodes.add(self.primary_node)
1121
    for device in self.disks:
1122
      _Helper(all_nodes, device)
1123
    return tuple(all_nodes)
1124

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

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

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

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

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

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

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

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

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

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

    
1177
    return ret
1178

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1262

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

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

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

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

    
1287
  VARIANT_DELIM = "+"
1288

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

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

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

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

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

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

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

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

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

    
1322

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

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

    
1340

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

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

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

    
1363

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

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

    
1374

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

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

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

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

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

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

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

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

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

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

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

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

    
1443
    return data
1444

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

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

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

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

    
1461
    return obj
1462

    
1463

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1549

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1733
  @property
1734
  def primary_hypervisor(self):
1735
    """The first hypervisor is the primary.
1736

1737
    Useful, for example, for L{Node}'s hv/disk state.
1738

1739
    """
1740
    return self.enabled_hypervisors[0]
1741

    
1742
  def ToDict(self, _with_private=False):
1743
    """Custom function for cluster.
1744

1745
    """
1746
    mydict = super(Cluster, self).ToDict(_with_private=_with_private)
1747

    
1748
    # Explicitly save private parameters.
1749
    if _with_private:
1750
      for os in mydict["osparams_private_cluster"]:
1751
        mydict["osparams_private_cluster"][os] = \
1752
          self.osparams_private_cluster[os].Unprivate()
1753

    
1754
    if self.tcpudp_port_pool is None:
1755
      tcpudp_port_pool = []
1756
    else:
1757
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1758

    
1759
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1760

    
1761
    return mydict
1762

    
1763
  @classmethod
1764
  def FromDict(cls, val):
1765
    """Custom function for cluster.
1766

1767
    """
1768
    obj = super(Cluster, cls).FromDict(val)
1769

    
1770
    if obj.tcpudp_port_pool is None:
1771
      obj.tcpudp_port_pool = set()
1772
    elif not isinstance(obj.tcpudp_port_pool, set):
1773
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1774

    
1775
    return obj
1776

    
1777
  def SimpleFillDP(self, diskparams):
1778
    """Fill a given diskparams dict with cluster defaults.
1779

1780
    @param diskparams: The diskparams
1781
    @return: The defaults dict
1782

1783
    """
1784
    return FillDiskParams(self.diskparams, diskparams)
1785

    
1786
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1787
    """Get the default hypervisor parameters for the cluster.
1788

1789
    @param hypervisor: the hypervisor name
1790
    @param os_name: if specified, we'll also update the defaults for this OS
1791
    @param skip_keys: if passed, list of keys not to use
1792
    @return: the defaults dict
1793

1794
    """
1795
    if skip_keys is None:
1796
      skip_keys = []
1797

    
1798
    fill_stack = [self.hvparams.get(hypervisor, {})]
1799
    if os_name is not None:
1800
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1801
      fill_stack.append(os_hvp)
1802

    
1803
    ret_dict = {}
1804
    for o_dict in fill_stack:
1805
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1806

    
1807
    return ret_dict
1808

    
1809
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1810
    """Fill a given hvparams dict with cluster defaults.
1811

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

1823
    """
1824
    if skip_globals:
1825
      skip_keys = constants.HVC_GLOBALS
1826
    else:
1827
      skip_keys = []
1828

    
1829
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1830
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1831

    
1832
  def FillHV(self, instance, skip_globals=False):
1833
    """Fill an instance's hvparams dict with cluster defaults.
1834

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

1844
    """
1845
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1846
                             instance.hvparams, skip_globals)
1847

    
1848
  def SimpleFillBE(self, beparams):
1849
    """Fill a given beparams dict with cluster defaults.
1850

1851
    @type beparams: dict
1852
    @param beparams: the dict to fill
1853
    @rtype: dict
1854
    @return: a copy of the passed in beparams with missing keys filled
1855
        from the cluster defaults
1856

1857
    """
1858
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1859

    
1860
  def FillBE(self, instance):
1861
    """Fill an instance's beparams dict with cluster defaults.
1862

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

1869
    """
1870
    return self.SimpleFillBE(instance.beparams)
1871

    
1872
  def SimpleFillNIC(self, nicparams):
1873
    """Fill a given nicparams dict with cluster defaults.
1874

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

1881
    """
1882
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1883

    
1884
  def SimpleFillOS(self, os_name,
1885
                    os_params_public,
1886
                    os_params_private=None,
1887
                    os_params_secret=None):
1888
    """Fill an instance's osparams dict with cluster defaults.
1889

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

1911
    """
1912
    name_only = os_name.split("+", 1)[0]
1913

    
1914
    defaults_base_public = self.osparams.get(name_only, {})
1915
    defaults_public = FillDict(defaults_base_public,
1916
                               self.osparams.get(os_name, {}))
1917
    params_public = FillDict(defaults_public, os_params_public)
1918

    
1919
    if os_params_private is not None:
1920
      defaults_base_private = self.osparams_private_cluster.get(name_only, {})
1921
      defaults_private = FillDict(defaults_base_private,
1922
                                  self.osparams_private_cluster.get(os_name,
1923
                                                                    {}))
1924
      params_private = FillDict(defaults_private, os_params_private)
1925
    else:
1926
      params_private = {}
1927

    
1928
    if os_params_secret is not None:
1929
      # There can't be default secret settings, so there's nothing to be done.
1930
      params_secret = os_params_secret
1931
    else:
1932
      params_secret = {}
1933

    
1934
    # Enforce that the set of keys be distinct:
1935
    duplicate_keys = utils.GetRepeatedKeys(params_public,
1936
                                           params_private,
1937
                                           params_secret)
1938
    if not duplicate_keys:
1939

    
1940
      # Actually update them:
1941
      params_public.update(params_private)
1942
      params_public.update(params_secret)
1943

    
1944
      return params_public
1945

    
1946
    else:
1947

    
1948
      def formatter(keys):
1949
        return utils.CommaJoin(sorted(map(repr, keys))) if keys else "(none)"
1950

    
1951
      #Lose the values.
1952
      params_public = set(params_public)
1953
      params_private = set(params_private)
1954
      params_secret = set(params_secret)
1955

    
1956
      msg = """Cannot assign multiple values to OS parameters.
1957

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

    
1968
  @staticmethod
1969
  def SimpleFillHvState(hv_state):
1970
    """Fill an hv_state sub dict with cluster defaults.
1971

1972
    """
1973
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1974

    
1975
  @staticmethod
1976
  def SimpleFillDiskState(disk_state):
1977
    """Fill an disk_state sub dict with cluster defaults.
1978

1979
    """
1980
    return FillDict(constants.DS_DEFAULTS, disk_state)
1981

    
1982
  def FillND(self, node, nodegroup):
1983
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1984

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

1991
    """
1992
    return self.SimpleFillND(nodegroup.FillND(node))
1993

    
1994
  def FillNDGroup(self, nodegroup):
1995
    """Return filled out ndparams for just L{objects.NodeGroup}
1996

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

2001
    """
2002
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
2003

    
2004
  def SimpleFillND(self, ndparams):
2005
    """Fill a given ndparams dict with defaults.
2006

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

2013
    """
2014
    return FillDict(self.ndparams, ndparams)
2015

    
2016
  def SimpleFillIPolicy(self, ipolicy):
2017
    """ Fill instance policy dict with defaults.
2018

2019
    @type ipolicy: dict
2020
    @param ipolicy: the dict to fill
2021
    @rtype: dict
2022
    @return: a copy of passed ipolicy with missing keys filled from
2023
      the cluster defaults
2024

2025
    """
2026
    return FillIPolicy(self.ipolicy, ipolicy)
2027

    
2028
  def IsDiskTemplateEnabled(self, disk_template):
2029
    """Checks if a particular disk template is enabled.
2030

2031
    """
2032
    return utils.storage.IsDiskTemplateEnabled(
2033
        disk_template, self.enabled_disk_templates)
2034

    
2035
  def IsFileStorageEnabled(self):
2036
    """Checks if file storage is enabled.
2037

2038
    """
2039
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
2040

    
2041
  def IsSharedFileStorageEnabled(self):
2042
    """Checks if shared file storage is enabled.
2043

2044
    """
2045
    return utils.storage.IsSharedFileStorageEnabled(
2046
        self.enabled_disk_templates)
2047

    
2048

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

    
2061

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

    
2076

    
2077
class ImportExportOptions(ConfigObject):
2078
  """Options for import/export daemon
2079

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

2087
  """
2088
  __slots__ = [
2089
    "key_name",
2090
    "ca_pem",
2091
    "compress",
2092
    "magic",
2093
    "ipv6",
2094
    "connect_timeout",
2095
    ]
2096

    
2097

    
2098
class ConfdRequest(ConfigObject):
2099
  """Object holding a confd request.
2100

2101
  @ivar protocol: confd protocol version
2102
  @ivar type: confd query type
2103
  @ivar query: query request
2104
  @ivar rsalt: requested reply salt
2105

2106
  """
2107
  __slots__ = [
2108
    "protocol",
2109
    "type",
2110
    "query",
2111
    "rsalt",
2112
    ]
2113

    
2114

    
2115
class ConfdReply(ConfigObject):
2116
  """Object holding a confd reply.
2117

2118
  @ivar protocol: confd protocol version
2119
  @ivar status: reply status code (ok, error)
2120
  @ivar answer: confd query reply
2121
  @ivar serial: configuration serial number
2122

2123
  """
2124
  __slots__ = [
2125
    "protocol",
2126
    "status",
2127
    "answer",
2128
    "serial",
2129
    ]
2130

    
2131

    
2132
class QueryFieldDefinition(ConfigObject):
2133
  """Object holding a query field definition.
2134

2135
  @ivar name: Field name
2136
  @ivar title: Human-readable title
2137
  @ivar kind: Field type
2138
  @ivar doc: Human-readable description
2139

2140
  """
2141
  __slots__ = [
2142
    "name",
2143
    "title",
2144
    "kind",
2145
    "doc",
2146
    ]
2147

    
2148

    
2149
class _QueryResponseBase(ConfigObject):
2150
  __slots__ = [
2151
    "fields",
2152
    ]
2153

    
2154
  def ToDict(self, _with_private=False):
2155
    """Custom function for serializing.
2156

2157
    """
2158
    mydict = super(_QueryResponseBase, self).ToDict()
2159
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2160
    return mydict
2161

    
2162
  @classmethod
2163
  def FromDict(cls, val):
2164
    """Custom function for de-serializing.
2165

2166
    """
2167
    obj = super(_QueryResponseBase, cls).FromDict(val)
2168
    obj.fields = \
2169
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2170
    return obj
2171

    
2172

    
2173
class QueryResponse(_QueryResponseBase):
2174
  """Object holding the response to a query.
2175

2176
  @ivar fields: List of L{QueryFieldDefinition} objects
2177
  @ivar data: Requested data
2178

2179
  """
2180
  __slots__ = [
2181
    "data",
2182
    ]
2183

    
2184

    
2185
class QueryFieldsRequest(ConfigObject):
2186
  """Object holding a request for querying available fields.
2187

2188
  """
2189
  __slots__ = [
2190
    "what",
2191
    "fields",
2192
    ]
2193

    
2194

    
2195
class QueryFieldsResponse(_QueryResponseBase):
2196
  """Object holding the response to a query for fields.
2197

2198
  @ivar fields: List of L{QueryFieldDefinition} objects
2199

2200
  """
2201
  __slots__ = []
2202

    
2203

    
2204
class MigrationStatus(ConfigObject):
2205
  """Object holding the status of a migration.
2206

2207
  """
2208
  __slots__ = [
2209
    "status",
2210
    "transferred_ram",
2211
    "total_ram",
2212
    ]
2213

    
2214

    
2215
class InstanceConsole(ConfigObject):
2216
  """Object describing how to access the console of an instance.
2217

2218
  """
2219
  __slots__ = [
2220
    "instance",
2221
    "kind",
2222
    "message",
2223
    "host",
2224
    "port",
2225
    "user",
2226
    "command",
2227
    "display",
2228
    ]
2229

    
2230
  def Validate(self):
2231
    """Validates contents of this object.
2232

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

    
2253

    
2254
class Network(TaggableObject):
2255
  """Object representing a network definition for ganeti.
2256

2257
  """
2258
  __slots__ = [
2259
    "name",
2260
    "serial_no",
2261
    "mac_prefix",
2262
    "network",
2263
    "network6",
2264
    "gateway",
2265
    "gateway6",
2266
    "reservations",
2267
    "ext_reservations",
2268
    ] + _TIMESTAMPS + _UUID
2269

    
2270
  def HooksDict(self, prefix=""):
2271
    """Export a dictionary used by hooks with a network's information.
2272

2273
    @type prefix: String
2274
    @param prefix: Prefix to prepend to the dict entries
2275

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

    
2293
    return result
2294

    
2295
  @classmethod
2296
  def FromDict(cls, val):
2297
    """Custom function for networks.
2298

2299
    Remove deprecated network_type and family.
2300

2301
    """
2302
    if "network_type" in val:
2303
      del val["network_type"]
2304
    if "family" in val:
2305
      del val["family"]
2306
    obj = super(Network, cls).FromDict(val)
2307
    return obj
2308

    
2309

    
2310
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2311
  """Simple wrapper over ConfigParse that allows serialization.
2312

2313
  This class is basically ConfigParser.SafeConfigParser with two
2314
  additional methods that allow it to serialize/unserialize to/from a
2315
  buffer.
2316

2317
  """
2318
  def Dumps(self):
2319
    """Dump this instance and return the string representation."""
2320
    buf = StringIO()
2321
    self.write(buf)
2322
    return buf.getvalue()
2323

    
2324
  @classmethod
2325
  def Loads(cls, data):
2326
    """Load data from a string."""
2327
    buf = StringIO(data)
2328
    cfp = cls()
2329
    cfp.readfp(buf)
2330
    return cfp
2331

    
2332

    
2333
class LvmPvInfo(ConfigObject):
2334
  """Information about an LVM physical volume (PV).
2335

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

    
2358
  def IsEmpty(self):
2359
    """Is this PV empty?
2360

2361
    """
2362
    return self.size <= (self.free + 1)
2363

    
2364
  def IsAllocatable(self):
2365
    """Is this PV allocatable?
2366

2367
    """
2368
    return ("a" in self.attributes)