Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 78f99abb

History | View | Annotate | Download (64.4 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

    
51
from socket import AF_INET
52

    
53

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

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

    
60

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

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

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

    
84

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

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

    
98

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

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

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

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

    
111

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

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

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

    
128

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

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

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

    
142

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

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

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

    
157
  return result
158

    
159

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

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

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

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

    
178

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

182
  """
183
  return {}
184

    
185

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

189
  It has the following properties:
190

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

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

198
  """
199
  __slots__ = []
200

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

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

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

216
    """
217

    
218
  def ToDict(self):
219
    """Convert to a dict holding only standard python types.
220

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

227
    """
228
    result = {}
229
    for name in self.GetAllSlots():
230
      value = getattr(self, name, None)
231
      if value is not None:
232
        result[name] = value
233
    return result
234

    
235
  __getstate__ = ToDict
236

    
237
  @classmethod
238
  def FromDict(cls, val):
239
    """Create an object from a dictionary.
240

241
    This generic routine takes a dict, instantiates a new instance of
242
    the given class, and sets attributes based on the dict content.
243

244
    As for `ToDict`, this does not work if the class has children
245
    who are ConfigObjects themselves (e.g. the nics list in an
246
    Instance), in which case the object should subclass the function
247
    and alter the objects.
248

249
    """
250
    if not isinstance(val, dict):
251
      raise errors.ConfigurationError("Invalid object passed to FromDict:"
252
                                      " expected dict, got %s" % type(val))
253
    val_str = dict([(str(k), v) for k, v in val.iteritems()])
254
    obj = cls(**val_str) # pylint: disable=W0142
255
    return obj
256

    
257
  def Copy(self):
258
    """Makes a deep copy of the current object and its children.
259

260
    """
261
    dict_form = self.ToDict()
262
    clone_obj = self.__class__.FromDict(dict_form)
263
    return clone_obj
264

    
265
  def __repr__(self):
266
    """Implement __repr__ for ConfigObjects."""
267
    return repr(self.ToDict())
268

    
269
  def UpgradeConfig(self):
270
    """Fill defaults for missing configuration values.
271

272
    This method will be called at configuration load time, and its
273
    implementation will be object dependent.
274

275
    """
276
    pass
277

    
278

    
279
class TaggableObject(ConfigObject):
280
  """An generic class supporting tags.
281

282
  """
283
  __slots__ = ["tags"]
284
  VALID_TAG_RE = re.compile(r"^[\w.+*/:@-]+$")
285

    
286
  @classmethod
287
  def ValidateTag(cls, tag):
288
    """Check if a tag is valid.
289

290
    If the tag is invalid, an errors.TagError will be raised. The
291
    function has no return value.
292

293
    """
294
    if not isinstance(tag, basestring):
295
      raise errors.TagError("Invalid tag type (not a string)")
296
    if len(tag) > constants.MAX_TAG_LEN:
297
      raise errors.TagError("Tag too long (>%d characters)" %
298
                            constants.MAX_TAG_LEN)
299
    if not tag:
300
      raise errors.TagError("Tags cannot be empty")
301
    if not cls.VALID_TAG_RE.match(tag):
302
      raise errors.TagError("Tag contains invalid characters")
303

    
304
  def GetTags(self):
305
    """Return the tags list.
306

307
    """
308
    tags = getattr(self, "tags", None)
309
    if tags is None:
310
      tags = self.tags = set()
311
    return tags
312

    
313
  def AddTag(self, tag):
314
    """Add a new tag.
315

316
    """
317
    self.ValidateTag(tag)
318
    tags = self.GetTags()
319
    if len(tags) >= constants.MAX_TAGS_PER_OBJ:
320
      raise errors.TagError("Too many tags")
321
    self.GetTags().add(tag)
322

    
323
  def RemoveTag(self, tag):
324
    """Remove a tag.
325

326
    """
327
    self.ValidateTag(tag)
328
    tags = self.GetTags()
329
    try:
330
      tags.remove(tag)
331
    except KeyError:
332
      raise errors.TagError("Tag not found")
333

    
334
  def ToDict(self):
335
    """Taggable-object-specific conversion to standard python types.
336

337
    This replaces the tags set with a list.
338

339
    """
340
    bo = super(TaggableObject, self).ToDict()
341

    
342
    tags = bo.get("tags", None)
343
    if isinstance(tags, set):
344
      bo["tags"] = list(tags)
345
    return bo
346

    
347
  @classmethod
348
  def FromDict(cls, val):
349
    """Custom function for instances.
350

351
    """
352
    obj = super(TaggableObject, cls).FromDict(val)
353
    if hasattr(obj, "tags") and isinstance(obj.tags, list):
354
      obj.tags = set(obj.tags)
355
    return obj
356

    
357

    
358
class MasterNetworkParameters(ConfigObject):
359
  """Network configuration parameters for the master
360

361
  @ivar uuid: master nodes UUID
362
  @ivar ip: master IP
363
  @ivar netmask: master netmask
364
  @ivar netdev: master network device
365
  @ivar ip_family: master IP family
366

367
  """
368
  __slots__ = [
369
    "uuid",
370
    "ip",
371
    "netmask",
372
    "netdev",
373
    "ip_family",
374
    ]
375

    
376

    
377
class ConfigData(ConfigObject):
378
  """Top-level config object."""
379
  __slots__ = [
380
    "version",
381
    "cluster",
382
    "nodes",
383
    "nodegroups",
384
    "instances",
385
    "networks",
386
    "serial_no",
387
    ] + _TIMESTAMPS
388

    
389
  def ToDict(self):
390
    """Custom function for top-level config data.
391

392
    This just replaces the list of instances, nodes and the cluster
393
    with standard python types.
394

395
    """
396
    mydict = super(ConfigData, self).ToDict()
397
    mydict["cluster"] = mydict["cluster"].ToDict()
398
    for key in "nodes", "instances", "nodegroups", "networks":
399
      mydict[key] = outils.ContainerToDicts(mydict[key])
400

    
401
    return mydict
402

    
403
  @classmethod
404
  def FromDict(cls, val):
405
    """Custom function for top-level config data
406

407
    """
408
    obj = super(ConfigData, cls).FromDict(val)
409
    obj.cluster = Cluster.FromDict(obj.cluster)
410
    obj.nodes = outils.ContainerFromDicts(obj.nodes, dict, Node)
411
    obj.instances = \
412
      outils.ContainerFromDicts(obj.instances, dict, Instance)
413
    obj.nodegroups = \
414
      outils.ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
415
    obj.networks = outils.ContainerFromDicts(obj.networks, dict, Network)
416
    return obj
417

    
418
  def HasAnyDiskOfType(self, dev_type):
419
    """Check if in there is at disk of the given type in the configuration.
420

421
    @type dev_type: L{constants.LDS_BLOCK}
422
    @param dev_type: the type to look for
423
    @rtype: boolean
424
    @return: boolean indicating if a disk of the given type was found or not
425

426
    """
427
    for instance in self.instances.values():
428
      for disk in instance.disks:
429
        if disk.IsBasedOnDiskType(dev_type):
430
          return True
431
    return False
432

    
433
  def UpgradeConfig(self):
434
    """Fill defaults for missing configuration values.
435

436
    """
437
    self.cluster.UpgradeConfig()
438
    for node in self.nodes.values():
439
      node.UpgradeConfig()
440
    for instance in self.instances.values():
441
      instance.UpgradeConfig()
442
    if self.nodegroups is None:
443
      self.nodegroups = {}
444
    for nodegroup in self.nodegroups.values():
445
      nodegroup.UpgradeConfig()
446
    if self.cluster.drbd_usermode_helper is None:
447
      # To decide if we set an helper let's check if at least one instance has
448
      # a DRBD disk. This does not cover all the possible scenarios but it
449
      # gives a good approximation.
450
      if self.HasAnyDiskOfType(constants.LD_DRBD8):
451
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
452
    if self.networks is None:
453
      self.networks = {}
454
    for network in self.networks.values():
455
      network.UpgradeConfig()
456
    self._UpgradeEnabledDiskTemplates()
457

    
458
  def _UpgradeEnabledDiskTemplates(self):
459
    """Upgrade the cluster's enabled disk templates by inspecting the currently
460
       enabled and/or used disk templates.
461

462
    """
463
    # enabled_disk_templates in the cluster config were introduced in 2.8.
464
    # Remove this code once upgrading from earlier versions is deprecated.
465
    if not self.cluster.enabled_disk_templates:
466
      template_set = \
467
        set([inst.disk_template for inst in self.instances.values()])
468
      # Add drbd and plain, if lvm is enabled (by specifying a volume group)
469
      if self.cluster.volume_group_name:
470
        template_set.add(constants.DT_DRBD8)
471
        template_set.add(constants.DT_PLAIN)
472
      # Set enabled_disk_templates to the inferred disk templates. Order them
473
      # according to a preference list that is based on Ganeti's history of
474
      # supported disk templates.
475
      self.cluster.enabled_disk_templates = []
476
      for preferred_template in constants.DISK_TEMPLATE_PREFERENCE:
477
        if preferred_template in template_set:
478
          self.cluster.enabled_disk_templates.append(preferred_template)
479
          template_set.remove(preferred_template)
480
      self.cluster.enabled_disk_templates.extend(list(template_set))
481

    
482

    
483
class NIC(ConfigObject):
484
  """Config object representing a network card."""
485
  __slots__ = ["name", "mac", "ip", "network", "nicparams", "netinfo"] + _UUID
486

    
487
  @classmethod
488
  def CheckParameterSyntax(cls, nicparams):
489
    """Check the given parameters for validity.
490

491
    @type nicparams:  dict
492
    @param nicparams: dictionary with parameter names/value
493
    @raise errors.ConfigurationError: when a parameter is not valid
494

495
    """
496
    mode = nicparams[constants.NIC_MODE]
497
    if (mode not in constants.NIC_VALID_MODES and
498
        mode != constants.VALUE_AUTO):
499
      raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
500

    
501
    if (mode == constants.NIC_MODE_BRIDGED and
502
        not nicparams[constants.NIC_LINK]):
503
      raise errors.ConfigurationError("Missing bridged NIC link")
504

    
505

    
506
class Disk(ConfigObject):
507
  """Config object representing a block device."""
508
  __slots__ = (["name", "dev_type", "logical_id", "physical_id",
509
                "children", "iv_name", "size", "mode", "params", "spindles"] +
510
               _UUID)
511

    
512
  def CreateOnSecondary(self):
513
    """Test if this device needs to be created on a secondary node."""
514
    return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
515

    
516
  def AssembleOnSecondary(self):
517
    """Test if this device needs to be assembled on a secondary node."""
518
    return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
519

    
520
  def OpenOnSecondary(self):
521
    """Test if this device needs to be opened on a secondary node."""
522
    return self.dev_type in (constants.LD_LV,)
523

    
524
  def StaticDevPath(self):
525
    """Return the device path if this device type has a static one.
526

527
    Some devices (LVM for example) live always at the same /dev/ path,
528
    irrespective of their status. For such devices, we return this
529
    path, for others we return None.
530

531
    @warning: The path returned is not a normalized pathname; callers
532
        should check that it is a valid path.
533

534
    """
535
    if self.dev_type == constants.LD_LV:
536
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
537
    elif self.dev_type == constants.LD_BLOCKDEV:
538
      return self.logical_id[1]
539
    elif self.dev_type == constants.LD_RBD:
540
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
541
    return None
542

    
543
  def ChildrenNeeded(self):
544
    """Compute the needed number of children for activation.
545

546
    This method will return either -1 (all children) or a positive
547
    number denoting the minimum number of children needed for
548
    activation (only mirrored devices will usually return >=0).
549

550
    Currently, only DRBD8 supports diskless activation (therefore we
551
    return 0), for all other we keep the previous semantics and return
552
    -1.
553

554
    """
555
    if self.dev_type == constants.LD_DRBD8:
556
      return 0
557
    return -1
558

    
559
  def IsBasedOnDiskType(self, dev_type):
560
    """Check if the disk or its children are based on the given type.
561

562
    @type dev_type: L{constants.LDS_BLOCK}
563
    @param dev_type: the type to look for
564
    @rtype: boolean
565
    @return: boolean indicating if a device of the given type was found or not
566

567
    """
568
    if self.children:
569
      for child in self.children:
570
        if child.IsBasedOnDiskType(dev_type):
571
          return True
572
    return self.dev_type == dev_type
573

    
574
  def GetNodes(self, node_uuid):
575
    """This function returns the nodes this device lives on.
576

577
    Given the node on which the parent of the device lives on (or, in
578
    case of a top-level device, the primary node of the devices'
579
    instance), this function will return a list of nodes on which this
580
    devices needs to (or can) be assembled.
581

582
    """
583
    if self.dev_type in [constants.LD_LV, constants.LD_FILE,
584
                         constants.LD_BLOCKDEV, constants.LD_RBD,
585
                         constants.LD_EXT]:
586
      result = [node_uuid]
587
    elif self.dev_type in constants.LDS_DRBD:
588
      result = [self.logical_id[0], self.logical_id[1]]
589
      if node_uuid not in result:
590
        raise errors.ConfigurationError("DRBD device passed unknown node")
591
    else:
592
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
593
    return result
594

    
595
  def ComputeNodeTree(self, parent_node_uuid):
596
    """Compute the node/disk tree for this disk and its children.
597

598
    This method, given the node on which the parent disk lives, will
599
    return the list of all (node UUID, disk) pairs which describe the disk
600
    tree in the most compact way. For example, a drbd/lvm stack
601
    will be returned as (primary_node, drbd) and (secondary_node, drbd)
602
    which represents all the top-level devices on the nodes.
603

604
    """
605
    my_nodes = self.GetNodes(parent_node_uuid)
606
    result = [(node, self) for node in my_nodes]
607
    if not self.children:
608
      # leaf device
609
      return result
610
    for node in my_nodes:
611
      for child in self.children:
612
        child_result = child.ComputeNodeTree(node)
613
        if len(child_result) == 1:
614
          # child (and all its descendants) is simple, doesn't split
615
          # over multiple hosts, so we don't need to describe it, our
616
          # own entry for this node describes it completely
617
          continue
618
        else:
619
          # check if child nodes differ from my nodes; note that
620
          # subdisk can differ from the child itself, and be instead
621
          # one of its descendants
622
          for subnode, subdisk in child_result:
623
            if subnode not in my_nodes:
624
              result.append((subnode, subdisk))
625
            # otherwise child is under our own node, so we ignore this
626
            # entry (but probably the other results in the list will
627
            # be different)
628
    return result
629

    
630
  def ComputeGrowth(self, amount):
631
    """Compute the per-VG growth requirements.
632

633
    This only works for VG-based disks.
634

635
    @type amount: integer
636
    @param amount: the desired increase in (user-visible) disk space
637
    @rtype: dict
638
    @return: a dictionary of volume-groups and the required size
639

640
    """
641
    if self.dev_type == constants.LD_LV:
642
      return {self.logical_id[0]: amount}
643
    elif self.dev_type == constants.LD_DRBD8:
644
      if self.children:
645
        return self.children[0].ComputeGrowth(amount)
646
      else:
647
        return {}
648
    else:
649
      # Other disk types do not require VG space
650
      return {}
651

    
652
  def RecordGrow(self, amount):
653
    """Update the size of this disk after growth.
654

655
    This method recurses over the disks's children and updates their
656
    size correspondigly. The method needs to be kept in sync with the
657
    actual algorithms from bdev.
658

659
    """
660
    if self.dev_type in (constants.LD_LV, constants.LD_FILE,
661
                         constants.LD_RBD, constants.LD_EXT):
662
      self.size += amount
663
    elif self.dev_type == constants.LD_DRBD8:
664
      if self.children:
665
        self.children[0].RecordGrow(amount)
666
      self.size += amount
667
    else:
668
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
669
                                   " disk type %s" % self.dev_type)
670

    
671
  def Update(self, size=None, mode=None, spindles=None):
672
    """Apply changes to size, spindles and mode.
673

674
    """
675
    if self.dev_type == constants.LD_DRBD8:
676
      if self.children:
677
        self.children[0].Update(size=size, mode=mode)
678
    else:
679
      assert not self.children
680

    
681
    if size is not None:
682
      self.size = size
683
    if mode is not None:
684
      self.mode = mode
685
    if spindles is not None:
686
      self.spindles = spindles
687

    
688
  def UnsetSize(self):
689
    """Sets recursively the size to zero for the disk and its children.
690

691
    """
692
    if self.children:
693
      for child in self.children:
694
        child.UnsetSize()
695
    self.size = 0
696

    
697
  def SetPhysicalID(self, target_node_uuid, nodes_ip):
698
    """Convert the logical ID to the physical ID.
699

700
    This is used only for drbd, which needs ip/port configuration.
701

702
    The routine descends down and updates its children also, because
703
    this helps when the only the top device is passed to the remote
704
    node.
705

706
    Arguments:
707
      - target_node_uuid: the node UUID we wish to configure for
708
      - nodes_ip: a mapping of node name to ip
709

710
    The target_node must exist in in nodes_ip, and must be one of the
711
    nodes in the logical ID for each of the DRBD devices encountered
712
    in the disk tree.
713

714
    """
715
    if self.children:
716
      for child in self.children:
717
        child.SetPhysicalID(target_node_uuid, nodes_ip)
718

    
719
    if self.logical_id is None and self.physical_id is not None:
720
      return
721
    if self.dev_type in constants.LDS_DRBD:
722
      pnode_uuid, snode_uuid, port, pminor, sminor, secret = self.logical_id
723
      if target_node_uuid not in (pnode_uuid, snode_uuid):
724
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
725
                                        target_node_uuid)
726
      pnode_ip = nodes_ip.get(pnode_uuid, None)
727
      snode_ip = nodes_ip.get(snode_uuid, None)
728
      if pnode_ip is None or snode_ip is None:
729
        raise errors.ConfigurationError("Can't find primary or secondary node"
730
                                        " for %s" % str(self))
731
      p_data = (pnode_ip, port)
732
      s_data = (snode_ip, port)
733
      if pnode_uuid == target_node_uuid:
734
        self.physical_id = p_data + s_data + (pminor, secret)
735
      else: # it must be secondary, we tested above
736
        self.physical_id = s_data + p_data + (sminor, secret)
737
    else:
738
      self.physical_id = self.logical_id
739
    return
740

    
741
  def ToDict(self):
742
    """Disk-specific conversion to standard python types.
743

744
    This replaces the children lists of objects with lists of
745
    standard python types.
746

747
    """
748
    bo = super(Disk, self).ToDict()
749

    
750
    for attr in ("children",):
751
      alist = bo.get(attr, None)
752
      if alist:
753
        bo[attr] = outils.ContainerToDicts(alist)
754
    return bo
755

    
756
  @classmethod
757
  def FromDict(cls, val):
758
    """Custom function for Disks
759

760
    """
761
    obj = super(Disk, cls).FromDict(val)
762
    if obj.children:
763
      obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
764
    if obj.logical_id and isinstance(obj.logical_id, list):
765
      obj.logical_id = tuple(obj.logical_id)
766
    if obj.physical_id and isinstance(obj.physical_id, list):
767
      obj.physical_id = tuple(obj.physical_id)
768
    if obj.dev_type in constants.LDS_DRBD:
769
      # we need a tuple of length six here
770
      if len(obj.logical_id) < 6:
771
        obj.logical_id += (None,) * (6 - len(obj.logical_id))
772
    return obj
773

    
774
  def __str__(self):
775
    """Custom str() formatter for disks.
776

777
    """
778
    if self.dev_type == constants.LD_LV:
779
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
780
    elif self.dev_type in constants.LDS_DRBD:
781
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
782
      val = "<DRBD8("
783
      if self.physical_id is None:
784
        phy = "unconfigured"
785
      else:
786
        phy = ("configured as %s:%s %s:%s" %
787
               (self.physical_id[0], self.physical_id[1],
788
                self.physical_id[2], self.physical_id[3]))
789

    
790
      val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
791
              (node_a, minor_a, node_b, minor_b, port, phy))
792
      if self.children and self.children.count(None) == 0:
793
        val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
794
      else:
795
        val += "no local storage"
796
    else:
797
      val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
798
             (self.dev_type, self.logical_id, self.physical_id, self.children))
799
    if self.iv_name is None:
800
      val += ", not visible"
801
    else:
802
      val += ", visible as /dev/%s" % self.iv_name
803
    if self.spindles is not None:
804
      val += ", spindles=%s" % self.spindles
805
    if isinstance(self.size, int):
806
      val += ", size=%dm)>" % self.size
807
    else:
808
      val += ", size='%s')>" % (self.size,)
809
    return val
810

    
811
  def Verify(self):
812
    """Checks that this disk is correctly configured.
813

814
    """
815
    all_errors = []
816
    if self.mode not in constants.DISK_ACCESS_SET:
817
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
818
    return all_errors
819

    
820
  def UpgradeConfig(self):
821
    """Fill defaults for missing configuration values.
822

823
    """
824
    if self.children:
825
      for child in self.children:
826
        child.UpgradeConfig()
827

    
828
    # FIXME: Make this configurable in Ganeti 2.7
829
    self.params = {}
830
    # add here config upgrade for this disk
831

    
832
  @staticmethod
833
  def ComputeLDParams(disk_template, disk_params):
834
    """Computes Logical Disk parameters from Disk Template parameters.
835

836
    @type disk_template: string
837
    @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
838
    @type disk_params: dict
839
    @param disk_params: disk template parameters;
840
                        dict(template_name -> parameters
841
    @rtype: list(dict)
842
    @return: a list of dicts, one for each node of the disk hierarchy. Each dict
843
      contains the LD parameters of the node. The tree is flattened in-order.
844

845
    """
846
    if disk_template not in constants.DISK_TEMPLATES:
847
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
848

    
849
    assert disk_template in disk_params
850

    
851
    result = list()
852
    dt_params = disk_params[disk_template]
853
    if disk_template == constants.DT_DRBD8:
854
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8], {
855
        constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
856
        constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
857
        constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
858
        constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
859
        constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
860
        constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
861
        constants.LDP_PROTOCOL: dt_params[constants.DRBD_PROTOCOL],
862
        constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
863
        constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
864
        constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
865
        constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
866
        constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
867
        constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
868
        }))
869

    
870
      # data LV
871
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
872
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
873
        }))
874

    
875
      # metadata LV
876
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
877
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
878
        }))
879

    
880
    elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
881
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
882

    
883
    elif disk_template == constants.DT_PLAIN:
884
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
885
        constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
886
        }))
887

    
888
    elif disk_template == constants.DT_BLOCK:
889
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
890

    
891
    elif disk_template == constants.DT_RBD:
892
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD], {
893
        constants.LDP_POOL: dt_params[constants.RBD_POOL],
894
        }))
895

    
896
    elif disk_template == constants.DT_EXT:
897
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_EXT])
898

    
899
    return result
900

    
901

    
902
class InstancePolicy(ConfigObject):
903
  """Config object representing instance policy limits dictionary.
904

905
  Note that this object is not actually used in the config, it's just
906
  used as a placeholder for a few functions.
907

908
  """
909
  @classmethod
910
  def CheckParameterSyntax(cls, ipolicy, check_std):
911
    """ Check the instance policy for validity.
912

913
    @type ipolicy: dict
914
    @param ipolicy: dictionary with min/max/std specs and policies
915
    @type check_std: bool
916
    @param check_std: Whether to check std value or just assume compliance
917
    @raise errors.ConfigurationError: when the policy is not legal
918

919
    """
920
    InstancePolicy.CheckISpecSyntax(ipolicy, check_std)
921
    if constants.IPOLICY_DTS in ipolicy:
922
      InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
923
    for key in constants.IPOLICY_PARAMETERS:
924
      if key in ipolicy:
925
        InstancePolicy.CheckParameter(key, ipolicy[key])
926
    wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
927
    if wrong_keys:
928
      raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
929
                                      utils.CommaJoin(wrong_keys))
930

    
931
  @classmethod
932
  def _CheckIncompleteSpec(cls, spec, keyname):
933
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
934
    if missing_params:
935
      msg = ("Missing instance specs parameters for %s: %s" %
936
             (keyname, utils.CommaJoin(missing_params)))
937
      raise errors.ConfigurationError(msg)
938

    
939
  @classmethod
940
  def CheckISpecSyntax(cls, ipolicy, check_std):
941
    """Check the instance policy specs for validity.
942

943
    @type ipolicy: dict
944
    @param ipolicy: dictionary with min/max/std specs
945
    @type check_std: bool
946
    @param check_std: Whether to check std value or just assume compliance
947
    @raise errors.ConfigurationError: when specs are not valid
948

949
    """
950
    if constants.ISPECS_MINMAX not in ipolicy:
951
      # Nothing to check
952
      return
953

    
954
    if check_std and constants.ISPECS_STD not in ipolicy:
955
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
956
      raise errors.ConfigurationError(msg)
957
    stdspec = ipolicy.get(constants.ISPECS_STD)
958
    if check_std:
959
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
960

    
961
    if not ipolicy[constants.ISPECS_MINMAX]:
962
      raise errors.ConfigurationError("Empty minmax specifications")
963
    std_is_good = False
964
    for minmaxspecs in ipolicy[constants.ISPECS_MINMAX]:
965
      missing = constants.ISPECS_MINMAX_KEYS - frozenset(minmaxspecs.keys())
966
      if missing:
967
        msg = "Missing instance specification: %s" % utils.CommaJoin(missing)
968
        raise errors.ConfigurationError(msg)
969
      for (key, spec) in minmaxspecs.items():
970
        InstancePolicy._CheckIncompleteSpec(spec, key)
971

    
972
      spec_std_ok = True
973
      for param in constants.ISPECS_PARAMETERS:
974
        par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
975
                                                           param, check_std)
976
        spec_std_ok = spec_std_ok and par_std_ok
977
      std_is_good = std_is_good or spec_std_ok
978
    if not std_is_good:
979
      raise errors.ConfigurationError("Invalid std specifications")
980

    
981
  @classmethod
982
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
983
    """Check the instance policy specs for validity on a given key.
984

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

988
    @type minmaxspecs: dict
989
    @param minmaxspecs: dictionary with min and max instance spec
990
    @type stdspec: dict
991
    @param stdspec: dictionary with standard instance spec
992
    @type name: string
993
    @param name: what are the limits for
994
    @type check_std: bool
995
    @param check_std: Whether to check std value or just assume compliance
996
    @rtype: bool
997
    @return: C{True} when specs are valid, C{False} when standard spec for the
998
        given name is not valid
999
    @raise errors.ConfigurationError: when min/max specs for the given name
1000
        are not valid
1001

1002
    """
1003
    minspec = minmaxspecs[constants.ISPECS_MIN]
1004
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1005
    min_v = minspec[name]
1006
    max_v = maxspec[name]
1007

    
1008
    if min_v > max_v:
1009
      err = ("Invalid specification of min/max values for %s: %s/%s" %
1010
             (name, min_v, max_v))
1011
      raise errors.ConfigurationError(err)
1012
    elif check_std:
1013
      std_v = stdspec.get(name, min_v)
1014
      return std_v >= min_v and std_v <= max_v
1015
    else:
1016
      return True
1017

    
1018
  @classmethod
1019
  def CheckDiskTemplates(cls, disk_templates):
1020
    """Checks the disk templates for validity.
1021

1022
    """
1023
    if not disk_templates:
1024
      raise errors.ConfigurationError("Instance policy must contain" +
1025
                                      " at least one disk template")
1026
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1027
    if wrong:
1028
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1029
                                      utils.CommaJoin(wrong))
1030

    
1031
  @classmethod
1032
  def CheckParameter(cls, key, value):
1033
    """Checks a parameter.
1034

1035
    Currently we expect all parameters to be float values.
1036

1037
    """
1038
    try:
1039
      float(value)
1040
    except (TypeError, ValueError), err:
1041
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1042
                                      " '%s', error: %s" % (key, value, err))
1043

    
1044

    
1045
class Instance(TaggableObject):
1046
  """Config object representing an instance."""
1047
  __slots__ = [
1048
    "name",
1049
    "primary_node",
1050
    "os",
1051
    "hypervisor",
1052
    "hvparams",
1053
    "beparams",
1054
    "osparams",
1055
    "admin_state",
1056
    "nics",
1057
    "disks",
1058
    "disk_template",
1059
    "disks_active",
1060
    "network_port",
1061
    "serial_no",
1062
    ] + _TIMESTAMPS + _UUID
1063

    
1064
  def _ComputeSecondaryNodes(self):
1065
    """Compute the list of secondary nodes.
1066

1067
    This is a simple wrapper over _ComputeAllNodes.
1068

1069
    """
1070
    all_nodes = set(self._ComputeAllNodes())
1071
    all_nodes.discard(self.primary_node)
1072
    return tuple(all_nodes)
1073

    
1074
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1075
                             "List of names of secondary nodes")
1076

    
1077
  def _ComputeAllNodes(self):
1078
    """Compute the list of all nodes.
1079

1080
    Since the data is already there (in the drbd disks), keeping it as
1081
    a separate normal attribute is redundant and if not properly
1082
    synchronised can cause problems. Thus it's better to compute it
1083
    dynamically.
1084

1085
    """
1086
    def _Helper(nodes, device):
1087
      """Recursively computes nodes given a top device."""
1088
      if device.dev_type in constants.LDS_DRBD:
1089
        nodea, nodeb = device.logical_id[:2]
1090
        nodes.add(nodea)
1091
        nodes.add(nodeb)
1092
      if device.children:
1093
        for child in device.children:
1094
          _Helper(nodes, child)
1095

    
1096
    all_nodes = set()
1097
    all_nodes.add(self.primary_node)
1098
    for device in self.disks:
1099
      _Helper(all_nodes, device)
1100
    return tuple(all_nodes)
1101

    
1102
  all_nodes = property(_ComputeAllNodes, None, None,
1103
                       "List of names of all the nodes of the instance")
1104

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

1108
    This function figures out what logical volumes should belong on
1109
    which nodes, recursing through a device tree.
1110

1111
    @type lvmap: dict
1112
    @param lvmap: optional dictionary to receive the
1113
        'node' : ['lv', ...] data.
1114
    @type devs: list of L{Disk}
1115
    @param devs: disks to get the LV name for. If None, all disk of this
1116
        instance are used.
1117
    @type node_uuid: string
1118
    @param node_uuid: UUID of the node to get the LV names for. If None, the
1119
        primary node of this instance is used.
1120
    @return: None if lvmap arg is given, otherwise, a dictionary of
1121
        the form { 'node_uuid' : ['volume1', 'volume2', ...], ... };
1122
        volumeN is of the form "vg_name/lv_name", compatible with
1123
        GetVolumeList()
1124

1125
    """
1126
    if node_uuid is None:
1127
      node_uuid = self.primary_node
1128

    
1129
    if lvmap is None:
1130
      lvmap = {
1131
        node_uuid: [],
1132
        }
1133
      ret = lvmap
1134
    else:
1135
      if not node_uuid in lvmap:
1136
        lvmap[node_uuid] = []
1137
      ret = None
1138

    
1139
    if not devs:
1140
      devs = self.disks
1141

    
1142
    for dev in devs:
1143
      if dev.dev_type == constants.LD_LV:
1144
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1145

    
1146
      elif dev.dev_type in constants.LDS_DRBD:
1147
        if dev.children:
1148
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1149
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1150

    
1151
      elif dev.children:
1152
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1153

    
1154
    return ret
1155

    
1156
  def FindDisk(self, idx):
1157
    """Find a disk given having a specified index.
1158

1159
    This is just a wrapper that does validation of the index.
1160

1161
    @type idx: int
1162
    @param idx: the disk index
1163
    @rtype: L{Disk}
1164
    @return: the corresponding disk
1165
    @raise errors.OpPrereqError: when the given index is not valid
1166

1167
    """
1168
    try:
1169
      idx = int(idx)
1170
      return self.disks[idx]
1171
    except (TypeError, ValueError), err:
1172
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1173
                                 errors.ECODE_INVAL)
1174
    except IndexError:
1175
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1176
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1177
                                 errors.ECODE_INVAL)
1178

    
1179
  def ToDict(self):
1180
    """Instance-specific conversion to standard python types.
1181

1182
    This replaces the children lists of objects with lists of standard
1183
    python types.
1184

1185
    """
1186
    bo = super(Instance, self).ToDict()
1187

    
1188
    for attr in "nics", "disks":
1189
      alist = bo.get(attr, None)
1190
      if alist:
1191
        nlist = outils.ContainerToDicts(alist)
1192
      else:
1193
        nlist = []
1194
      bo[attr] = nlist
1195
    return bo
1196

    
1197
  @classmethod
1198
  def FromDict(cls, val):
1199
    """Custom function for instances.
1200

1201
    """
1202
    if "admin_state" not in val:
1203
      if val.get("admin_up", False):
1204
        val["admin_state"] = constants.ADMINST_UP
1205
      else:
1206
        val["admin_state"] = constants.ADMINST_DOWN
1207
    if "admin_up" in val:
1208
      del val["admin_up"]
1209
    obj = super(Instance, cls).FromDict(val)
1210
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1211
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1212
    return obj
1213

    
1214
  def UpgradeConfig(self):
1215
    """Fill defaults for missing configuration values.
1216

1217
    """
1218
    for nic in self.nics:
1219
      nic.UpgradeConfig()
1220
    for disk in self.disks:
1221
      disk.UpgradeConfig()
1222
    if self.hvparams:
1223
      for key in constants.HVC_GLOBALS:
1224
        try:
1225
          del self.hvparams[key]
1226
        except KeyError:
1227
          pass
1228
    if self.osparams is None:
1229
      self.osparams = {}
1230
    UpgradeBeParams(self.beparams)
1231
    if self.disks_active is None:
1232
      self.disks_active = self.admin_state == constants.ADMINST_UP
1233

    
1234

    
1235
class OS(ConfigObject):
1236
  """Config object representing an operating system.
1237

1238
  @type supported_parameters: list
1239
  @ivar supported_parameters: a list of tuples, name and description,
1240
      containing the supported parameters by this OS
1241

1242
  @type VARIANT_DELIM: string
1243
  @cvar VARIANT_DELIM: the variant delimiter
1244

1245
  """
1246
  __slots__ = [
1247
    "name",
1248
    "path",
1249
    "api_versions",
1250
    "create_script",
1251
    "export_script",
1252
    "import_script",
1253
    "rename_script",
1254
    "verify_script",
1255
    "supported_variants",
1256
    "supported_parameters",
1257
    ]
1258

    
1259
  VARIANT_DELIM = "+"
1260

    
1261
  @classmethod
1262
  def SplitNameVariant(cls, name):
1263
    """Splits the name into the proper name and variant.
1264

1265
    @param name: the OS (unprocessed) name
1266
    @rtype: list
1267
    @return: a list of two elements; if the original name didn't
1268
        contain a variant, it's returned as an empty string
1269

1270
    """
1271
    nv = name.split(cls.VARIANT_DELIM, 1)
1272
    if len(nv) == 1:
1273
      nv.append("")
1274
    return nv
1275

    
1276
  @classmethod
1277
  def GetName(cls, name):
1278
    """Returns the proper name of the os (without the variant).
1279

1280
    @param name: the OS (unprocessed) name
1281

1282
    """
1283
    return cls.SplitNameVariant(name)[0]
1284

    
1285
  @classmethod
1286
  def GetVariant(cls, name):
1287
    """Returns the variant the os (without the base name).
1288

1289
    @param name: the OS (unprocessed) name
1290

1291
    """
1292
    return cls.SplitNameVariant(name)[1]
1293

    
1294

    
1295
class ExtStorage(ConfigObject):
1296
  """Config object representing an External Storage Provider.
1297

1298
  """
1299
  __slots__ = [
1300
    "name",
1301
    "path",
1302
    "create_script",
1303
    "remove_script",
1304
    "grow_script",
1305
    "attach_script",
1306
    "detach_script",
1307
    "setinfo_script",
1308
    "verify_script",
1309
    "supported_parameters",
1310
    ]
1311

    
1312

    
1313
class NodeHvState(ConfigObject):
1314
  """Hypvervisor state on a node.
1315

1316
  @ivar mem_total: Total amount of memory
1317
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1318
    available)
1319
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1320
    rounding
1321
  @ivar mem_inst: Memory used by instances living on node
1322
  @ivar cpu_total: Total node CPU core count
1323
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1324

1325
  """
1326
  __slots__ = [
1327
    "mem_total",
1328
    "mem_node",
1329
    "mem_hv",
1330
    "mem_inst",
1331
    "cpu_total",
1332
    "cpu_node",
1333
    ] + _TIMESTAMPS
1334

    
1335

    
1336
class NodeDiskState(ConfigObject):
1337
  """Disk state on a node.
1338

1339
  """
1340
  __slots__ = [
1341
    "total",
1342
    "reserved",
1343
    "overhead",
1344
    ] + _TIMESTAMPS
1345

    
1346

    
1347
class Node(TaggableObject):
1348
  """Config object representing a node.
1349

1350
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1351
  @ivar hv_state_static: Hypervisor state overriden by user
1352
  @ivar disk_state: Disk state (e.g. free space)
1353
  @ivar disk_state_static: Disk state overriden by user
1354

1355
  """
1356
  __slots__ = [
1357
    "name",
1358
    "primary_ip",
1359
    "secondary_ip",
1360
    "serial_no",
1361
    "master_candidate",
1362
    "offline",
1363
    "drained",
1364
    "group",
1365
    "master_capable",
1366
    "vm_capable",
1367
    "ndparams",
1368
    "powered",
1369
    "hv_state",
1370
    "hv_state_static",
1371
    "disk_state",
1372
    "disk_state_static",
1373
    ] + _TIMESTAMPS + _UUID
1374

    
1375
  def UpgradeConfig(self):
1376
    """Fill defaults for missing configuration values.
1377

1378
    """
1379
    # pylint: disable=E0203
1380
    # because these are "defined" via slots, not manually
1381
    if self.master_capable is None:
1382
      self.master_capable = True
1383

    
1384
    if self.vm_capable is None:
1385
      self.vm_capable = True
1386

    
1387
    if self.ndparams is None:
1388
      self.ndparams = {}
1389
    # And remove any global parameter
1390
    for key in constants.NDC_GLOBALS:
1391
      if key in self.ndparams:
1392
        logging.warning("Ignoring %s node parameter for node %s",
1393
                        key, self.name)
1394
        del self.ndparams[key]
1395

    
1396
    if self.powered is None:
1397
      self.powered = True
1398

    
1399
  def ToDict(self):
1400
    """Custom function for serializing.
1401

1402
    """
1403
    data = super(Node, self).ToDict()
1404

    
1405
    hv_state = data.get("hv_state", None)
1406
    if hv_state is not None:
1407
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1408

    
1409
    disk_state = data.get("disk_state", None)
1410
    if disk_state is not None:
1411
      data["disk_state"] = \
1412
        dict((key, outils.ContainerToDicts(value))
1413
             for (key, value) in disk_state.items())
1414

    
1415
    return data
1416

    
1417
  @classmethod
1418
  def FromDict(cls, val):
1419
    """Custom function for deserializing.
1420

1421
    """
1422
    obj = super(Node, cls).FromDict(val)
1423

    
1424
    if obj.hv_state is not None:
1425
      obj.hv_state = \
1426
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1427

    
1428
    if obj.disk_state is not None:
1429
      obj.disk_state = \
1430
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1431
             for (key, value) in obj.disk_state.items())
1432

    
1433
    return obj
1434

    
1435

    
1436
class NodeGroup(TaggableObject):
1437
  """Config object representing a node group."""
1438
  __slots__ = [
1439
    "name",
1440
    "members",
1441
    "ndparams",
1442
    "diskparams",
1443
    "ipolicy",
1444
    "serial_no",
1445
    "hv_state_static",
1446
    "disk_state_static",
1447
    "alloc_policy",
1448
    "networks",
1449
    ] + _TIMESTAMPS + _UUID
1450

    
1451
  def ToDict(self):
1452
    """Custom function for nodegroup.
1453

1454
    This discards the members object, which gets recalculated and is only kept
1455
    in memory.
1456

1457
    """
1458
    mydict = super(NodeGroup, self).ToDict()
1459
    del mydict["members"]
1460
    return mydict
1461

    
1462
  @classmethod
1463
  def FromDict(cls, val):
1464
    """Custom function for nodegroup.
1465

1466
    The members slot is initialized to an empty list, upon deserialization.
1467

1468
    """
1469
    obj = super(NodeGroup, cls).FromDict(val)
1470
    obj.members = []
1471
    return obj
1472

    
1473
  def UpgradeConfig(self):
1474
    """Fill defaults for missing configuration values.
1475

1476
    """
1477
    if self.ndparams is None:
1478
      self.ndparams = {}
1479

    
1480
    if self.serial_no is None:
1481
      self.serial_no = 1
1482

    
1483
    if self.alloc_policy is None:
1484
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1485

    
1486
    # We only update mtime, and not ctime, since we would not be able
1487
    # to provide a correct value for creation time.
1488
    if self.mtime is None:
1489
      self.mtime = time.time()
1490

    
1491
    if self.diskparams is None:
1492
      self.diskparams = {}
1493
    if self.ipolicy is None:
1494
      self.ipolicy = MakeEmptyIPolicy()
1495

    
1496
    if self.networks is None:
1497
      self.networks = {}
1498

    
1499
  def FillND(self, node):
1500
    """Return filled out ndparams for L{objects.Node}
1501

1502
    @type node: L{objects.Node}
1503
    @param node: A Node object to fill
1504
    @return a copy of the node's ndparams with defaults filled
1505

1506
    """
1507
    return self.SimpleFillND(node.ndparams)
1508

    
1509
  def SimpleFillND(self, ndparams):
1510
    """Fill a given ndparams dict with defaults.
1511

1512
    @type ndparams: dict
1513
    @param ndparams: the dict to fill
1514
    @rtype: dict
1515
    @return: a copy of the passed in ndparams with missing keys filled
1516
        from the node group defaults
1517

1518
    """
1519
    return FillDict(self.ndparams, ndparams)
1520

    
1521

    
1522
class Cluster(TaggableObject):
1523
  """Config object representing the cluster."""
1524
  __slots__ = [
1525
    "serial_no",
1526
    "rsahostkeypub",
1527
    "dsahostkeypub",
1528
    "highest_used_port",
1529
    "tcpudp_port_pool",
1530
    "mac_prefix",
1531
    "volume_group_name",
1532
    "reserved_lvs",
1533
    "drbd_usermode_helper",
1534
    "default_bridge",
1535
    "default_hypervisor",
1536
    "master_node",
1537
    "master_ip",
1538
    "master_netdev",
1539
    "master_netmask",
1540
    "use_external_mip_script",
1541
    "cluster_name",
1542
    "file_storage_dir",
1543
    "shared_file_storage_dir",
1544
    "enabled_hypervisors",
1545
    "hvparams",
1546
    "ipolicy",
1547
    "os_hvp",
1548
    "beparams",
1549
    "osparams",
1550
    "nicparams",
1551
    "ndparams",
1552
    "diskparams",
1553
    "candidate_pool_size",
1554
    "modify_etc_hosts",
1555
    "modify_ssh_setup",
1556
    "maintain_node_health",
1557
    "uid_pool",
1558
    "default_iallocator",
1559
    "hidden_os",
1560
    "blacklisted_os",
1561
    "primary_ip_family",
1562
    "prealloc_wipe_disks",
1563
    "hv_state_static",
1564
    "disk_state_static",
1565
    "enabled_disk_templates",
1566
    ] + _TIMESTAMPS + _UUID
1567

    
1568
  def UpgradeConfig(self):
1569
    """Fill defaults for missing configuration values.
1570

1571
    """
1572
    # pylint: disable=E0203
1573
    # because these are "defined" via slots, not manually
1574
    if self.hvparams is None:
1575
      self.hvparams = constants.HVC_DEFAULTS
1576
    else:
1577
      for hypervisor in self.hvparams:
1578
        self.hvparams[hypervisor] = FillDict(
1579
            constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1580

    
1581
    if self.os_hvp is None:
1582
      self.os_hvp = {}
1583

    
1584
    # osparams added before 2.2
1585
    if self.osparams is None:
1586
      self.osparams = {}
1587

    
1588
    self.ndparams = UpgradeNDParams(self.ndparams)
1589

    
1590
    self.beparams = UpgradeGroupedParams(self.beparams,
1591
                                         constants.BEC_DEFAULTS)
1592
    for beparams_group in self.beparams:
1593
      UpgradeBeParams(self.beparams[beparams_group])
1594

    
1595
    migrate_default_bridge = not self.nicparams
1596
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1597
                                          constants.NICC_DEFAULTS)
1598
    if migrate_default_bridge:
1599
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1600
        self.default_bridge
1601

    
1602
    if self.modify_etc_hosts is None:
1603
      self.modify_etc_hosts = True
1604

    
1605
    if self.modify_ssh_setup is None:
1606
      self.modify_ssh_setup = True
1607

    
1608
    # default_bridge is no longer used in 2.1. The slot is left there to
1609
    # support auto-upgrading. It can be removed once we decide to deprecate
1610
    # upgrading straight from 2.0.
1611
    if self.default_bridge is not None:
1612
      self.default_bridge = None
1613

    
1614
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1615
    # code can be removed once upgrading straight from 2.0 is deprecated.
1616
    if self.default_hypervisor is not None:
1617
      self.enabled_hypervisors = ([self.default_hypervisor] +
1618
                                  [hvname for hvname in self.enabled_hypervisors
1619
                                   if hvname != self.default_hypervisor])
1620
      self.default_hypervisor = None
1621

    
1622
    # maintain_node_health added after 2.1.1
1623
    if self.maintain_node_health is None:
1624
      self.maintain_node_health = False
1625

    
1626
    if self.uid_pool is None:
1627
      self.uid_pool = []
1628

    
1629
    if self.default_iallocator is None:
1630
      self.default_iallocator = ""
1631

    
1632
    # reserved_lvs added before 2.2
1633
    if self.reserved_lvs is None:
1634
      self.reserved_lvs = []
1635

    
1636
    # hidden and blacklisted operating systems added before 2.2.1
1637
    if self.hidden_os is None:
1638
      self.hidden_os = []
1639

    
1640
    if self.blacklisted_os is None:
1641
      self.blacklisted_os = []
1642

    
1643
    # primary_ip_family added before 2.3
1644
    if self.primary_ip_family is None:
1645
      self.primary_ip_family = AF_INET
1646

    
1647
    if self.master_netmask is None:
1648
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1649
      self.master_netmask = ipcls.iplen
1650

    
1651
    if self.prealloc_wipe_disks is None:
1652
      self.prealloc_wipe_disks = False
1653

    
1654
    # shared_file_storage_dir added before 2.5
1655
    if self.shared_file_storage_dir is None:
1656
      self.shared_file_storage_dir = ""
1657

    
1658
    if self.use_external_mip_script is None:
1659
      self.use_external_mip_script = False
1660

    
1661
    if self.diskparams:
1662
      self.diskparams = UpgradeDiskParams(self.diskparams)
1663
    else:
1664
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1665

    
1666
    # instance policy added before 2.6
1667
    if self.ipolicy is None:
1668
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1669
    else:
1670
      # we can either make sure to upgrade the ipolicy always, or only
1671
      # do it in some corner cases (e.g. missing keys); note that this
1672
      # will break any removal of keys from the ipolicy dict
1673
      wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1674
      if wrongkeys:
1675
        # These keys would be silently removed by FillIPolicy()
1676
        msg = ("Cluster instance policy contains spurious keys: %s" %
1677
               utils.CommaJoin(wrongkeys))
1678
        raise errors.ConfigurationError(msg)
1679
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1680

    
1681
  @property
1682
  def primary_hypervisor(self):
1683
    """The first hypervisor is the primary.
1684

1685
    Useful, for example, for L{Node}'s hv/disk state.
1686

1687
    """
1688
    return self.enabled_hypervisors[0]
1689

    
1690
  def ToDict(self):
1691
    """Custom function for cluster.
1692

1693
    """
1694
    mydict = super(Cluster, self).ToDict()
1695

    
1696
    if self.tcpudp_port_pool is None:
1697
      tcpudp_port_pool = []
1698
    else:
1699
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1700

    
1701
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1702

    
1703
    return mydict
1704

    
1705
  @classmethod
1706
  def FromDict(cls, val):
1707
    """Custom function for cluster.
1708

1709
    """
1710
    obj = super(Cluster, cls).FromDict(val)
1711

    
1712
    if obj.tcpudp_port_pool is None:
1713
      obj.tcpudp_port_pool = set()
1714
    elif not isinstance(obj.tcpudp_port_pool, set):
1715
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1716

    
1717
    return obj
1718

    
1719
  def SimpleFillDP(self, diskparams):
1720
    """Fill a given diskparams dict with cluster defaults.
1721

1722
    @param diskparams: The diskparams
1723
    @return: The defaults dict
1724

1725
    """
1726
    return FillDiskParams(self.diskparams, diskparams)
1727

    
1728
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1729
    """Get the default hypervisor parameters for the cluster.
1730

1731
    @param hypervisor: the hypervisor name
1732
    @param os_name: if specified, we'll also update the defaults for this OS
1733
    @param skip_keys: if passed, list of keys not to use
1734
    @return: the defaults dict
1735

1736
    """
1737
    if skip_keys is None:
1738
      skip_keys = []
1739

    
1740
    fill_stack = [self.hvparams.get(hypervisor, {})]
1741
    if os_name is not None:
1742
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1743
      fill_stack.append(os_hvp)
1744

    
1745
    ret_dict = {}
1746
    for o_dict in fill_stack:
1747
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1748

    
1749
    return ret_dict
1750

    
1751
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1752
    """Fill a given hvparams dict with cluster defaults.
1753

1754
    @type hv_name: string
1755
    @param hv_name: the hypervisor to use
1756
    @type os_name: string
1757
    @param os_name: the OS to use for overriding the hypervisor defaults
1758
    @type skip_globals: boolean
1759
    @param skip_globals: if True, the global hypervisor parameters will
1760
        not be filled
1761
    @rtype: dict
1762
    @return: a copy of the given hvparams with missing keys filled from
1763
        the cluster defaults
1764

1765
    """
1766
    if skip_globals:
1767
      skip_keys = constants.HVC_GLOBALS
1768
    else:
1769
      skip_keys = []
1770

    
1771
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1772
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1773

    
1774
  def FillHV(self, instance, skip_globals=False):
1775
    """Fill an instance's hvparams dict with cluster defaults.
1776

1777
    @type instance: L{objects.Instance}
1778
    @param instance: the instance parameter to fill
1779
    @type skip_globals: boolean
1780
    @param skip_globals: if True, the global hypervisor parameters will
1781
        not be filled
1782
    @rtype: dict
1783
    @return: a copy of the instance's hvparams with missing keys filled from
1784
        the cluster defaults
1785

1786
    """
1787
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1788
                             instance.hvparams, skip_globals)
1789

    
1790
  def SimpleFillBE(self, beparams):
1791
    """Fill a given beparams dict with cluster defaults.
1792

1793
    @type beparams: dict
1794
    @param beparams: the dict to fill
1795
    @rtype: dict
1796
    @return: a copy of the passed in beparams with missing keys filled
1797
        from the cluster defaults
1798

1799
    """
1800
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1801

    
1802
  def FillBE(self, instance):
1803
    """Fill an instance's beparams dict with cluster defaults.
1804

1805
    @type instance: L{objects.Instance}
1806
    @param instance: the instance parameter to fill
1807
    @rtype: dict
1808
    @return: a copy of the instance's beparams with missing keys filled from
1809
        the cluster defaults
1810

1811
    """
1812
    return self.SimpleFillBE(instance.beparams)
1813

    
1814
  def SimpleFillNIC(self, nicparams):
1815
    """Fill a given nicparams dict with cluster defaults.
1816

1817
    @type nicparams: dict
1818
    @param nicparams: the dict to fill
1819
    @rtype: dict
1820
    @return: a copy of the passed in nicparams with missing keys filled
1821
        from the cluster defaults
1822

1823
    """
1824
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1825

    
1826
  def SimpleFillOS(self, os_name, os_params):
1827
    """Fill an instance's osparams dict with cluster defaults.
1828

1829
    @type os_name: string
1830
    @param os_name: the OS name to use
1831
    @type os_params: dict
1832
    @param os_params: the dict to fill with default values
1833
    @rtype: dict
1834
    @return: a copy of the instance's osparams with missing keys filled from
1835
        the cluster defaults
1836

1837
    """
1838
    name_only = os_name.split("+", 1)[0]
1839
    # base OS
1840
    result = self.osparams.get(name_only, {})
1841
    # OS with variant
1842
    result = FillDict(result, self.osparams.get(os_name, {}))
1843
    # specified params
1844
    return FillDict(result, os_params)
1845

    
1846
  @staticmethod
1847
  def SimpleFillHvState(hv_state):
1848
    """Fill an hv_state sub dict with cluster defaults.
1849

1850
    """
1851
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1852

    
1853
  @staticmethod
1854
  def SimpleFillDiskState(disk_state):
1855
    """Fill an disk_state sub dict with cluster defaults.
1856

1857
    """
1858
    return FillDict(constants.DS_DEFAULTS, disk_state)
1859

    
1860
  def FillND(self, node, nodegroup):
1861
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1862

1863
    @type node: L{objects.Node}
1864
    @param node: A Node object to fill
1865
    @type nodegroup: L{objects.NodeGroup}
1866
    @param nodegroup: A Node object to fill
1867
    @return a copy of the node's ndparams with defaults filled
1868

1869
    """
1870
    return self.SimpleFillND(nodegroup.FillND(node))
1871

    
1872
  def SimpleFillND(self, ndparams):
1873
    """Fill a given ndparams dict with defaults.
1874

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

1881
    """
1882
    return FillDict(self.ndparams, ndparams)
1883

    
1884
  def SimpleFillIPolicy(self, ipolicy):
1885
    """ Fill instance policy dict with defaults.
1886

1887
    @type ipolicy: dict
1888
    @param ipolicy: the dict to fill
1889
    @rtype: dict
1890
    @return: a copy of passed ipolicy with missing keys filled from
1891
      the cluster defaults
1892

1893
    """
1894
    return FillIPolicy(self.ipolicy, ipolicy)
1895

    
1896
  def IsDiskTemplateEnabled(self, disk_template):
1897
    """Checks if a particular disk template is enabled.
1898

1899
    """
1900
    return utils.storage.IsDiskTemplateEnabled(
1901
        disk_template, self.enabled_disk_templates)
1902

    
1903
  def IsFileStorageEnabled(self):
1904
    """Checks if file storage is enabled.
1905

1906
    """
1907
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1908

    
1909
  def IsSharedFileStorageEnabled(self):
1910
    """Checks if shared file storage is enabled.
1911

1912
    """
1913
    return utils.storage.IsSharedFileStorageEnabled(
1914
        self.enabled_disk_templates)
1915

    
1916

    
1917
class BlockDevStatus(ConfigObject):
1918
  """Config object representing the status of a block device."""
1919
  __slots__ = [
1920
    "dev_path",
1921
    "major",
1922
    "minor",
1923
    "sync_percent",
1924
    "estimated_time",
1925
    "is_degraded",
1926
    "ldisk_status",
1927
    ]
1928

    
1929

    
1930
class ImportExportStatus(ConfigObject):
1931
  """Config object representing the status of an import or export."""
1932
  __slots__ = [
1933
    "recent_output",
1934
    "listen_port",
1935
    "connected",
1936
    "progress_mbytes",
1937
    "progress_throughput",
1938
    "progress_eta",
1939
    "progress_percent",
1940
    "exit_status",
1941
    "error_message",
1942
    ] + _TIMESTAMPS
1943

    
1944

    
1945
class ImportExportOptions(ConfigObject):
1946
  """Options for import/export daemon
1947

1948
  @ivar key_name: X509 key name (None for cluster certificate)
1949
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1950
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
1951
  @ivar magic: Used to ensure the connection goes to the right disk
1952
  @ivar ipv6: Whether to use IPv6
1953
  @ivar connect_timeout: Number of seconds for establishing connection
1954

1955
  """
1956
  __slots__ = [
1957
    "key_name",
1958
    "ca_pem",
1959
    "compress",
1960
    "magic",
1961
    "ipv6",
1962
    "connect_timeout",
1963
    ]
1964

    
1965

    
1966
class ConfdRequest(ConfigObject):
1967
  """Object holding a confd request.
1968

1969
  @ivar protocol: confd protocol version
1970
  @ivar type: confd query type
1971
  @ivar query: query request
1972
  @ivar rsalt: requested reply salt
1973

1974
  """
1975
  __slots__ = [
1976
    "protocol",
1977
    "type",
1978
    "query",
1979
    "rsalt",
1980
    ]
1981

    
1982

    
1983
class ConfdReply(ConfigObject):
1984
  """Object holding a confd reply.
1985

1986
  @ivar protocol: confd protocol version
1987
  @ivar status: reply status code (ok, error)
1988
  @ivar answer: confd query reply
1989
  @ivar serial: configuration serial number
1990

1991
  """
1992
  __slots__ = [
1993
    "protocol",
1994
    "status",
1995
    "answer",
1996
    "serial",
1997
    ]
1998

    
1999

    
2000
class QueryFieldDefinition(ConfigObject):
2001
  """Object holding a query field definition.
2002

2003
  @ivar name: Field name
2004
  @ivar title: Human-readable title
2005
  @ivar kind: Field type
2006
  @ivar doc: Human-readable description
2007

2008
  """
2009
  __slots__ = [
2010
    "name",
2011
    "title",
2012
    "kind",
2013
    "doc",
2014
    ]
2015

    
2016

    
2017
class _QueryResponseBase(ConfigObject):
2018
  __slots__ = [
2019
    "fields",
2020
    ]
2021

    
2022
  def ToDict(self):
2023
    """Custom function for serializing.
2024

2025
    """
2026
    mydict = super(_QueryResponseBase, self).ToDict()
2027
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2028
    return mydict
2029

    
2030
  @classmethod
2031
  def FromDict(cls, val):
2032
    """Custom function for de-serializing.
2033

2034
    """
2035
    obj = super(_QueryResponseBase, cls).FromDict(val)
2036
    obj.fields = \
2037
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2038
    return obj
2039

    
2040

    
2041
class QueryResponse(_QueryResponseBase):
2042
  """Object holding the response to a query.
2043

2044
  @ivar fields: List of L{QueryFieldDefinition} objects
2045
  @ivar data: Requested data
2046

2047
  """
2048
  __slots__ = [
2049
    "data",
2050
    ]
2051

    
2052

    
2053
class QueryFieldsRequest(ConfigObject):
2054
  """Object holding a request for querying available fields.
2055

2056
  """
2057
  __slots__ = [
2058
    "what",
2059
    "fields",
2060
    ]
2061

    
2062

    
2063
class QueryFieldsResponse(_QueryResponseBase):
2064
  """Object holding the response to a query for fields.
2065

2066
  @ivar fields: List of L{QueryFieldDefinition} objects
2067

2068
  """
2069
  __slots__ = []
2070

    
2071

    
2072
class MigrationStatus(ConfigObject):
2073
  """Object holding the status of a migration.
2074

2075
  """
2076
  __slots__ = [
2077
    "status",
2078
    "transferred_ram",
2079
    "total_ram",
2080
    ]
2081

    
2082

    
2083
class InstanceConsole(ConfigObject):
2084
  """Object describing how to access the console of an instance.
2085

2086
  """
2087
  __slots__ = [
2088
    "instance",
2089
    "kind",
2090
    "message",
2091
    "host",
2092
    "port",
2093
    "user",
2094
    "command",
2095
    "display",
2096
    ]
2097

    
2098
  def Validate(self):
2099
    """Validates contents of this object.
2100

2101
    """
2102
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2103
    assert self.instance, "Missing instance name"
2104
    assert self.message or self.kind in [constants.CONS_SSH,
2105
                                         constants.CONS_SPICE,
2106
                                         constants.CONS_VNC]
2107
    assert self.host or self.kind == constants.CONS_MESSAGE
2108
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2109
                                      constants.CONS_SSH]
2110
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2111
                                      constants.CONS_SPICE,
2112
                                      constants.CONS_VNC]
2113
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2114
                                         constants.CONS_SPICE,
2115
                                         constants.CONS_VNC]
2116
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2117
                                         constants.CONS_SPICE,
2118
                                         constants.CONS_SSH]
2119
    return True
2120

    
2121

    
2122
class Network(TaggableObject):
2123
  """Object representing a network definition for ganeti.
2124

2125
  """
2126
  __slots__ = [
2127
    "name",
2128
    "serial_no",
2129
    "mac_prefix",
2130
    "network",
2131
    "network6",
2132
    "gateway",
2133
    "gateway6",
2134
    "reservations",
2135
    "ext_reservations",
2136
    ] + _TIMESTAMPS + _UUID
2137

    
2138
  def HooksDict(self, prefix=""):
2139
    """Export a dictionary used by hooks with a network's information.
2140

2141
    @type prefix: String
2142
    @param prefix: Prefix to prepend to the dict entries
2143

2144
    """
2145
    result = {
2146
      "%sNETWORK_NAME" % prefix: self.name,
2147
      "%sNETWORK_UUID" % prefix: self.uuid,
2148
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2149
    }
2150
    if self.network:
2151
      result["%sNETWORK_SUBNET" % prefix] = self.network
2152
    if self.gateway:
2153
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2154
    if self.network6:
2155
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2156
    if self.gateway6:
2157
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2158
    if self.mac_prefix:
2159
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2160

    
2161
    return result
2162

    
2163
  @classmethod
2164
  def FromDict(cls, val):
2165
    """Custom function for networks.
2166

2167
    Remove deprecated network_type and family.
2168

2169
    """
2170
    if "network_type" in val:
2171
      del val["network_type"]
2172
    if "family" in val:
2173
      del val["family"]
2174
    obj = super(Network, cls).FromDict(val)
2175
    return obj
2176

    
2177

    
2178
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2179
  """Simple wrapper over ConfigParse that allows serialization.
2180

2181
  This class is basically ConfigParser.SafeConfigParser with two
2182
  additional methods that allow it to serialize/unserialize to/from a
2183
  buffer.
2184

2185
  """
2186
  def Dumps(self):
2187
    """Dump this instance and return the string representation."""
2188
    buf = StringIO()
2189
    self.write(buf)
2190
    return buf.getvalue()
2191

    
2192
  @classmethod
2193
  def Loads(cls, data):
2194
    """Load data from a string."""
2195
    buf = StringIO(data)
2196
    cfp = cls()
2197
    cfp.readfp(buf)
2198
    return cfp
2199

    
2200

    
2201
class LvmPvInfo(ConfigObject):
2202
  """Information about an LVM physical volume (PV).
2203

2204
  @type name: string
2205
  @ivar name: name of the PV
2206
  @type vg_name: string
2207
  @ivar vg_name: name of the volume group containing the PV
2208
  @type size: float
2209
  @ivar size: size of the PV in MiB
2210
  @type free: float
2211
  @ivar free: free space in the PV, in MiB
2212
  @type attributes: string
2213
  @ivar attributes: PV attributes
2214
  @type lv_list: list of strings
2215
  @ivar lv_list: names of the LVs hosted on the PV
2216
  """
2217
  __slots__ = [
2218
    "name",
2219
    "vg_name",
2220
    "size",
2221
    "free",
2222
    "attributes",
2223
    "lv_list"
2224
    ]
2225

    
2226
  def IsEmpty(self):
2227
    """Is this PV empty?
2228

2229
    """
2230
    return self.size <= (self.free + 1)
2231

    
2232
  def IsAllocatable(self):
2233
    """Is this PV allocatable?
2234

2235
    """
2236
    return ("a" in self.attributes)