Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ c66d8987

History | View | Annotate | Download (61.3 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, skip_keys=None):
86
  """Fills an instance policy with defaults.
87

88
  """
89
  assert frozenset(default_ipolicy.keys()) == constants.IPOLICY_ALL_KEYS
90
  ret_dict = {}
91
  for key in constants.IPOLICY_ISPECS:
92
    ret_dict[key] = FillDict(default_ipolicy[key],
93
                             custom_ipolicy.get(key, {}),
94
                             skip_keys=skip_keys)
95
  # list items
96
  for key in [constants.IPOLICY_DTS]:
97
    ret_dict[key] = list(custom_ipolicy.get(key, default_ipolicy[key]))
98
  # other items which we know we can directly copy (immutables)
99
  for key in constants.IPOLICY_PARAMETERS:
100
    ret_dict[key] = custom_ipolicy.get(key, default_ipolicy[key])
101

    
102
  return ret_dict
103

    
104

    
105
def FillDiskParams(default_dparams, custom_dparams, skip_keys=None):
106
  """Fills the disk parameter defaults.
107

108
  @see: L{FillDict} for parameters and return value
109

110
  """
111
  assert frozenset(default_dparams.keys()) == constants.DISK_TEMPLATES
112

    
113
  return dict((dt, FillDict(default_dparams[dt], custom_dparams.get(dt, {}),
114
                             skip_keys=skip_keys))
115
              for dt in constants.DISK_TEMPLATES)
116

    
117

    
118
def UpgradeGroupedParams(target, defaults):
119
  """Update all groups for the target parameter.
120

121
  @type target: dict of dicts
122
  @param target: {group: {parameter: value}}
123
  @type defaults: dict
124
  @param defaults: default parameter values
125

126
  """
127
  if target is None:
128
    target = {constants.PP_DEFAULT: defaults}
129
  else:
130
    for group in target:
131
      target[group] = FillDict(defaults, target[group])
132
  return target
133

    
134

    
135
def UpgradeBeParams(target):
136
  """Update the be parameters dict to the new format.
137

138
  @type target: dict
139
  @param target: "be" parameters dict
140

141
  """
142
  if constants.BE_MEMORY in target:
143
    memory = target[constants.BE_MEMORY]
144
    target[constants.BE_MAXMEM] = memory
145
    target[constants.BE_MINMEM] = memory
146
    del target[constants.BE_MEMORY]
147

    
148

    
149
def UpgradeDiskParams(diskparams):
150
  """Upgrade the disk parameters.
151

152
  @type diskparams: dict
153
  @param diskparams: disk parameters to upgrade
154
  @rtype: dict
155
  @return: the upgraded disk parameters dict
156

157
  """
158
  if not diskparams:
159
    result = {}
160
  else:
161
    result = FillDiskParams(constants.DISK_DT_DEFAULTS, diskparams)
162

    
163
  return result
164

    
165

    
166
def UpgradeNDParams(ndparams):
167
  """Upgrade ndparams structure.
168

169
  @type ndparams: dict
170
  @param ndparams: disk parameters to upgrade
171
  @rtype: dict
172
  @return: the upgraded node parameters dict
173

174
  """
175
  if ndparams is None:
176
    ndparams = {}
177

    
178
  if (constants.ND_OOB_PROGRAM in ndparams and
179
      ndparams[constants.ND_OOB_PROGRAM] is None):
180
    # will be reset by the line below
181
    del ndparams[constants.ND_OOB_PROGRAM]
182
  return FillDict(constants.NDC_DEFAULTS, ndparams)
183

    
184

    
185
def MakeEmptyIPolicy():
186
  """Create empty IPolicy dictionary.
187

188
  """
189
  return dict([
190
    (constants.ISPECS_MIN, {}),
191
    (constants.ISPECS_MAX, {}),
192
    (constants.ISPECS_STD, {}),
193
    ])
194

    
195

    
196
class ConfigObject(outils.ValidatedSlots):
197
  """A generic config object.
198

199
  It has the following properties:
200

201
    - provides somewhat safe recursive unpickling and pickling for its classes
202
    - unset attributes which are defined in slots are always returned
203
      as None instead of raising an error
204

205
  Classes derived from this must always declare __slots__ (we use many
206
  config objects and the memory reduction is useful)
207

208
  """
209
  __slots__ = []
210

    
211
  def __getattr__(self, name):
212
    if name not in self.GetAllSlots():
213
      raise AttributeError("Invalid object attribute %s.%s" %
214
                           (type(self).__name__, name))
215
    return None
216

    
217
  def __setstate__(self, state):
218
    slots = self.GetAllSlots()
219
    for name in state:
220
      if name in slots:
221
        setattr(self, name, state[name])
222

    
223
  def Validate(self):
224
    """Validates the slots.
225

226
    """
227

    
228
  def ToDict(self):
229
    """Convert to a dict holding only standard python types.
230

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

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

    
245
  __getstate__ = ToDict
246

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

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

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

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

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

270
    """
271
    dict_form = self.ToDict()
272
    clone_obj = self.__class__.FromDict(dict_form)
273
    return clone_obj
274

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

    
279
  def UpgradeConfig(self):
280
    """Fill defaults for missing configuration values.
281

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

285
    """
286
    pass
287

    
288

    
289
class TaggableObject(ConfigObject):
290
  """An generic class supporting tags.
291

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

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

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

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

    
314
  def GetTags(self):
315
    """Return the tags list.
316

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

    
323
  def AddTag(self, tag):
324
    """Add a new tag.
325

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

    
333
  def RemoveTag(self, tag):
334
    """Remove a tag.
335

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

    
344
  def ToDict(self):
345
    """Taggable-object-specific conversion to standard python types.
346

347
    This replaces the tags set with a list.
348

349
    """
350
    bo = super(TaggableObject, self).ToDict()
351

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

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

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

    
367

    
368
class MasterNetworkParameters(ConfigObject):
369
  """Network configuration parameters for the master
370

371
  @ivar name: master name
372
  @ivar ip: master IP
373
  @ivar netmask: master netmask
374
  @ivar netdev: master network device
375
  @ivar ip_family: master IP family
376

377
  """
378
  __slots__ = [
379
    "name",
380
    "ip",
381
    "netmask",
382
    "netdev",
383
    "ip_family",
384
    ]
385

    
386

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

    
399
  def ToDict(self):
400
    """Custom function for top-level config data.
401

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

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

    
411
    return mydict
412

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

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

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

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

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

    
443
  def UpgradeConfig(self):
444
    """Fill defaults for missing configuration values.
445

446
    """
447
    self.cluster.UpgradeConfig()
448
    for node in self.nodes.values():
449
      node.UpgradeConfig()
450
    for instance in self.instances.values():
451
      instance.UpgradeConfig()
452
    if self.nodegroups is None:
453
      self.nodegroups = {}
454
    for nodegroup in self.nodegroups.values():
455
      nodegroup.UpgradeConfig()
456
    if self.cluster.drbd_usermode_helper is None:
457
      # To decide if we set an helper let's check if at least one instance has
458
      # a DRBD disk. This does not cover all the possible scenarios but it
459
      # gives a good approximation.
460
      if self.HasAnyDiskOfType(constants.LD_DRBD8):
461
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
462
    if self.networks is None:
463
      self.networks = {}
464
    for network in self.networks.values():
465
      network.UpgradeConfig()
466
    self._UpgradeStorageTypes()
467

    
468
  def _UpgradeStorageTypes(self):
469
    """Upgrade the cluster's enabled storage types by inspecting the currently
470
       enabled and/or used storage types.
471

472
    """
473
    # enabled_storage_types in the cluster config were introduced in 2.8. Remove
474
    # this code once upgrading from earlier versions is deprecated.
475
    if not self.cluster.enabled_storage_types:
476
      storage_type_set = \
477
        set([constants.DISK_TEMPLATES_STORAGE_TYPE[inst.disk_template]
478
               for inst in self.instances.values()])
479
      # Add lvm, file and shared file storage, if they are enabled, even though
480
      # they might currently not be used.
481
      if self.cluster.volume_group_name:
482
        storage_type_set.add(constants.ST_LVM_VG)
483
      # FIXME: Adapt this when dis/enabling at configure time is removed.
484
      if constants.ENABLE_FILE_STORAGE:
485
        storage_type_set.add(constants.ST_FILE)
486
      if constants.ENABLE_SHARED_FILE_STORAGE:
487
        storage_type_set.add(constants.ST_SHARED_FILE)
488
      # Set enabled_storage_types to the inferred storage types. Order them
489
      # according to a preference list that is based on Ganeti's history of
490
      # supported storage types.
491
      self.cluster.enabled_storage_types = []
492
      for preferred_type in constants.STORAGE_TYPES_PREFERENCE:
493
        if preferred_type in storage_type_set:
494
          self.cluster.enabled_storage_types.append(preferred_type)
495
          storage_type_set.remove(preferred_type)
496
      self.cluster.enabled_storage_types.extend(list(storage_type_set))
497

    
498

    
499
class NIC(ConfigObject):
500
  """Config object representing a network card."""
501
  __slots__ = ["mac", "ip", "network", "nicparams", "netinfo"]
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__ = ["dev_type", "logical_id", "physical_id",
525
               "children", "iv_name", "size", "mode", "params"]
526

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

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

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

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

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

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

549
    """
550
    if self.dev_type == constants.LD_LV:
551
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
552
    elif self.dev_type == constants.LD_BLOCKDEV:
553
      return self.logical_id[1]
554
    elif self.dev_type == constants.LD_RBD:
555
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
556
    return None
557

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

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

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

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

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

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

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

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

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

597
    """
598
    if self.dev_type in [constants.LD_LV, constants.LD_FILE,
599
                         constants.LD_BLOCKDEV, constants.LD_RBD,
600
                         constants.LD_EXT]:
601
      result = [node]
602
    elif self.dev_type in constants.LDS_DRBD:
603
      result = [self.logical_id[0], self.logical_id[1]]
604
      if node not in result:
605
        raise errors.ConfigurationError("DRBD device passed unknown node")
606
    else:
607
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
608
    return result
609

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

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

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

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

648
    This only works for VG-based disks.
649

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

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

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

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

674
    """
675
    if self.dev_type in (constants.LD_LV, constants.LD_FILE,
676
                         constants.LD_RBD, constants.LD_EXT):
677
      self.size += amount
678
    elif self.dev_type == constants.LD_DRBD8:
679
      if self.children:
680
        self.children[0].RecordGrow(amount)
681
      self.size += amount
682
    else:
683
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
684
                                   " disk type %s" % self.dev_type)
685

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

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

    
696
    if size is not None:
697
      self.size = size
698
    if mode is not None:
699
      self.mode = mode
700

    
701
  def UnsetSize(self):
702
    """Sets recursively the size to zero for the disk and its children.
703

704
    """
705
    if self.children:
706
      for child in self.children:
707
        child.UnsetSize()
708
    self.size = 0
709

    
710
  def SetPhysicalID(self, target_node, nodes_ip):
711
    """Convert the logical ID to the physical ID.
712

713
    This is used only for drbd, which needs ip/port configuration.
714

715
    The routine descends down and updates its children also, because
716
    this helps when the only the top device is passed to the remote
717
    node.
718

719
    Arguments:
720
      - target_node: the node we wish to configure for
721
      - nodes_ip: a mapping of node name to ip
722

723
    The target_node must exist in in nodes_ip, and must be one of the
724
    nodes in the logical ID for each of the DRBD devices encountered
725
    in the disk tree.
726

727
    """
728
    if self.children:
729
      for child in self.children:
730
        child.SetPhysicalID(target_node, nodes_ip)
731

    
732
    if self.logical_id is None and self.physical_id is not None:
733
      return
734
    if self.dev_type in constants.LDS_DRBD:
735
      pnode, snode, port, pminor, sminor, secret = self.logical_id
736
      if target_node not in (pnode, snode):
737
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
738
                                        target_node)
739
      pnode_ip = nodes_ip.get(pnode, None)
740
      snode_ip = nodes_ip.get(snode, None)
741
      if pnode_ip is None or snode_ip is None:
742
        raise errors.ConfigurationError("Can't find primary or secondary node"
743
                                        " for %s" % str(self))
744
      p_data = (pnode_ip, port)
745
      s_data = (snode_ip, port)
746
      if pnode == target_node:
747
        self.physical_id = p_data + s_data + (pminor, secret)
748
      else: # it must be secondary, we tested above
749
        self.physical_id = s_data + p_data + (sminor, secret)
750
    else:
751
      self.physical_id = self.logical_id
752
    return
753

    
754
  def ToDict(self):
755
    """Disk-specific conversion to standard python types.
756

757
    This replaces the children lists of objects with lists of
758
    standard python types.
759

760
    """
761
    bo = super(Disk, self).ToDict()
762

    
763
    for attr in ("children",):
764
      alist = bo.get(attr, None)
765
      if alist:
766
        bo[attr] = outils.ContainerToDicts(alist)
767
    return bo
768

    
769
  @classmethod
770
  def FromDict(cls, val):
771
    """Custom function for Disks
772

773
    """
774
    obj = super(Disk, cls).FromDict(val)
775
    if obj.children:
776
      obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
777
    if obj.logical_id and isinstance(obj.logical_id, list):
778
      obj.logical_id = tuple(obj.logical_id)
779
    if obj.physical_id and isinstance(obj.physical_id, list):
780
      obj.physical_id = tuple(obj.physical_id)
781
    if obj.dev_type in constants.LDS_DRBD:
782
      # we need a tuple of length six here
783
      if len(obj.logical_id) < 6:
784
        obj.logical_id += (None,) * (6 - len(obj.logical_id))
785
    return obj
786

    
787
  def __str__(self):
788
    """Custom str() formatter for disks.
789

790
    """
791
    if self.dev_type == constants.LD_LV:
792
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
793
    elif self.dev_type in constants.LDS_DRBD:
794
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
795
      val = "<DRBD8("
796
      if self.physical_id is None:
797
        phy = "unconfigured"
798
      else:
799
        phy = ("configured as %s:%s %s:%s" %
800
               (self.physical_id[0], self.physical_id[1],
801
                self.physical_id[2], self.physical_id[3]))
802

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

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

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

    
831
  def UpgradeConfig(self):
832
    """Fill defaults for missing configuration values.
833

834
    """
835
    if self.children:
836
      for child in self.children:
837
        child.UpgradeConfig()
838

    
839
    # FIXME: Make this configurable in Ganeti 2.7
840
    self.params = {}
841
    # add here config upgrade for this disk
842

    
843
  @staticmethod
844
  def ComputeLDParams(disk_template, disk_params):
845
    """Computes Logical Disk parameters from Disk Template parameters.
846

847
    @type disk_template: string
848
    @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
849
    @type disk_params: dict
850
    @param disk_params: disk template parameters;
851
                        dict(template_name -> parameters
852
    @rtype: list(dict)
853
    @return: a list of dicts, one for each node of the disk hierarchy. Each dict
854
      contains the LD parameters of the node. The tree is flattened in-order.
855

856
    """
857
    if disk_template not in constants.DISK_TEMPLATES:
858
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
859

    
860
    assert disk_template in disk_params
861

    
862
    result = list()
863
    dt_params = disk_params[disk_template]
864
    if disk_template == constants.DT_DRBD8:
865
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8], {
866
        constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
867
        constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
868
        constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
869
        constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
870
        constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
871
        constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
872
        constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
873
        constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
874
        constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
875
        constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
876
        constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
877
        constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
878
        }))
879

    
880
      # data LV
881
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
882
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
883
        }))
884

    
885
      # metadata LV
886
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
887
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
888
        }))
889

    
890
    elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
891
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
892

    
893
    elif disk_template == constants.DT_PLAIN:
894
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
895
        constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
896
        }))
897

    
898
    elif disk_template == constants.DT_BLOCK:
899
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
900

    
901
    elif disk_template == constants.DT_RBD:
902
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD], {
903
        constants.LDP_POOL: dt_params[constants.RBD_POOL],
904
        }))
905

    
906
    elif disk_template == constants.DT_EXT:
907
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_EXT])
908

    
909
    return result
910

    
911

    
912
class InstancePolicy(ConfigObject):
913
  """Config object representing instance policy limits dictionary.
914

915

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

919
  """
920
  @classmethod
921
  def CheckParameterSyntax(cls, ipolicy, check_std):
922
    """ Check the instance policy for validity.
923

924
    """
925
    for param in constants.ISPECS_PARAMETERS:
926
      InstancePolicy.CheckISpecSyntax(ipolicy, param, check_std)
927
    if constants.IPOLICY_DTS in ipolicy:
928
      InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
929
    for key in constants.IPOLICY_PARAMETERS:
930
      if key in ipolicy:
931
        InstancePolicy.CheckParameter(key, ipolicy[key])
932
    wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
933
    if wrong_keys:
934
      raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
935
                                      utils.CommaJoin(wrong_keys))
936

    
937
  @classmethod
938
  def CheckISpecSyntax(cls, ipolicy, name, check_std):
939
    """Check the instance policy for validity on a given key.
940

941
    We check if the instance policy makes sense for a given key, that is
942
    if ipolicy[min][name] <= ipolicy[std][name] <= ipolicy[max][name].
943

944
    @type ipolicy: dict
945
    @param ipolicy: dictionary with min, max, std specs
946
    @type name: string
947
    @param name: what are the limits for
948
    @type check_std: bool
949
    @param check_std: Whether to check std value or just assume compliance
950
    @raise errors.ConfigureError: when specs for given name are not valid
951

952
    """
953
    min_v = ipolicy[constants.ISPECS_MIN].get(name, 0)
954

    
955
    if check_std:
956
      std_v = ipolicy[constants.ISPECS_STD].get(name, min_v)
957
      std_msg = std_v
958
    else:
959
      std_v = min_v
960
      std_msg = "-"
961

    
962
    max_v = ipolicy[constants.ISPECS_MAX].get(name, std_v)
963
    err = ("Invalid specification of min/max/std values for %s: %s/%s/%s" %
964
           (name,
965
            ipolicy[constants.ISPECS_MIN].get(name, "-"),
966
            ipolicy[constants.ISPECS_MAX].get(name, "-"),
967
            std_msg))
968
    if min_v > std_v or std_v > max_v:
969
      raise errors.ConfigurationError(err)
970

    
971
  @classmethod
972
  def CheckDiskTemplates(cls, disk_templates):
973
    """Checks the disk templates for validity.
974

975
    """
976
    if not disk_templates:
977
      raise errors.ConfigurationError("Instance policy must contain" +
978
                                      " at least one disk template")
979
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
980
    if wrong:
981
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
982
                                      utils.CommaJoin(wrong))
983

    
984
  @classmethod
985
  def CheckParameter(cls, key, value):
986
    """Checks a parameter.
987

988
    Currently we expect all parameters to be float values.
989

990
    """
991
    try:
992
      float(value)
993
    except (TypeError, ValueError), err:
994
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
995
                                      " '%s', error: %s" % (key, value, err))
996

    
997

    
998
class Instance(TaggableObject):
999
  """Config object representing an instance."""
1000
  __slots__ = [
1001
    "name",
1002
    "primary_node",
1003
    "os",
1004
    "hypervisor",
1005
    "hvparams",
1006
    "beparams",
1007
    "osparams",
1008
    "admin_state",
1009
    "nics",
1010
    "disks",
1011
    "disk_template",
1012
    "network_port",
1013
    "serial_no",
1014
    ] + _TIMESTAMPS + _UUID
1015

    
1016
  def _ComputeSecondaryNodes(self):
1017
    """Compute the list of secondary nodes.
1018

1019
    This is a simple wrapper over _ComputeAllNodes.
1020

1021
    """
1022
    all_nodes = set(self._ComputeAllNodes())
1023
    all_nodes.discard(self.primary_node)
1024
    return tuple(all_nodes)
1025

    
1026
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1027
                             "List of names of secondary nodes")
1028

    
1029
  def _ComputeAllNodes(self):
1030
    """Compute the list of all nodes.
1031

1032
    Since the data is already there (in the drbd disks), keeping it as
1033
    a separate normal attribute is redundant and if not properly
1034
    synchronised can cause problems. Thus it's better to compute it
1035
    dynamically.
1036

1037
    """
1038
    def _Helper(nodes, device):
1039
      """Recursively computes nodes given a top device."""
1040
      if device.dev_type in constants.LDS_DRBD:
1041
        nodea, nodeb = device.logical_id[:2]
1042
        nodes.add(nodea)
1043
        nodes.add(nodeb)
1044
      if device.children:
1045
        for child in device.children:
1046
          _Helper(nodes, child)
1047

    
1048
    all_nodes = set()
1049
    all_nodes.add(self.primary_node)
1050
    for device in self.disks:
1051
      _Helper(all_nodes, device)
1052
    return tuple(all_nodes)
1053

    
1054
  all_nodes = property(_ComputeAllNodes, None, None,
1055
                       "List of names of all the nodes of the instance")
1056

    
1057
  def MapLVsByNode(self, lvmap=None, devs=None, node=None):
1058
    """Provide a mapping of nodes to LVs this instance owns.
1059

1060
    This function figures out what logical volumes should belong on
1061
    which nodes, recursing through a device tree.
1062

1063
    @param lvmap: optional dictionary to receive the
1064
        'node' : ['lv', ...] data.
1065

1066
    @return: None if lvmap arg is given, otherwise, a dictionary of
1067
        the form { 'nodename' : ['volume1', 'volume2', ...], ... };
1068
        volumeN is of the form "vg_name/lv_name", compatible with
1069
        GetVolumeList()
1070

1071
    """
1072
    if node is None:
1073
      node = self.primary_node
1074

    
1075
    if lvmap is None:
1076
      lvmap = {
1077
        node: [],
1078
        }
1079
      ret = lvmap
1080
    else:
1081
      if not node in lvmap:
1082
        lvmap[node] = []
1083
      ret = None
1084

    
1085
    if not devs:
1086
      devs = self.disks
1087

    
1088
    for dev in devs:
1089
      if dev.dev_type == constants.LD_LV:
1090
        lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1091

    
1092
      elif dev.dev_type in constants.LDS_DRBD:
1093
        if dev.children:
1094
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1095
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1096

    
1097
      elif dev.children:
1098
        self.MapLVsByNode(lvmap, dev.children, node)
1099

    
1100
    return ret
1101

    
1102
  def FindDisk(self, idx):
1103
    """Find a disk given having a specified index.
1104

1105
    This is just a wrapper that does validation of the index.
1106

1107
    @type idx: int
1108
    @param idx: the disk index
1109
    @rtype: L{Disk}
1110
    @return: the corresponding disk
1111
    @raise errors.OpPrereqError: when the given index is not valid
1112

1113
    """
1114
    try:
1115
      idx = int(idx)
1116
      return self.disks[idx]
1117
    except (TypeError, ValueError), err:
1118
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1119
                                 errors.ECODE_INVAL)
1120
    except IndexError:
1121
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1122
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1123
                                 errors.ECODE_INVAL)
1124

    
1125
  def ToDict(self):
1126
    """Instance-specific conversion to standard python types.
1127

1128
    This replaces the children lists of objects with lists of standard
1129
    python types.
1130

1131
    """
1132
    bo = super(Instance, self).ToDict()
1133

    
1134
    for attr in "nics", "disks":
1135
      alist = bo.get(attr, None)
1136
      if alist:
1137
        nlist = outils.ContainerToDicts(alist)
1138
      else:
1139
        nlist = []
1140
      bo[attr] = nlist
1141
    return bo
1142

    
1143
  @classmethod
1144
  def FromDict(cls, val):
1145
    """Custom function for instances.
1146

1147
    """
1148
    if "admin_state" not in val:
1149
      if val.get("admin_up", False):
1150
        val["admin_state"] = constants.ADMINST_UP
1151
      else:
1152
        val["admin_state"] = constants.ADMINST_DOWN
1153
    if "admin_up" in val:
1154
      del val["admin_up"]
1155
    obj = super(Instance, cls).FromDict(val)
1156
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1157
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1158
    return obj
1159

    
1160
  def UpgradeConfig(self):
1161
    """Fill defaults for missing configuration values.
1162

1163
    """
1164
    for nic in self.nics:
1165
      nic.UpgradeConfig()
1166
    for disk in self.disks:
1167
      disk.UpgradeConfig()
1168
    if self.hvparams:
1169
      for key in constants.HVC_GLOBALS:
1170
        try:
1171
          del self.hvparams[key]
1172
        except KeyError:
1173
          pass
1174
    if self.osparams is None:
1175
      self.osparams = {}
1176
    UpgradeBeParams(self.beparams)
1177

    
1178

    
1179
class OS(ConfigObject):
1180
  """Config object representing an operating system.
1181

1182
  @type supported_parameters: list
1183
  @ivar supported_parameters: a list of tuples, name and description,
1184
      containing the supported parameters by this OS
1185

1186
  @type VARIANT_DELIM: string
1187
  @cvar VARIANT_DELIM: the variant delimiter
1188

1189
  """
1190
  __slots__ = [
1191
    "name",
1192
    "path",
1193
    "api_versions",
1194
    "create_script",
1195
    "export_script",
1196
    "import_script",
1197
    "rename_script",
1198
    "verify_script",
1199
    "supported_variants",
1200
    "supported_parameters",
1201
    ]
1202

    
1203
  VARIANT_DELIM = "+"
1204

    
1205
  @classmethod
1206
  def SplitNameVariant(cls, name):
1207
    """Splits the name into the proper name and variant.
1208

1209
    @param name: the OS (unprocessed) name
1210
    @rtype: list
1211
    @return: a list of two elements; if the original name didn't
1212
        contain a variant, it's returned as an empty string
1213

1214
    """
1215
    nv = name.split(cls.VARIANT_DELIM, 1)
1216
    if len(nv) == 1:
1217
      nv.append("")
1218
    return nv
1219

    
1220
  @classmethod
1221
  def GetName(cls, name):
1222
    """Returns the proper name of the os (without the variant).
1223

1224
    @param name: the OS (unprocessed) name
1225

1226
    """
1227
    return cls.SplitNameVariant(name)[0]
1228

    
1229
  @classmethod
1230
  def GetVariant(cls, name):
1231
    """Returns the variant the os (without the base name).
1232

1233
    @param name: the OS (unprocessed) name
1234

1235
    """
1236
    return cls.SplitNameVariant(name)[1]
1237

    
1238

    
1239
class ExtStorage(ConfigObject):
1240
  """Config object representing an External Storage Provider.
1241

1242
  """
1243
  __slots__ = [
1244
    "name",
1245
    "path",
1246
    "create_script",
1247
    "remove_script",
1248
    "grow_script",
1249
    "attach_script",
1250
    "detach_script",
1251
    "setinfo_script",
1252
    "verify_script",
1253
    "supported_parameters",
1254
    ]
1255

    
1256

    
1257
class NodeHvState(ConfigObject):
1258
  """Hypvervisor state on a node.
1259

1260
  @ivar mem_total: Total amount of memory
1261
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1262
    available)
1263
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1264
    rounding
1265
  @ivar mem_inst: Memory used by instances living on node
1266
  @ivar cpu_total: Total node CPU core count
1267
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1268

1269
  """
1270
  __slots__ = [
1271
    "mem_total",
1272
    "mem_node",
1273
    "mem_hv",
1274
    "mem_inst",
1275
    "cpu_total",
1276
    "cpu_node",
1277
    ] + _TIMESTAMPS
1278

    
1279

    
1280
class NodeDiskState(ConfigObject):
1281
  """Disk state on a node.
1282

1283
  """
1284
  __slots__ = [
1285
    "total",
1286
    "reserved",
1287
    "overhead",
1288
    ] + _TIMESTAMPS
1289

    
1290

    
1291
class Node(TaggableObject):
1292
  """Config object representing a node.
1293

1294
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1295
  @ivar hv_state_static: Hypervisor state overriden by user
1296
  @ivar disk_state: Disk state (e.g. free space)
1297
  @ivar disk_state_static: Disk state overriden by user
1298

1299
  """
1300
  __slots__ = [
1301
    "name",
1302
    "primary_ip",
1303
    "secondary_ip",
1304
    "serial_no",
1305
    "master_candidate",
1306
    "offline",
1307
    "drained",
1308
    "group",
1309
    "master_capable",
1310
    "vm_capable",
1311
    "ndparams",
1312
    "powered",
1313
    "hv_state",
1314
    "hv_state_static",
1315
    "disk_state",
1316
    "disk_state_static",
1317
    ] + _TIMESTAMPS + _UUID
1318

    
1319
  def UpgradeConfig(self):
1320
    """Fill defaults for missing configuration values.
1321

1322
    """
1323
    # pylint: disable=E0203
1324
    # because these are "defined" via slots, not manually
1325
    if self.master_capable is None:
1326
      self.master_capable = True
1327

    
1328
    if self.vm_capable is None:
1329
      self.vm_capable = True
1330

    
1331
    if self.ndparams is None:
1332
      self.ndparams = {}
1333
    # And remove any global parameter
1334
    for key in constants.NDC_GLOBALS:
1335
      if key in self.ndparams:
1336
        logging.warning("Ignoring %s node parameter for node %s",
1337
                        key, self.name)
1338
        del self.ndparams[key]
1339

    
1340
    if self.powered is None:
1341
      self.powered = True
1342

    
1343
  def ToDict(self):
1344
    """Custom function for serializing.
1345

1346
    """
1347
    data = super(Node, self).ToDict()
1348

    
1349
    hv_state = data.get("hv_state", None)
1350
    if hv_state is not None:
1351
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1352

    
1353
    disk_state = data.get("disk_state", None)
1354
    if disk_state is not None:
1355
      data["disk_state"] = \
1356
        dict((key, outils.ContainerToDicts(value))
1357
             for (key, value) in disk_state.items())
1358

    
1359
    return data
1360

    
1361
  @classmethod
1362
  def FromDict(cls, val):
1363
    """Custom function for deserializing.
1364

1365
    """
1366
    obj = super(Node, cls).FromDict(val)
1367

    
1368
    if obj.hv_state is not None:
1369
      obj.hv_state = \
1370
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1371

    
1372
    if obj.disk_state is not None:
1373
      obj.disk_state = \
1374
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1375
             for (key, value) in obj.disk_state.items())
1376

    
1377
    return obj
1378

    
1379

    
1380
class NodeGroup(TaggableObject):
1381
  """Config object representing a node group."""
1382
  __slots__ = [
1383
    "name",
1384
    "members",
1385
    "ndparams",
1386
    "diskparams",
1387
    "ipolicy",
1388
    "serial_no",
1389
    "hv_state_static",
1390
    "disk_state_static",
1391
    "alloc_policy",
1392
    "networks",
1393
    ] + _TIMESTAMPS + _UUID
1394

    
1395
  def ToDict(self):
1396
    """Custom function for nodegroup.
1397

1398
    This discards the members object, which gets recalculated and is only kept
1399
    in memory.
1400

1401
    """
1402
    mydict = super(NodeGroup, self).ToDict()
1403
    del mydict["members"]
1404
    return mydict
1405

    
1406
  @classmethod
1407
  def FromDict(cls, val):
1408
    """Custom function for nodegroup.
1409

1410
    The members slot is initialized to an empty list, upon deserialization.
1411

1412
    """
1413
    obj = super(NodeGroup, cls).FromDict(val)
1414
    obj.members = []
1415
    return obj
1416

    
1417
  def UpgradeConfig(self):
1418
    """Fill defaults for missing configuration values.
1419

1420
    """
1421
    if self.ndparams is None:
1422
      self.ndparams = {}
1423

    
1424
    if self.serial_no is None:
1425
      self.serial_no = 1
1426

    
1427
    if self.alloc_policy is None:
1428
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1429

    
1430
    # We only update mtime, and not ctime, since we would not be able
1431
    # to provide a correct value for creation time.
1432
    if self.mtime is None:
1433
      self.mtime = time.time()
1434

    
1435
    if self.diskparams is None:
1436
      self.diskparams = {}
1437
    if self.ipolicy is None:
1438
      self.ipolicy = MakeEmptyIPolicy()
1439

    
1440
    if self.networks is None:
1441
      self.networks = {}
1442

    
1443
  def FillND(self, node):
1444
    """Return filled out ndparams for L{objects.Node}
1445

1446
    @type node: L{objects.Node}
1447
    @param node: A Node object to fill
1448
    @return a copy of the node's ndparams with defaults filled
1449

1450
    """
1451
    return self.SimpleFillND(node.ndparams)
1452

    
1453
  def SimpleFillND(self, ndparams):
1454
    """Fill a given ndparams dict with defaults.
1455

1456
    @type ndparams: dict
1457
    @param ndparams: the dict to fill
1458
    @rtype: dict
1459
    @return: a copy of the passed in ndparams with missing keys filled
1460
        from the node group defaults
1461

1462
    """
1463
    return FillDict(self.ndparams, ndparams)
1464

    
1465

    
1466
class Cluster(TaggableObject):
1467
  """Config object representing the cluster."""
1468
  __slots__ = [
1469
    "serial_no",
1470
    "rsahostkeypub",
1471
    "highest_used_port",
1472
    "tcpudp_port_pool",
1473
    "mac_prefix",
1474
    "volume_group_name",
1475
    "reserved_lvs",
1476
    "drbd_usermode_helper",
1477
    "default_bridge",
1478
    "default_hypervisor",
1479
    "master_node",
1480
    "master_ip",
1481
    "master_netdev",
1482
    "master_netmask",
1483
    "use_external_mip_script",
1484
    "cluster_name",
1485
    "file_storage_dir",
1486
    "shared_file_storage_dir",
1487
    "enabled_hypervisors",
1488
    "hvparams",
1489
    "ipolicy",
1490
    "os_hvp",
1491
    "beparams",
1492
    "osparams",
1493
    "nicparams",
1494
    "ndparams",
1495
    "diskparams",
1496
    "candidate_pool_size",
1497
    "modify_etc_hosts",
1498
    "modify_ssh_setup",
1499
    "maintain_node_health",
1500
    "uid_pool",
1501
    "default_iallocator",
1502
    "hidden_os",
1503
    "blacklisted_os",
1504
    "primary_ip_family",
1505
    "prealloc_wipe_disks",
1506
    "hv_state_static",
1507
    "disk_state_static",
1508
    "enabled_storage_types",
1509
    ] + _TIMESTAMPS + _UUID
1510

    
1511
  def UpgradeConfig(self):
1512
    """Fill defaults for missing configuration values.
1513

1514
    """
1515
    # pylint: disable=E0203
1516
    # because these are "defined" via slots, not manually
1517
    if self.hvparams is None:
1518
      self.hvparams = constants.HVC_DEFAULTS
1519
    else:
1520
      for hypervisor in self.hvparams:
1521
        self.hvparams[hypervisor] = FillDict(
1522
            constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1523

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

    
1527
    # osparams added before 2.2
1528
    if self.osparams is None:
1529
      self.osparams = {}
1530

    
1531
    self.ndparams = UpgradeNDParams(self.ndparams)
1532

    
1533
    self.beparams = UpgradeGroupedParams(self.beparams,
1534
                                         constants.BEC_DEFAULTS)
1535
    for beparams_group in self.beparams:
1536
      UpgradeBeParams(self.beparams[beparams_group])
1537

    
1538
    migrate_default_bridge = not self.nicparams
1539
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1540
                                          constants.NICC_DEFAULTS)
1541
    if migrate_default_bridge:
1542
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1543
        self.default_bridge
1544

    
1545
    if self.modify_etc_hosts is None:
1546
      self.modify_etc_hosts = True
1547

    
1548
    if self.modify_ssh_setup is None:
1549
      self.modify_ssh_setup = True
1550

    
1551
    # default_bridge is no longer used in 2.1. The slot is left there to
1552
    # support auto-upgrading. It can be removed once we decide to deprecate
1553
    # upgrading straight from 2.0.
1554
    if self.default_bridge is not None:
1555
      self.default_bridge = None
1556

    
1557
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1558
    # code can be removed once upgrading straight from 2.0 is deprecated.
1559
    if self.default_hypervisor is not None:
1560
      self.enabled_hypervisors = ([self.default_hypervisor] +
1561
                                  [hvname for hvname in self.enabled_hypervisors
1562
                                   if hvname != self.default_hypervisor])
1563
      self.default_hypervisor = None
1564

    
1565
    # maintain_node_health added after 2.1.1
1566
    if self.maintain_node_health is None:
1567
      self.maintain_node_health = False
1568

    
1569
    if self.uid_pool is None:
1570
      self.uid_pool = []
1571

    
1572
    if self.default_iallocator is None:
1573
      self.default_iallocator = ""
1574

    
1575
    # reserved_lvs added before 2.2
1576
    if self.reserved_lvs is None:
1577
      self.reserved_lvs = []
1578

    
1579
    # hidden and blacklisted operating systems added before 2.2.1
1580
    if self.hidden_os is None:
1581
      self.hidden_os = []
1582

    
1583
    if self.blacklisted_os is None:
1584
      self.blacklisted_os = []
1585

    
1586
    # primary_ip_family added before 2.3
1587
    if self.primary_ip_family is None:
1588
      self.primary_ip_family = AF_INET
1589

    
1590
    if self.master_netmask is None:
1591
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1592
      self.master_netmask = ipcls.iplen
1593

    
1594
    if self.prealloc_wipe_disks is None:
1595
      self.prealloc_wipe_disks = False
1596

    
1597
    # shared_file_storage_dir added before 2.5
1598
    if self.shared_file_storage_dir is None:
1599
      self.shared_file_storage_dir = ""
1600

    
1601
    if self.use_external_mip_script is None:
1602
      self.use_external_mip_script = False
1603

    
1604
    if self.diskparams:
1605
      self.diskparams = UpgradeDiskParams(self.diskparams)
1606
    else:
1607
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1608

    
1609
    # instance policy added before 2.6
1610
    if self.ipolicy is None:
1611
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1612
    else:
1613
      # we can either make sure to upgrade the ipolicy always, or only
1614
      # do it in some corner cases (e.g. missing keys); note that this
1615
      # will break any removal of keys from the ipolicy dict
1616
      wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1617
      if wrongkeys:
1618
        # These keys would be silently removed by FillIPolicy()
1619
        msg = ("Cluster instance policy contains spourious keys: %s" %
1620
               utils.CommaJoin(wrongkeys))
1621
        raise errors.ConfigurationError(msg)
1622
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1623

    
1624
  @property
1625
  def primary_hypervisor(self):
1626
    """The first hypervisor is the primary.
1627

1628
    Useful, for example, for L{Node}'s hv/disk state.
1629

1630
    """
1631
    return self.enabled_hypervisors[0]
1632

    
1633
  def ToDict(self):
1634
    """Custom function for cluster.
1635

1636
    """
1637
    mydict = super(Cluster, self).ToDict()
1638

    
1639
    if self.tcpudp_port_pool is None:
1640
      tcpudp_port_pool = []
1641
    else:
1642
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1643

    
1644
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1645

    
1646
    return mydict
1647

    
1648
  @classmethod
1649
  def FromDict(cls, val):
1650
    """Custom function for cluster.
1651

1652
    """
1653
    obj = super(Cluster, cls).FromDict(val)
1654

    
1655
    if obj.tcpudp_port_pool is None:
1656
      obj.tcpudp_port_pool = set()
1657
    elif not isinstance(obj.tcpudp_port_pool, set):
1658
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1659

    
1660
    return obj
1661

    
1662
  def SimpleFillDP(self, diskparams):
1663
    """Fill a given diskparams dict with cluster defaults.
1664

1665
    @param diskparams: The diskparams
1666
    @return: The defaults dict
1667

1668
    """
1669
    return FillDiskParams(self.diskparams, diskparams)
1670

    
1671
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1672
    """Get the default hypervisor parameters for the cluster.
1673

1674
    @param hypervisor: the hypervisor name
1675
    @param os_name: if specified, we'll also update the defaults for this OS
1676
    @param skip_keys: if passed, list of keys not to use
1677
    @return: the defaults dict
1678

1679
    """
1680
    if skip_keys is None:
1681
      skip_keys = []
1682

    
1683
    fill_stack = [self.hvparams.get(hypervisor, {})]
1684
    if os_name is not None:
1685
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1686
      fill_stack.append(os_hvp)
1687

    
1688
    ret_dict = {}
1689
    for o_dict in fill_stack:
1690
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1691

    
1692
    return ret_dict
1693

    
1694
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1695
    """Fill a given hvparams dict with cluster defaults.
1696

1697
    @type hv_name: string
1698
    @param hv_name: the hypervisor to use
1699
    @type os_name: string
1700
    @param os_name: the OS to use for overriding the hypervisor defaults
1701
    @type skip_globals: boolean
1702
    @param skip_globals: if True, the global hypervisor parameters will
1703
        not be filled
1704
    @rtype: dict
1705
    @return: a copy of the given hvparams with missing keys filled from
1706
        the cluster defaults
1707

1708
    """
1709
    if skip_globals:
1710
      skip_keys = constants.HVC_GLOBALS
1711
    else:
1712
      skip_keys = []
1713

    
1714
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1715
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1716

    
1717
  def FillHV(self, instance, skip_globals=False):
1718
    """Fill an instance's hvparams dict with cluster defaults.
1719

1720
    @type instance: L{objects.Instance}
1721
    @param instance: the instance parameter to fill
1722
    @type skip_globals: boolean
1723
    @param skip_globals: if True, the global hypervisor parameters will
1724
        not be filled
1725
    @rtype: dict
1726
    @return: a copy of the instance's hvparams with missing keys filled from
1727
        the cluster defaults
1728

1729
    """
1730
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1731
                             instance.hvparams, skip_globals)
1732

    
1733
  def SimpleFillBE(self, beparams):
1734
    """Fill a given beparams dict with cluster defaults.
1735

1736
    @type beparams: dict
1737
    @param beparams: the dict to fill
1738
    @rtype: dict
1739
    @return: a copy of the passed in beparams with missing keys filled
1740
        from the cluster defaults
1741

1742
    """
1743
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1744

    
1745
  def FillBE(self, instance):
1746
    """Fill an instance's beparams dict with cluster defaults.
1747

1748
    @type instance: L{objects.Instance}
1749
    @param instance: the instance parameter to fill
1750
    @rtype: dict
1751
    @return: a copy of the instance's beparams with missing keys filled from
1752
        the cluster defaults
1753

1754
    """
1755
    return self.SimpleFillBE(instance.beparams)
1756

    
1757
  def SimpleFillNIC(self, nicparams):
1758
    """Fill a given nicparams dict with cluster defaults.
1759

1760
    @type nicparams: dict
1761
    @param nicparams: the dict to fill
1762
    @rtype: dict
1763
    @return: a copy of the passed in nicparams with missing keys filled
1764
        from the cluster defaults
1765

1766
    """
1767
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1768

    
1769
  def SimpleFillOS(self, os_name, os_params):
1770
    """Fill an instance's osparams dict with cluster defaults.
1771

1772
    @type os_name: string
1773
    @param os_name: the OS name to use
1774
    @type os_params: dict
1775
    @param os_params: the dict to fill with default values
1776
    @rtype: dict
1777
    @return: a copy of the instance's osparams with missing keys filled from
1778
        the cluster defaults
1779

1780
    """
1781
    name_only = os_name.split("+", 1)[0]
1782
    # base OS
1783
    result = self.osparams.get(name_only, {})
1784
    # OS with variant
1785
    result = FillDict(result, self.osparams.get(os_name, {}))
1786
    # specified params
1787
    return FillDict(result, os_params)
1788

    
1789
  @staticmethod
1790
  def SimpleFillHvState(hv_state):
1791
    """Fill an hv_state sub dict with cluster defaults.
1792

1793
    """
1794
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1795

    
1796
  @staticmethod
1797
  def SimpleFillDiskState(disk_state):
1798
    """Fill an disk_state sub dict with cluster defaults.
1799

1800
    """
1801
    return FillDict(constants.DS_DEFAULTS, disk_state)
1802

    
1803
  def FillND(self, node, nodegroup):
1804
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1805

1806
    @type node: L{objects.Node}
1807
    @param node: A Node object to fill
1808
    @type nodegroup: L{objects.NodeGroup}
1809
    @param nodegroup: A Node object to fill
1810
    @return a copy of the node's ndparams with defaults filled
1811

1812
    """
1813
    return self.SimpleFillND(nodegroup.FillND(node))
1814

    
1815
  def SimpleFillND(self, ndparams):
1816
    """Fill a given ndparams dict with defaults.
1817

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

1824
    """
1825
    return FillDict(self.ndparams, ndparams)
1826

    
1827
  def SimpleFillIPolicy(self, ipolicy):
1828
    """ Fill instance policy dict with defaults.
1829

1830
    @type ipolicy: dict
1831
    @param ipolicy: the dict to fill
1832
    @rtype: dict
1833
    @return: a copy of passed ipolicy with missing keys filled from
1834
      the cluster defaults
1835

1836
    """
1837
    return FillIPolicy(self.ipolicy, ipolicy)
1838

    
1839

    
1840
class BlockDevStatus(ConfigObject):
1841
  """Config object representing the status of a block device."""
1842
  __slots__ = [
1843
    "dev_path",
1844
    "major",
1845
    "minor",
1846
    "sync_percent",
1847
    "estimated_time",
1848
    "is_degraded",
1849
    "ldisk_status",
1850
    ]
1851

    
1852

    
1853
class ImportExportStatus(ConfigObject):
1854
  """Config object representing the status of an import or export."""
1855
  __slots__ = [
1856
    "recent_output",
1857
    "listen_port",
1858
    "connected",
1859
    "progress_mbytes",
1860
    "progress_throughput",
1861
    "progress_eta",
1862
    "progress_percent",
1863
    "exit_status",
1864
    "error_message",
1865
    ] + _TIMESTAMPS
1866

    
1867

    
1868
class ImportExportOptions(ConfigObject):
1869
  """Options for import/export daemon
1870

1871
  @ivar key_name: X509 key name (None for cluster certificate)
1872
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1873
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
1874
  @ivar magic: Used to ensure the connection goes to the right disk
1875
  @ivar ipv6: Whether to use IPv6
1876
  @ivar connect_timeout: Number of seconds for establishing connection
1877

1878
  """
1879
  __slots__ = [
1880
    "key_name",
1881
    "ca_pem",
1882
    "compress",
1883
    "magic",
1884
    "ipv6",
1885
    "connect_timeout",
1886
    ]
1887

    
1888

    
1889
class ConfdRequest(ConfigObject):
1890
  """Object holding a confd request.
1891

1892
  @ivar protocol: confd protocol version
1893
  @ivar type: confd query type
1894
  @ivar query: query request
1895
  @ivar rsalt: requested reply salt
1896

1897
  """
1898
  __slots__ = [
1899
    "protocol",
1900
    "type",
1901
    "query",
1902
    "rsalt",
1903
    ]
1904

    
1905

    
1906
class ConfdReply(ConfigObject):
1907
  """Object holding a confd reply.
1908

1909
  @ivar protocol: confd protocol version
1910
  @ivar status: reply status code (ok, error)
1911
  @ivar answer: confd query reply
1912
  @ivar serial: configuration serial number
1913

1914
  """
1915
  __slots__ = [
1916
    "protocol",
1917
    "status",
1918
    "answer",
1919
    "serial",
1920
    ]
1921

    
1922

    
1923
class QueryFieldDefinition(ConfigObject):
1924
  """Object holding a query field definition.
1925

1926
  @ivar name: Field name
1927
  @ivar title: Human-readable title
1928
  @ivar kind: Field type
1929
  @ivar doc: Human-readable description
1930

1931
  """
1932
  __slots__ = [
1933
    "name",
1934
    "title",
1935
    "kind",
1936
    "doc",
1937
    ]
1938

    
1939

    
1940
class _QueryResponseBase(ConfigObject):
1941
  __slots__ = [
1942
    "fields",
1943
    ]
1944

    
1945
  def ToDict(self):
1946
    """Custom function for serializing.
1947

1948
    """
1949
    mydict = super(_QueryResponseBase, self).ToDict()
1950
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
1951
    return mydict
1952

    
1953
  @classmethod
1954
  def FromDict(cls, val):
1955
    """Custom function for de-serializing.
1956

1957
    """
1958
    obj = super(_QueryResponseBase, cls).FromDict(val)
1959
    obj.fields = \
1960
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
1961
    return obj
1962

    
1963

    
1964
class QueryResponse(_QueryResponseBase):
1965
  """Object holding the response to a query.
1966

1967
  @ivar fields: List of L{QueryFieldDefinition} objects
1968
  @ivar data: Requested data
1969

1970
  """
1971
  __slots__ = [
1972
    "data",
1973
    ]
1974

    
1975

    
1976
class QueryFieldsRequest(ConfigObject):
1977
  """Object holding a request for querying available fields.
1978

1979
  """
1980
  __slots__ = [
1981
    "what",
1982
    "fields",
1983
    ]
1984

    
1985

    
1986
class QueryFieldsResponse(_QueryResponseBase):
1987
  """Object holding the response to a query for fields.
1988

1989
  @ivar fields: List of L{QueryFieldDefinition} objects
1990

1991
  """
1992
  __slots__ = []
1993

    
1994

    
1995
class MigrationStatus(ConfigObject):
1996
  """Object holding the status of a migration.
1997

1998
  """
1999
  __slots__ = [
2000
    "status",
2001
    "transferred_ram",
2002
    "total_ram",
2003
    ]
2004

    
2005

    
2006
class InstanceConsole(ConfigObject):
2007
  """Object describing how to access the console of an instance.
2008

2009
  """
2010
  __slots__ = [
2011
    "instance",
2012
    "kind",
2013
    "message",
2014
    "host",
2015
    "port",
2016
    "user",
2017
    "command",
2018
    "display",
2019
    ]
2020

    
2021
  def Validate(self):
2022
    """Validates contents of this object.
2023

2024
    """
2025
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2026
    assert self.instance, "Missing instance name"
2027
    assert self.message or self.kind in [constants.CONS_SSH,
2028
                                         constants.CONS_SPICE,
2029
                                         constants.CONS_VNC]
2030
    assert self.host or self.kind == constants.CONS_MESSAGE
2031
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2032
                                      constants.CONS_SSH]
2033
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2034
                                      constants.CONS_SPICE,
2035
                                      constants.CONS_VNC]
2036
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2037
                                         constants.CONS_SPICE,
2038
                                         constants.CONS_VNC]
2039
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2040
                                         constants.CONS_SPICE,
2041
                                         constants.CONS_SSH]
2042
    return True
2043

    
2044

    
2045
class Network(TaggableObject):
2046
  """Object representing a network definition for ganeti.
2047

2048
  """
2049
  __slots__ = [
2050
    "name",
2051
    "serial_no",
2052
    "mac_prefix",
2053
    "network",
2054
    "network6",
2055
    "gateway",
2056
    "gateway6",
2057
    "reservations",
2058
    "ext_reservations",
2059
    ] + _TIMESTAMPS + _UUID
2060

    
2061
  def HooksDict(self, prefix=""):
2062
    """Export a dictionary used by hooks with a network's information.
2063

2064
    @type prefix: String
2065
    @param prefix: Prefix to prepend to the dict entries
2066

2067
    """
2068
    result = {
2069
      "%sNETWORK_NAME" % prefix: self.name,
2070
      "%sNETWORK_UUID" % prefix: self.uuid,
2071
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2072
    }
2073
    if self.network:
2074
      result["%sNETWORK_SUBNET" % prefix] = self.network
2075
    if self.gateway:
2076
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2077
    if self.network6:
2078
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2079
    if self.gateway6:
2080
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2081
    if self.mac_prefix:
2082
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2083

    
2084
    return result
2085

    
2086
  @classmethod
2087
  def FromDict(cls, val):
2088
    """Custom function for networks.
2089

2090
    Remove deprecated network_type and family.
2091

2092
    """
2093
    if "network_type" in val:
2094
      del val["network_type"]
2095
    if "family" in val:
2096
      del val["family"]
2097
    obj = super(Network, cls).FromDict(val)
2098
    return obj
2099

    
2100

    
2101
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2102
  """Simple wrapper over ConfigParse that allows serialization.
2103

2104
  This class is basically ConfigParser.SafeConfigParser with two
2105
  additional methods that allow it to serialize/unserialize to/from a
2106
  buffer.
2107

2108
  """
2109
  def Dumps(self):
2110
    """Dump this instance and return the string representation."""
2111
    buf = StringIO()
2112
    self.write(buf)
2113
    return buf.getvalue()
2114

    
2115
  @classmethod
2116
  def Loads(cls, data):
2117
    """Load data from a string."""
2118
    buf = StringIO(data)
2119
    cfp = cls()
2120
    cfp.readfp(buf)
2121
    return cfp
2122

    
2123

    
2124
class LvmPvInfo(ConfigObject):
2125
  """Information about an LVM physical volume (PV).
2126

2127
  @type name: string
2128
  @ivar name: name of the PV
2129
  @type vg_name: string
2130
  @ivar vg_name: name of the volume group containing the PV
2131
  @type size: float
2132
  @ivar size: size of the PV in MiB
2133
  @type free: float
2134
  @ivar free: free space in the PV, in MiB
2135
  @type attributes: string
2136
  @ivar attributes: PV attributes
2137
  @type lv_list: list of strings
2138
  @ivar lv_list: names of the LVs hosted on the PV
2139
  """
2140
  __slots__ = [
2141
    "name",
2142
    "vg_name",
2143
    "size",
2144
    "free",
2145
    "attributes",
2146
    "lv_list"
2147
    ]
2148

    
2149
  def IsEmpty(self):
2150
    """Is this PV empty?
2151

2152
    """
2153
    return self.size <= (self.free + 1)
2154

    
2155
  def IsAllocatable(self):
2156
    """Is this PV allocatable?
2157

2158
    """
2159
    return ("a" in self.attributes)