Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ b6dd32db

History | View | Annotate | Download (68.2 kB)

1
#
2
#
3

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

    
21

    
22
"""Transportable objects for Ganeti.
23

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

27
"""
28

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

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

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

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

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

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

    
52
from socket import AF_INET
53

    
54

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

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

    
61

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

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

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

    
83

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

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

    
97

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

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

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

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

    
110

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

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

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

    
127

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

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

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

    
141

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

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

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

    
156
  return result
157

    
158

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

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

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

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

    
177

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

181
  """
182
  return {}
183

    
184

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

188
  It has the following properties:
189

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

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

197
  """
198
  __slots__ = []
199

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

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

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

215
    """
216

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

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

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

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

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

    
243
  __getstate__ = ToDict
244

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

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

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

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

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

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

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

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

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

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

287
    """
288
    pass
289

    
290

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

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

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

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

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

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

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

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

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

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

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

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

349
    This replaces the tags set with a list.
350

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

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

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

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

    
369

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

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

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

    
388

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

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

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

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

    
414
    return mydict
415

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

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

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

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

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

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

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

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

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

    
497

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

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

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

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

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

    
521

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

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

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

    
544
    return tuple(set(nodes))
545

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

671
    This only works for VG-based disks.
672

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
779
    self.dynamic_params = dyn_disk_params
780

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
871
    # add here config upgrade for this disk
872

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

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

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

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

    
896
    assert disk_template in disk_params
897

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

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

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

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

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

    
935
    return result
936

    
937

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1089

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

    
1111
  def FindDisk(self, idx):
1112
    """Find a disk given having a specified index.
1113

1114
    This is just a wrapper that does validation of the index.
1115

1116
    @type idx: int
1117
    @param idx: the disk index
1118
    @rtype: L{Disk}
1119
    @return: the corresponding disk
1120
    @raise errors.OpPrereqError: when the given index is not valid
1121

1122
    """
1123
    try:
1124
      idx = int(idx)
1125
      return self.disks[idx]
1126
    except (TypeError, ValueError), err:
1127
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1128
                                 errors.ECODE_INVAL)
1129
    except IndexError:
1130
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1131
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1132
                                 errors.ECODE_INVAL)
1133

    
1134
  def ToDict(self, _with_private=False):
1135
    """Instance-specific conversion to standard python types.
1136

1137
    This replaces the children lists of objects with lists of standard
1138
    python types.
1139

1140
    """
1141
    bo = super(Instance, self).ToDict(_with_private=_with_private)
1142

    
1143
    if _with_private:
1144
      bo["osparams_private"] = self.osparams_private.Unprivate()
1145

    
1146
    for attr in "nics", "disks":
1147
      alist = bo.get(attr, None)
1148
      if alist:
1149
        nlist = outils.ContainerToDicts(alist)
1150
      else:
1151
        nlist = []
1152
      bo[attr] = nlist
1153
    return bo
1154

    
1155
  @classmethod
1156
  def FromDict(cls, val):
1157
    """Custom function for instances.
1158

1159
    """
1160
    if "admin_state" not in val:
1161
      if val.get("admin_up", False):
1162
        val["admin_state"] = constants.ADMINST_UP
1163
      else:
1164
        val["admin_state"] = constants.ADMINST_DOWN
1165
    if "admin_up" in val:
1166
      del val["admin_up"]
1167
    obj = super(Instance, cls).FromDict(val)
1168
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1169
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1170
    return obj
1171

    
1172
  def UpgradeConfig(self):
1173
    """Fill defaults for missing configuration values.
1174

1175
    """
1176
    for nic in self.nics:
1177
      nic.UpgradeConfig()
1178
    for disk in self.disks:
1179
      disk.UpgradeConfig()
1180
    if self.hvparams:
1181
      for key in constants.HVC_GLOBALS:
1182
        try:
1183
          del self.hvparams[key]
1184
        except KeyError:
1185
          pass
1186
    if self.osparams is None:
1187
      self.osparams = {}
1188
    if self.osparams_private is None:
1189
      self.osparams_private = serializer.PrivateDict()
1190
    UpgradeBeParams(self.beparams)
1191
    if self.disks_active is None:
1192
      self.disks_active = self.admin_state == constants.ADMINST_UP
1193

    
1194

    
1195
class OS(ConfigObject):
1196
  """Config object representing an operating system.
1197

1198
  @type supported_parameters: list
1199
  @ivar supported_parameters: a list of tuples, name and description,
1200
      containing the supported parameters by this OS
1201

1202
  @type VARIANT_DELIM: string
1203
  @cvar VARIANT_DELIM: the variant delimiter
1204

1205
  """
1206
  __slots__ = [
1207
    "name",
1208
    "path",
1209
    "api_versions",
1210
    "create_script",
1211
    "export_script",
1212
    "import_script",
1213
    "rename_script",
1214
    "verify_script",
1215
    "supported_variants",
1216
    "supported_parameters",
1217
    ]
1218

    
1219
  VARIANT_DELIM = "+"
1220

    
1221
  @classmethod
1222
  def SplitNameVariant(cls, name):
1223
    """Splits the name into the proper name and variant.
1224

1225
    @param name: the OS (unprocessed) name
1226
    @rtype: list
1227
    @return: a list of two elements; if the original name didn't
1228
        contain a variant, it's returned as an empty string
1229

1230
    """
1231
    nv = name.split(cls.VARIANT_DELIM, 1)
1232
    if len(nv) == 1:
1233
      nv.append("")
1234
    return nv
1235

    
1236
  @classmethod
1237
  def GetName(cls, name):
1238
    """Returns the proper name of the os (without the variant).
1239

1240
    @param name: the OS (unprocessed) name
1241

1242
    """
1243
    return cls.SplitNameVariant(name)[0]
1244

    
1245
  @classmethod
1246
  def GetVariant(cls, name):
1247
    """Returns the variant the os (without the base name).
1248

1249
    @param name: the OS (unprocessed) name
1250

1251
    """
1252
    return cls.SplitNameVariant(name)[1]
1253

    
1254

    
1255
class ExtStorage(ConfigObject):
1256
  """Config object representing an External Storage Provider.
1257

1258
  """
1259
  __slots__ = [
1260
    "name",
1261
    "path",
1262
    "create_script",
1263
    "remove_script",
1264
    "grow_script",
1265
    "attach_script",
1266
    "detach_script",
1267
    "setinfo_script",
1268
    "verify_script",
1269
    "supported_parameters",
1270
    ]
1271

    
1272

    
1273
class NodeHvState(ConfigObject):
1274
  """Hypvervisor state on a node.
1275

1276
  @ivar mem_total: Total amount of memory
1277
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1278
    available)
1279
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1280
    rounding
1281
  @ivar mem_inst: Memory used by instances living on node
1282
  @ivar cpu_total: Total node CPU core count
1283
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1284

1285
  """
1286
  __slots__ = [
1287
    "mem_total",
1288
    "mem_node",
1289
    "mem_hv",
1290
    "mem_inst",
1291
    "cpu_total",
1292
    "cpu_node",
1293
    ] + _TIMESTAMPS
1294

    
1295

    
1296
class NodeDiskState(ConfigObject):
1297
  """Disk state on a node.
1298

1299
  """
1300
  __slots__ = [
1301
    "total",
1302
    "reserved",
1303
    "overhead",
1304
    ] + _TIMESTAMPS
1305

    
1306

    
1307
class Node(TaggableObject):
1308
  """Config object representing a node.
1309

1310
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1311
  @ivar hv_state_static: Hypervisor state overriden by user
1312
  @ivar disk_state: Disk state (e.g. free space)
1313
  @ivar disk_state_static: Disk state overriden by user
1314

1315
  """
1316
  __slots__ = [
1317
    "name",
1318
    "primary_ip",
1319
    "secondary_ip",
1320
    "serial_no",
1321
    "master_candidate",
1322
    "offline",
1323
    "drained",
1324
    "group",
1325
    "master_capable",
1326
    "vm_capable",
1327
    "ndparams",
1328
    "powered",
1329
    "hv_state",
1330
    "hv_state_static",
1331
    "disk_state",
1332
    "disk_state_static",
1333
    ] + _TIMESTAMPS + _UUID
1334

    
1335
  def UpgradeConfig(self):
1336
    """Fill defaults for missing configuration values.
1337

1338
    """
1339
    # pylint: disable=E0203
1340
    # because these are "defined" via slots, not manually
1341
    if self.master_capable is None:
1342
      self.master_capable = True
1343

    
1344
    if self.vm_capable is None:
1345
      self.vm_capable = True
1346

    
1347
    if self.ndparams is None:
1348
      self.ndparams = {}
1349
    # And remove any global parameter
1350
    for key in constants.NDC_GLOBALS:
1351
      if key in self.ndparams:
1352
        logging.warning("Ignoring %s node parameter for node %s",
1353
                        key, self.name)
1354
        del self.ndparams[key]
1355

    
1356
    if self.powered is None:
1357
      self.powered = True
1358

    
1359
  def ToDict(self, _with_private=False):
1360
    """Custom function for serializing.
1361

1362
    """
1363
    data = super(Node, self).ToDict(_with_private=_with_private)
1364

    
1365
    hv_state = data.get("hv_state", None)
1366
    if hv_state is not None:
1367
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1368

    
1369
    disk_state = data.get("disk_state", None)
1370
    if disk_state is not None:
1371
      data["disk_state"] = \
1372
        dict((key, outils.ContainerToDicts(value))
1373
             for (key, value) in disk_state.items())
1374

    
1375
    return data
1376

    
1377
  @classmethod
1378
  def FromDict(cls, val):
1379
    """Custom function for deserializing.
1380

1381
    """
1382
    obj = super(Node, cls).FromDict(val)
1383

    
1384
    if obj.hv_state is not None:
1385
      obj.hv_state = \
1386
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1387

    
1388
    if obj.disk_state is not None:
1389
      obj.disk_state = \
1390
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1391
             for (key, value) in obj.disk_state.items())
1392

    
1393
    return obj
1394

    
1395

    
1396
class NodeGroup(TaggableObject):
1397
  """Config object representing a node group."""
1398
  __slots__ = [
1399
    "name",
1400
    "members",
1401
    "ndparams",
1402
    "diskparams",
1403
    "ipolicy",
1404
    "serial_no",
1405
    "hv_state_static",
1406
    "disk_state_static",
1407
    "alloc_policy",
1408
    "networks",
1409
    ] + _TIMESTAMPS + _UUID
1410

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

1414
    This discards the members object, which gets recalculated and is only kept
1415
    in memory.
1416

1417
    """
1418
    mydict = super(NodeGroup, self).ToDict(_with_private=_with_private)
1419
    del mydict["members"]
1420
    return mydict
1421

    
1422
  @classmethod
1423
  def FromDict(cls, val):
1424
    """Custom function for nodegroup.
1425

1426
    The members slot is initialized to an empty list, upon deserialization.
1427

1428
    """
1429
    obj = super(NodeGroup, cls).FromDict(val)
1430
    obj.members = []
1431
    return obj
1432

    
1433
  def UpgradeConfig(self):
1434
    """Fill defaults for missing configuration values.
1435

1436
    """
1437
    if self.ndparams is None:
1438
      self.ndparams = {}
1439

    
1440
    if self.serial_no is None:
1441
      self.serial_no = 1
1442

    
1443
    if self.alloc_policy is None:
1444
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1445

    
1446
    # We only update mtime, and not ctime, since we would not be able
1447
    # to provide a correct value for creation time.
1448
    if self.mtime is None:
1449
      self.mtime = time.time()
1450

    
1451
    if self.diskparams is None:
1452
      self.diskparams = {}
1453
    if self.ipolicy is None:
1454
      self.ipolicy = MakeEmptyIPolicy()
1455

    
1456
    if self.networks is None:
1457
      self.networks = {}
1458

    
1459
  def FillND(self, node):
1460
    """Return filled out ndparams for L{objects.Node}
1461

1462
    @type node: L{objects.Node}
1463
    @param node: A Node object to fill
1464
    @return a copy of the node's ndparams with defaults filled
1465

1466
    """
1467
    return self.SimpleFillND(node.ndparams)
1468

    
1469
  def SimpleFillND(self, ndparams):
1470
    """Fill a given ndparams dict with defaults.
1471

1472
    @type ndparams: dict
1473
    @param ndparams: the dict to fill
1474
    @rtype: dict
1475
    @return: a copy of the passed in ndparams with missing keys filled
1476
        from the node group defaults
1477

1478
    """
1479
    return FillDict(self.ndparams, ndparams)
1480

    
1481

    
1482
class Cluster(TaggableObject):
1483
  """Config object representing the cluster."""
1484
  __slots__ = [
1485
    "serial_no",
1486
    "rsahostkeypub",
1487
    "dsahostkeypub",
1488
    "highest_used_port",
1489
    "tcpudp_port_pool",
1490
    "mac_prefix",
1491
    "volume_group_name",
1492
    "reserved_lvs",
1493
    "drbd_usermode_helper",
1494
    "default_bridge",
1495
    "default_hypervisor",
1496
    "master_node",
1497
    "master_ip",
1498
    "master_netdev",
1499
    "master_netmask",
1500
    "use_external_mip_script",
1501
    "cluster_name",
1502
    "file_storage_dir",
1503
    "shared_file_storage_dir",
1504
    "gluster_storage_dir",
1505
    "enabled_hypervisors",
1506
    "hvparams",
1507
    "ipolicy",
1508
    "os_hvp",
1509
    "beparams",
1510
    "osparams",
1511
    "osparams_private_cluster",
1512
    "nicparams",
1513
    "ndparams",
1514
    "diskparams",
1515
    "candidate_pool_size",
1516
    "modify_etc_hosts",
1517
    "modify_ssh_setup",
1518
    "maintain_node_health",
1519
    "uid_pool",
1520
    "default_iallocator",
1521
    "default_iallocator_params",
1522
    "hidden_os",
1523
    "blacklisted_os",
1524
    "primary_ip_family",
1525
    "prealloc_wipe_disks",
1526
    "hv_state_static",
1527
    "disk_state_static",
1528
    "enabled_disk_templates",
1529
    "candidate_certs",
1530
    "max_running_jobs",
1531
    "instance_communication_network",
1532
    ] + _TIMESTAMPS + _UUID
1533

    
1534
  def UpgradeConfig(self):
1535
    """Fill defaults for missing configuration values.
1536

1537
    """
1538
    # pylint: disable=E0203
1539
    # because these are "defined" via slots, not manually
1540
    if self.hvparams is None:
1541
      self.hvparams = constants.HVC_DEFAULTS
1542
    else:
1543
      for hypervisor in constants.HYPER_TYPES:
1544
        try:
1545
          existing_params = self.hvparams[hypervisor]
1546
        except KeyError:
1547
          existing_params = {}
1548
        self.hvparams[hypervisor] = FillDict(
1549
            constants.HVC_DEFAULTS[hypervisor], existing_params)
1550

    
1551
    if self.os_hvp is None:
1552
      self.os_hvp = {}
1553

    
1554
    if self.osparams is None:
1555
      self.osparams = {}
1556
    # osparams_private_cluster added in 2.12
1557
    if self.osparams_private_cluster is None:
1558
      self.osparams_private_cluster = {}
1559

    
1560
    self.ndparams = UpgradeNDParams(self.ndparams)
1561

    
1562
    self.beparams = UpgradeGroupedParams(self.beparams,
1563
                                         constants.BEC_DEFAULTS)
1564
    for beparams_group in self.beparams:
1565
      UpgradeBeParams(self.beparams[beparams_group])
1566

    
1567
    migrate_default_bridge = not self.nicparams
1568
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1569
                                          constants.NICC_DEFAULTS)
1570
    if migrate_default_bridge:
1571
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1572
        self.default_bridge
1573

    
1574
    if self.modify_etc_hosts is None:
1575
      self.modify_etc_hosts = True
1576

    
1577
    if self.modify_ssh_setup is None:
1578
      self.modify_ssh_setup = True
1579

    
1580
    # default_bridge is no longer used in 2.1. The slot is left there to
1581
    # support auto-upgrading. It can be removed once we decide to deprecate
1582
    # upgrading straight from 2.0.
1583
    if self.default_bridge is not None:
1584
      self.default_bridge = None
1585

    
1586
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1587
    # code can be removed once upgrading straight from 2.0 is deprecated.
1588
    if self.default_hypervisor is not None:
1589
      self.enabled_hypervisors = ([self.default_hypervisor] +
1590
                                  [hvname for hvname in self.enabled_hypervisors
1591
                                   if hvname != self.default_hypervisor])
1592
      self.default_hypervisor = None
1593

    
1594
    # maintain_node_health added after 2.1.1
1595
    if self.maintain_node_health is None:
1596
      self.maintain_node_health = False
1597

    
1598
    if self.uid_pool is None:
1599
      self.uid_pool = []
1600

    
1601
    if self.default_iallocator is None:
1602
      self.default_iallocator = ""
1603

    
1604
    if self.default_iallocator_params is None:
1605
      self.default_iallocator_params = {}
1606

    
1607
    # reserved_lvs added before 2.2
1608
    if self.reserved_lvs is None:
1609
      self.reserved_lvs = []
1610

    
1611
    # hidden and blacklisted operating systems added before 2.2.1
1612
    if self.hidden_os is None:
1613
      self.hidden_os = []
1614

    
1615
    if self.blacklisted_os is None:
1616
      self.blacklisted_os = []
1617

    
1618
    # primary_ip_family added before 2.3
1619
    if self.primary_ip_family is None:
1620
      self.primary_ip_family = AF_INET
1621

    
1622
    if self.master_netmask is None:
1623
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1624
      self.master_netmask = ipcls.iplen
1625

    
1626
    if self.prealloc_wipe_disks is None:
1627
      self.prealloc_wipe_disks = False
1628

    
1629
    # shared_file_storage_dir added before 2.5
1630
    if self.shared_file_storage_dir is None:
1631
      self.shared_file_storage_dir = ""
1632

    
1633
    # gluster_storage_dir added in 2.11
1634
    if self.gluster_storage_dir is None:
1635
      self.gluster_storage_dir = ""
1636

    
1637
    if self.use_external_mip_script is None:
1638
      self.use_external_mip_script = False
1639

    
1640
    if self.diskparams:
1641
      self.diskparams = UpgradeDiskParams(self.diskparams)
1642
    else:
1643
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1644

    
1645
    # instance policy added before 2.6
1646
    if self.ipolicy is None:
1647
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1648
    else:
1649
      # we can either make sure to upgrade the ipolicy always, or only
1650
      # do it in some corner cases (e.g. missing keys); note that this
1651
      # will break any removal of keys from the ipolicy dict
1652
      wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1653
      if wrongkeys:
1654
        # These keys would be silently removed by FillIPolicy()
1655
        msg = ("Cluster instance policy contains spurious keys: %s" %
1656
               utils.CommaJoin(wrongkeys))
1657
        raise errors.ConfigurationError(msg)
1658
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1659

    
1660
    if self.candidate_certs is None:
1661
      self.candidate_certs = {}
1662

    
1663
    if self.max_running_jobs is None:
1664
      self.max_running_jobs = constants.LUXID_MAXIMAL_RUNNING_JOBS_DEFAULT
1665

    
1666
    if self.instance_communication_network is None:
1667
      self.instance_communication_network = ""
1668

    
1669
  @property
1670
  def primary_hypervisor(self):
1671
    """The first hypervisor is the primary.
1672

1673
    Useful, for example, for L{Node}'s hv/disk state.
1674

1675
    """
1676
    return self.enabled_hypervisors[0]
1677

    
1678
  def ToDict(self, _with_private=False):
1679
    """Custom function for cluster.
1680

1681
    """
1682
    mydict = super(Cluster, self).ToDict(_with_private=_with_private)
1683

    
1684
    # Explicitly save private parameters.
1685
    if _with_private:
1686
      for os in mydict["osparams_private_cluster"]:
1687
        mydict["osparams_private_cluster"][os] = \
1688
          self.osparams_private_cluster[os].Unprivate()
1689

    
1690
    if self.tcpudp_port_pool is None:
1691
      tcpudp_port_pool = []
1692
    else:
1693
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1694

    
1695
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1696

    
1697
    return mydict
1698

    
1699
  @classmethod
1700
  def FromDict(cls, val):
1701
    """Custom function for cluster.
1702

1703
    """
1704
    obj = super(Cluster, cls).FromDict(val)
1705

    
1706
    if obj.tcpudp_port_pool is None:
1707
      obj.tcpudp_port_pool = set()
1708
    elif not isinstance(obj.tcpudp_port_pool, set):
1709
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1710

    
1711
    return obj
1712

    
1713
  def SimpleFillDP(self, diskparams):
1714
    """Fill a given diskparams dict with cluster defaults.
1715

1716
    @param diskparams: The diskparams
1717
    @return: The defaults dict
1718

1719
    """
1720
    return FillDiskParams(self.diskparams, diskparams)
1721

    
1722
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1723
    """Get the default hypervisor parameters for the cluster.
1724

1725
    @param hypervisor: the hypervisor name
1726
    @param os_name: if specified, we'll also update the defaults for this OS
1727
    @param skip_keys: if passed, list of keys not to use
1728
    @return: the defaults dict
1729

1730
    """
1731
    if skip_keys is None:
1732
      skip_keys = []
1733

    
1734
    fill_stack = [self.hvparams.get(hypervisor, {})]
1735
    if os_name is not None:
1736
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1737
      fill_stack.append(os_hvp)
1738

    
1739
    ret_dict = {}
1740
    for o_dict in fill_stack:
1741
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1742

    
1743
    return ret_dict
1744

    
1745
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1746
    """Fill a given hvparams dict with cluster defaults.
1747

1748
    @type hv_name: string
1749
    @param hv_name: the hypervisor to use
1750
    @type os_name: string
1751
    @param os_name: the OS to use for overriding the hypervisor defaults
1752
    @type skip_globals: boolean
1753
    @param skip_globals: if True, the global hypervisor parameters will
1754
        not be filled
1755
    @rtype: dict
1756
    @return: a copy of the given hvparams with missing keys filled from
1757
        the cluster defaults
1758

1759
    """
1760
    if skip_globals:
1761
      skip_keys = constants.HVC_GLOBALS
1762
    else:
1763
      skip_keys = []
1764

    
1765
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1766
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1767

    
1768
  def FillHV(self, instance, skip_globals=False):
1769
    """Fill an instance's hvparams dict with cluster defaults.
1770

1771
    @type instance: L{objects.Instance}
1772
    @param instance: the instance parameter to fill
1773
    @type skip_globals: boolean
1774
    @param skip_globals: if True, the global hypervisor parameters will
1775
        not be filled
1776
    @rtype: dict
1777
    @return: a copy of the instance's hvparams with missing keys filled from
1778
        the cluster defaults
1779

1780
    """
1781
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1782
                             instance.hvparams, skip_globals)
1783

    
1784
  def SimpleFillBE(self, beparams):
1785
    """Fill a given beparams dict with cluster defaults.
1786

1787
    @type beparams: dict
1788
    @param beparams: the dict to fill
1789
    @rtype: dict
1790
    @return: a copy of the passed in beparams with missing keys filled
1791
        from the cluster defaults
1792

1793
    """
1794
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1795

    
1796
  def FillBE(self, instance):
1797
    """Fill an instance's beparams dict with cluster defaults.
1798

1799
    @type instance: L{objects.Instance}
1800
    @param instance: the instance parameter to fill
1801
    @rtype: dict
1802
    @return: a copy of the instance's beparams with missing keys filled from
1803
        the cluster defaults
1804

1805
    """
1806
    return self.SimpleFillBE(instance.beparams)
1807

    
1808
  def SimpleFillNIC(self, nicparams):
1809
    """Fill a given nicparams dict with cluster defaults.
1810

1811
    @type nicparams: dict
1812
    @param nicparams: the dict to fill
1813
    @rtype: dict
1814
    @return: a copy of the passed in nicparams with missing keys filled
1815
        from the cluster defaults
1816

1817
    """
1818
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1819

    
1820
  def SimpleFillOS(self, os_name,
1821
                    os_params_public,
1822
                    os_params_private=None,
1823
                    os_params_secret=None):
1824
    """Fill an instance's osparams dict with cluster defaults.
1825

1826
    @type os_name: string
1827
    @param os_name: the OS name to use
1828
    @type os_params_public: dict
1829
    @param os_params_public: the dict to fill with default values
1830
    @type os_params_private: dict
1831
    @param os_params_private: the dict with private fields to fill
1832
                              with default values. Not passing this field
1833
                              results in no private fields being added to the
1834
                              return value. Private fields will be wrapped in
1835
                              L{Private} objects.
1836
    @type os_params_secret: dict
1837
    @param os_params_secret: the dict with secret fields to fill
1838
                             with default values. Not passing this field
1839
                             results in no secret fields being added to the
1840
                             return value. Private fields will be wrapped in
1841
                             L{Private} objects.
1842
    @rtype: dict
1843
    @return: a copy of the instance's osparams with missing keys filled from
1844
        the cluster defaults. Private and secret parameters are not included
1845
        unless the respective optional parameters are supplied.
1846

1847
    """
1848
    name_only = os_name.split("+", 1)[0]
1849

    
1850
    defaults_base_public = self.osparams.get(name_only, {})
1851
    defaults_public = FillDict(defaults_base_public,
1852
                               self.osparams.get(os_name, {}))
1853
    params_public = FillDict(defaults_public, os_params_public)
1854

    
1855
    if os_params_private is not None:
1856
      defaults_base_private = self.osparams_private_cluster.get(name_only, {})
1857
      defaults_private = FillDict(defaults_base_private,
1858
                                  self.osparams_private_cluster.get(os_name,
1859
                                                                    {}))
1860
      params_private = FillDict(defaults_private, os_params_private)
1861
    else:
1862
      params_private = {}
1863

    
1864
    if os_params_secret is not None:
1865
      # There can't be default secret settings, so there's nothing to be done.
1866
      params_secret = os_params_secret
1867
    else:
1868
      params_secret = {}
1869

    
1870
    # Enforce that the set of keys be distinct:
1871
    duplicate_keys = utils.GetRepeatedKeys(params_public,
1872
                                           params_private,
1873
                                           params_secret)
1874
    if not duplicate_keys:
1875

    
1876
      # Actually update them:
1877
      params_public.update(params_private)
1878
      params_public.update(params_secret)
1879

    
1880
      return params_public
1881

    
1882
    else:
1883

    
1884
      def formatter(keys):
1885
        return utils.CommaJoin(sorted(map(repr, keys))) if keys else "(none)"
1886

    
1887
      #Lose the values.
1888
      params_public = set(params_public)
1889
      params_private = set(params_private)
1890
      params_secret = set(params_secret)
1891

    
1892
      msg = """Cannot assign multiple values to OS parameters.
1893

1894
      Conflicting OS parameters that would have been set by this operation:
1895
      - at public visibility:  {public}
1896
      - at private visibility: {private}
1897
      - at secret visibility:  {secret}
1898
      """.format(dupes=formatter(duplicate_keys),
1899
                 public=formatter(params_public & duplicate_keys),
1900
                 private=formatter(params_private & duplicate_keys),
1901
                 secret=formatter(params_secret & duplicate_keys))
1902
      raise errors.OpPrereqError(msg)
1903

    
1904
  @staticmethod
1905
  def SimpleFillHvState(hv_state):
1906
    """Fill an hv_state sub dict with cluster defaults.
1907

1908
    """
1909
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1910

    
1911
  @staticmethod
1912
  def SimpleFillDiskState(disk_state):
1913
    """Fill an disk_state sub dict with cluster defaults.
1914

1915
    """
1916
    return FillDict(constants.DS_DEFAULTS, disk_state)
1917

    
1918
  def FillND(self, node, nodegroup):
1919
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1920

1921
    @type node: L{objects.Node}
1922
    @param node: A Node object to fill
1923
    @type nodegroup: L{objects.NodeGroup}
1924
    @param nodegroup: A Node object to fill
1925
    @return a copy of the node's ndparams with defaults filled
1926

1927
    """
1928
    return self.SimpleFillND(nodegroup.FillND(node))
1929

    
1930
  def FillNDGroup(self, nodegroup):
1931
    """Return filled out ndparams for just L{objects.NodeGroup}
1932

1933
    @type nodegroup: L{objects.NodeGroup}
1934
    @param nodegroup: A Node object to fill
1935
    @return a copy of the node group's ndparams with defaults filled
1936

1937
    """
1938
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
1939

    
1940
  def SimpleFillND(self, ndparams):
1941
    """Fill a given ndparams dict with defaults.
1942

1943
    @type ndparams: dict
1944
    @param ndparams: the dict to fill
1945
    @rtype: dict
1946
    @return: a copy of the passed in ndparams with missing keys filled
1947
        from the cluster defaults
1948

1949
    """
1950
    return FillDict(self.ndparams, ndparams)
1951

    
1952
  def SimpleFillIPolicy(self, ipolicy):
1953
    """ Fill instance policy dict with defaults.
1954

1955
    @type ipolicy: dict
1956
    @param ipolicy: the dict to fill
1957
    @rtype: dict
1958
    @return: a copy of passed ipolicy with missing keys filled from
1959
      the cluster defaults
1960

1961
    """
1962
    return FillIPolicy(self.ipolicy, ipolicy)
1963

    
1964
  def IsDiskTemplateEnabled(self, disk_template):
1965
    """Checks if a particular disk template is enabled.
1966

1967
    """
1968
    return utils.storage.IsDiskTemplateEnabled(
1969
        disk_template, self.enabled_disk_templates)
1970

    
1971
  def IsFileStorageEnabled(self):
1972
    """Checks if file storage is enabled.
1973

1974
    """
1975
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1976

    
1977
  def IsSharedFileStorageEnabled(self):
1978
    """Checks if shared file storage is enabled.
1979

1980
    """
1981
    return utils.storage.IsSharedFileStorageEnabled(
1982
        self.enabled_disk_templates)
1983

    
1984

    
1985
class BlockDevStatus(ConfigObject):
1986
  """Config object representing the status of a block device."""
1987
  __slots__ = [
1988
    "dev_path",
1989
    "major",
1990
    "minor",
1991
    "sync_percent",
1992
    "estimated_time",
1993
    "is_degraded",
1994
    "ldisk_status",
1995
    ]
1996

    
1997

    
1998
class ImportExportStatus(ConfigObject):
1999
  """Config object representing the status of an import or export."""
2000
  __slots__ = [
2001
    "recent_output",
2002
    "listen_port",
2003
    "connected",
2004
    "progress_mbytes",
2005
    "progress_throughput",
2006
    "progress_eta",
2007
    "progress_percent",
2008
    "exit_status",
2009
    "error_message",
2010
    ] + _TIMESTAMPS
2011

    
2012

    
2013
class ImportExportOptions(ConfigObject):
2014
  """Options for import/export daemon
2015

2016
  @ivar key_name: X509 key name (None for cluster certificate)
2017
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
2018
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
2019
  @ivar magic: Used to ensure the connection goes to the right disk
2020
  @ivar ipv6: Whether to use IPv6
2021
  @ivar connect_timeout: Number of seconds for establishing connection
2022

2023
  """
2024
  __slots__ = [
2025
    "key_name",
2026
    "ca_pem",
2027
    "compress",
2028
    "magic",
2029
    "ipv6",
2030
    "connect_timeout",
2031
    ]
2032

    
2033

    
2034
class ConfdRequest(ConfigObject):
2035
  """Object holding a confd request.
2036

2037
  @ivar protocol: confd protocol version
2038
  @ivar type: confd query type
2039
  @ivar query: query request
2040
  @ivar rsalt: requested reply salt
2041

2042
  """
2043
  __slots__ = [
2044
    "protocol",
2045
    "type",
2046
    "query",
2047
    "rsalt",
2048
    ]
2049

    
2050

    
2051
class ConfdReply(ConfigObject):
2052
  """Object holding a confd reply.
2053

2054
  @ivar protocol: confd protocol version
2055
  @ivar status: reply status code (ok, error)
2056
  @ivar answer: confd query reply
2057
  @ivar serial: configuration serial number
2058

2059
  """
2060
  __slots__ = [
2061
    "protocol",
2062
    "status",
2063
    "answer",
2064
    "serial",
2065
    ]
2066

    
2067

    
2068
class QueryFieldDefinition(ConfigObject):
2069
  """Object holding a query field definition.
2070

2071
  @ivar name: Field name
2072
  @ivar title: Human-readable title
2073
  @ivar kind: Field type
2074
  @ivar doc: Human-readable description
2075

2076
  """
2077
  __slots__ = [
2078
    "name",
2079
    "title",
2080
    "kind",
2081
    "doc",
2082
    ]
2083

    
2084

    
2085
class _QueryResponseBase(ConfigObject):
2086
  __slots__ = [
2087
    "fields",
2088
    ]
2089

    
2090
  def ToDict(self, _with_private=False):
2091
    """Custom function for serializing.
2092

2093
    """
2094
    mydict = super(_QueryResponseBase, self).ToDict()
2095
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2096
    return mydict
2097

    
2098
  @classmethod
2099
  def FromDict(cls, val):
2100
    """Custom function for de-serializing.
2101

2102
    """
2103
    obj = super(_QueryResponseBase, cls).FromDict(val)
2104
    obj.fields = \
2105
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2106
    return obj
2107

    
2108

    
2109
class QueryResponse(_QueryResponseBase):
2110
  """Object holding the response to a query.
2111

2112
  @ivar fields: List of L{QueryFieldDefinition} objects
2113
  @ivar data: Requested data
2114

2115
  """
2116
  __slots__ = [
2117
    "data",
2118
    ]
2119

    
2120

    
2121
class QueryFieldsRequest(ConfigObject):
2122
  """Object holding a request for querying available fields.
2123

2124
  """
2125
  __slots__ = [
2126
    "what",
2127
    "fields",
2128
    ]
2129

    
2130

    
2131
class QueryFieldsResponse(_QueryResponseBase):
2132
  """Object holding the response to a query for fields.
2133

2134
  @ivar fields: List of L{QueryFieldDefinition} objects
2135

2136
  """
2137
  __slots__ = []
2138

    
2139

    
2140
class MigrationStatus(ConfigObject):
2141
  """Object holding the status of a migration.
2142

2143
  """
2144
  __slots__ = [
2145
    "status",
2146
    "transferred_ram",
2147
    "total_ram",
2148
    ]
2149

    
2150

    
2151
class InstanceConsole(ConfigObject):
2152
  """Object describing how to access the console of an instance.
2153

2154
  """
2155
  __slots__ = [
2156
    "instance",
2157
    "kind",
2158
    "message",
2159
    "host",
2160
    "port",
2161
    "user",
2162
    "command",
2163
    "display",
2164
    ]
2165

    
2166
  def Validate(self):
2167
    """Validates contents of this object.
2168

2169
    """
2170
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2171
    assert self.instance, "Missing instance name"
2172
    assert self.message or self.kind in [constants.CONS_SSH,
2173
                                         constants.CONS_SPICE,
2174
                                         constants.CONS_VNC]
2175
    assert self.host or self.kind == constants.CONS_MESSAGE
2176
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2177
                                      constants.CONS_SSH]
2178
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2179
                                      constants.CONS_SPICE,
2180
                                      constants.CONS_VNC]
2181
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2182
                                         constants.CONS_SPICE,
2183
                                         constants.CONS_VNC]
2184
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2185
                                         constants.CONS_SPICE,
2186
                                         constants.CONS_SSH]
2187
    return True
2188

    
2189

    
2190
class Network(TaggableObject):
2191
  """Object representing a network definition for ganeti.
2192

2193
  """
2194
  __slots__ = [
2195
    "name",
2196
    "serial_no",
2197
    "mac_prefix",
2198
    "network",
2199
    "network6",
2200
    "gateway",
2201
    "gateway6",
2202
    "reservations",
2203
    "ext_reservations",
2204
    ] + _TIMESTAMPS + _UUID
2205

    
2206
  def HooksDict(self, prefix=""):
2207
    """Export a dictionary used by hooks with a network's information.
2208

2209
    @type prefix: String
2210
    @param prefix: Prefix to prepend to the dict entries
2211

2212
    """
2213
    result = {
2214
      "%sNETWORK_NAME" % prefix: self.name,
2215
      "%sNETWORK_UUID" % prefix: self.uuid,
2216
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2217
    }
2218
    if self.network:
2219
      result["%sNETWORK_SUBNET" % prefix] = self.network
2220
    if self.gateway:
2221
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2222
    if self.network6:
2223
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2224
    if self.gateway6:
2225
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2226
    if self.mac_prefix:
2227
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2228

    
2229
    return result
2230

    
2231
  @classmethod
2232
  def FromDict(cls, val):
2233
    """Custom function for networks.
2234

2235
    Remove deprecated network_type and family.
2236

2237
    """
2238
    if "network_type" in val:
2239
      del val["network_type"]
2240
    if "family" in val:
2241
      del val["family"]
2242
    obj = super(Network, cls).FromDict(val)
2243
    return obj
2244

    
2245

    
2246
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2247
  """Simple wrapper over ConfigParse that allows serialization.
2248

2249
  This class is basically ConfigParser.SafeConfigParser with two
2250
  additional methods that allow it to serialize/unserialize to/from a
2251
  buffer.
2252

2253
  """
2254
  def Dumps(self):
2255
    """Dump this instance and return the string representation."""
2256
    buf = StringIO()
2257
    self.write(buf)
2258
    return buf.getvalue()
2259

    
2260
  @classmethod
2261
  def Loads(cls, data):
2262
    """Load data from a string."""
2263
    buf = StringIO(data)
2264
    cfp = cls()
2265
    cfp.readfp(buf)
2266
    return cfp
2267

    
2268

    
2269
class LvmPvInfo(ConfigObject):
2270
  """Information about an LVM physical volume (PV).
2271

2272
  @type name: string
2273
  @ivar name: name of the PV
2274
  @type vg_name: string
2275
  @ivar vg_name: name of the volume group containing the PV
2276
  @type size: float
2277
  @ivar size: size of the PV in MiB
2278
  @type free: float
2279
  @ivar free: free space in the PV, in MiB
2280
  @type attributes: string
2281
  @ivar attributes: PV attributes
2282
  @type lv_list: list of strings
2283
  @ivar lv_list: names of the LVs hosted on the PV
2284
  """
2285
  __slots__ = [
2286
    "name",
2287
    "vg_name",
2288
    "size",
2289
    "free",
2290
    "attributes",
2291
    "lv_list"
2292
    ]
2293

    
2294
  def IsEmpty(self):
2295
    """Is this PV empty?
2296

2297
    """
2298
    return self.size <= (self.free + 1)
2299

    
2300
  def IsAllocatable(self):
2301
    """Is this PV allocatable?
2302

2303
    """
2304
    return ("a" in self.attributes)