Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ af9cef96

History | View | Annotate | Download (61 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
  @staticmethod
268
  def _ContainerToDicts(container):
269
    """Convert the elements of a container to standard python types.
270

271
    This method converts a container with elements derived from
272
    ConfigData to standard python types. If the container is a dict,
273
    we don't touch the keys, only the values.
274

275
    """
276
    if isinstance(container, dict):
277
      ret = dict([(k, v.ToDict()) for k, v in container.iteritems()])
278
    elif isinstance(container, (list, tuple, set, frozenset)):
279
      ret = [elem.ToDict() for elem in container]
280
    else:
281
      raise TypeError("Invalid type %s passed to _ContainerToDicts" %
282
                      type(container))
283
    return ret
284

    
285
  @staticmethod
286
  def _ContainerFromDicts(source, c_type, e_type):
287
    """Convert a container from standard python types.
288

289
    This method converts a container with standard python types to
290
    ConfigData objects. If the container is a dict, we don't touch the
291
    keys, only the values.
292

293
    """
294
    if not isinstance(c_type, type):
295
      raise TypeError("Container type %s passed to _ContainerFromDicts is"
296
                      " not a type" % type(c_type))
297
    if source is None:
298
      source = c_type()
299
    if c_type is dict:
300
      ret = dict([(k, e_type.FromDict(v)) for k, v in source.iteritems()])
301
    elif c_type in (list, tuple, set, frozenset):
302
      ret = c_type([e_type.FromDict(elem) for elem in source])
303
    else:
304
      raise TypeError("Invalid container type %s passed to"
305
                      " _ContainerFromDicts" % c_type)
306
    return ret
307

    
308
  def Copy(self):
309
    """Makes a deep copy of the current object and its children.
310

311
    """
312
    dict_form = self.ToDict()
313
    clone_obj = self.__class__.FromDict(dict_form)
314
    return clone_obj
315

    
316
  def __repr__(self):
317
    """Implement __repr__ for ConfigObjects."""
318
    return repr(self.ToDict())
319

    
320
  def UpgradeConfig(self):
321
    """Fill defaults for missing configuration values.
322

323
    This method will be called at configuration load time, and its
324
    implementation will be object dependent.
325

326
    """
327
    pass
328

    
329

    
330
class TaggableObject(ConfigObject):
331
  """An generic class supporting tags.
332

333
  """
334
  __slots__ = ["tags"]
335
  VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
336

    
337
  @classmethod
338
  def ValidateTag(cls, tag):
339
    """Check if a tag is valid.
340

341
    If the tag is invalid, an errors.TagError will be raised. The
342
    function has no return value.
343

344
    """
345
    if not isinstance(tag, basestring):
346
      raise errors.TagError("Invalid tag type (not a string)")
347
    if len(tag) > constants.MAX_TAG_LEN:
348
      raise errors.TagError("Tag too long (>%d characters)" %
349
                            constants.MAX_TAG_LEN)
350
    if not tag:
351
      raise errors.TagError("Tags cannot be empty")
352
    if not cls.VALID_TAG_RE.match(tag):
353
      raise errors.TagError("Tag contains invalid characters")
354

    
355
  def GetTags(self):
356
    """Return the tags list.
357

358
    """
359
    tags = getattr(self, "tags", None)
360
    if tags is None:
361
      tags = self.tags = set()
362
    return tags
363

    
364
  def AddTag(self, tag):
365
    """Add a new tag.
366

367
    """
368
    self.ValidateTag(tag)
369
    tags = self.GetTags()
370
    if len(tags) >= constants.MAX_TAGS_PER_OBJ:
371
      raise errors.TagError("Too many tags")
372
    self.GetTags().add(tag)
373

    
374
  def RemoveTag(self, tag):
375
    """Remove a tag.
376

377
    """
378
    self.ValidateTag(tag)
379
    tags = self.GetTags()
380
    try:
381
      tags.remove(tag)
382
    except KeyError:
383
      raise errors.TagError("Tag not found")
384

    
385
  def ToDict(self):
386
    """Taggable-object-specific conversion to standard python types.
387

388
    This replaces the tags set with a list.
389

390
    """
391
    bo = super(TaggableObject, self).ToDict()
392

    
393
    tags = bo.get("tags", None)
394
    if isinstance(tags, set):
395
      bo["tags"] = list(tags)
396
    return bo
397

    
398
  @classmethod
399
  def FromDict(cls, val):
400
    """Custom function for instances.
401

402
    """
403
    obj = super(TaggableObject, cls).FromDict(val)
404
    if hasattr(obj, "tags") and isinstance(obj.tags, list):
405
      obj.tags = set(obj.tags)
406
    return obj
407

    
408

    
409
class MasterNetworkParameters(ConfigObject):
410
  """Network configuration parameters for the master
411

412
  @ivar name: master name
413
  @ivar ip: master IP
414
  @ivar netmask: master netmask
415
  @ivar netdev: master network device
416
  @ivar ip_family: master IP family
417

418
  """
419
  __slots__ = [
420
    "name",
421
    "ip",
422
    "netmask",
423
    "netdev",
424
    "ip_family",
425
    ]
426

    
427

    
428
class ConfigData(ConfigObject):
429
  """Top-level config object."""
430
  __slots__ = [
431
    "version",
432
    "cluster",
433
    "nodes",
434
    "nodegroups",
435
    "instances",
436
    "networks",
437
    "serial_no",
438
    ] + _TIMESTAMPS
439

    
440
  def ToDict(self):
441
    """Custom function for top-level config data.
442

443
    This just replaces the list of instances, nodes and the cluster
444
    with standard python types.
445

446
    """
447
    mydict = super(ConfigData, self).ToDict()
448
    mydict["cluster"] = mydict["cluster"].ToDict()
449
    for key in "nodes", "instances", "nodegroups", "networks":
450
      mydict[key] = self._ContainerToDicts(mydict[key])
451

    
452
    return mydict
453

    
454
  @classmethod
455
  def FromDict(cls, val):
456
    """Custom function for top-level config data
457

458
    """
459
    obj = super(ConfigData, cls).FromDict(val)
460
    obj.cluster = Cluster.FromDict(obj.cluster)
461
    obj.nodes = cls._ContainerFromDicts(obj.nodes, dict, Node)
462
    obj.instances = cls._ContainerFromDicts(obj.instances, dict, Instance)
463
    obj.nodegroups = cls._ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
464
    obj.networks = cls._ContainerFromDicts(obj.networks, dict, Network)
465
    return obj
466

    
467
  def HasAnyDiskOfType(self, dev_type):
468
    """Check if in there is at disk of the given type in the configuration.
469

470
    @type dev_type: L{constants.LDS_BLOCK}
471
    @param dev_type: the type to look for
472
    @rtype: boolean
473
    @return: boolean indicating if a disk of the given type was found or not
474

475
    """
476
    for instance in self.instances.values():
477
      for disk in instance.disks:
478
        if disk.IsBasedOnDiskType(dev_type):
479
          return True
480
    return False
481

    
482
  def UpgradeConfig(self):
483
    """Fill defaults for missing configuration values.
484

485
    """
486
    self.cluster.UpgradeConfig()
487
    for node in self.nodes.values():
488
      node.UpgradeConfig()
489
    for instance in self.instances.values():
490
      instance.UpgradeConfig()
491
    if self.nodegroups is None:
492
      self.nodegroups = {}
493
    for nodegroup in self.nodegroups.values():
494
      nodegroup.UpgradeConfig()
495
    if self.cluster.drbd_usermode_helper is None:
496
      # To decide if we set an helper let's check if at least one instance has
497
      # a DRBD disk. This does not cover all the possible scenarios but it
498
      # gives a good approximation.
499
      if self.HasAnyDiskOfType(constants.LD_DRBD8):
500
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
501
    if self.networks is None:
502
      self.networks = {}
503
    for network in self.networks.values():
504
      network.UpgradeConfig()
505

    
506

    
507
class NIC(ConfigObject):
508
  """Config object representing a network card."""
509
  __slots__ = ["name", "pci", "mac", "ip", "network", "nicparams", "netinfo"] + _UUID
510

    
511
  @classmethod
512
  def CheckParameterSyntax(cls, nicparams):
513
    """Check the given parameters for validity.
514

515
    @type nicparams:  dict
516
    @param nicparams: dictionary with parameter names/value
517
    @raise errors.ConfigurationError: when a parameter is not valid
518

519
    """
520
    mode = nicparams[constants.NIC_MODE]
521
    if (mode not in constants.NIC_VALID_MODES and
522
        mode != constants.VALUE_AUTO):
523
      raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
524

    
525
    if (mode == constants.NIC_MODE_BRIDGED and
526
        not nicparams[constants.NIC_LINK]):
527
      raise errors.ConfigurationError("Missing bridged NIC link")
528

    
529

    
530
class Disk(ConfigObject):
531
  """Config object representing a block device."""
532
  __slots__ = ["name", "pci", "dev_type", "logical_id", "physical_id",
533
               "children", "iv_name", "size", "mode", "params"] + _UUID
534

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

    
539
  def AssembleOnSecondary(self):
540
    """Test if this device needs to be assembled on a secondary node."""
541
    return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
542

    
543
  def OpenOnSecondary(self):
544
    """Test if this device needs to be opened on a secondary node."""
545
    return self.dev_type in (constants.LD_LV,)
546

    
547
  def StaticDevPath(self):
548
    """Return the device path if this device type has a static one.
549

550
    Some devices (LVM for example) live always at the same /dev/ path,
551
    irrespective of their status. For such devices, we return this
552
    path, for others we return None.
553

554
    @warning: The path returned is not a normalized pathname; callers
555
        should check that it is a valid path.
556

557
    """
558
    if self.dev_type == constants.LD_LV:
559
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
560
    elif self.dev_type == constants.LD_BLOCKDEV:
561
      return self.logical_id[1]
562
    elif self.dev_type == constants.LD_RBD:
563
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
564
    return None
565

    
566
  def ChildrenNeeded(self):
567
    """Compute the needed number of children for activation.
568

569
    This method will return either -1 (all children) or a positive
570
    number denoting the minimum number of children needed for
571
    activation (only mirrored devices will usually return >=0).
572

573
    Currently, only DRBD8 supports diskless activation (therefore we
574
    return 0), for all other we keep the previous semantics and return
575
    -1.
576

577
    """
578
    if self.dev_type == constants.LD_DRBD8:
579
      return 0
580
    return -1
581

    
582
  def IsBasedOnDiskType(self, dev_type):
583
    """Check if the disk or its children are based on the given type.
584

585
    @type dev_type: L{constants.LDS_BLOCK}
586
    @param dev_type: the type to look for
587
    @rtype: boolean
588
    @return: boolean indicating if a device of the given type was found or not
589

590
    """
591
    if self.children:
592
      for child in self.children:
593
        if child.IsBasedOnDiskType(dev_type):
594
          return True
595
    return self.dev_type == dev_type
596

    
597
  def GetNodes(self, node):
598
    """This function returns the nodes this device lives on.
599

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

605
    """
606
    if self.dev_type in [constants.LD_LV, constants.LD_FILE,
607
                         constants.LD_BLOCKDEV, constants.LD_RBD,
608
                         constants.LD_EXT]:
609
      result = [node]
610
    elif self.dev_type in constants.LDS_DRBD:
611
      result = [self.logical_id[0], self.logical_id[1]]
612
      if node not in result:
613
        raise errors.ConfigurationError("DRBD device passed unknown node")
614
    else:
615
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
616
    return result
617

    
618
  def ComputeNodeTree(self, parent_node):
619
    """Compute the node/disk tree for this disk and its children.
620

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

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

    
653
  def ComputeGrowth(self, amount):
654
    """Compute the per-VG growth requirements.
655

656
    This only works for VG-based disks.
657

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

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

    
675
  def RecordGrow(self, amount):
676
    """Update the size of this disk after growth.
677

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

682
    """
683
    if self.dev_type in (constants.LD_LV, constants.LD_FILE,
684
                         constants.LD_RBD, constants.LD_EXT):
685
      self.size += amount
686
    elif self.dev_type == constants.LD_DRBD8:
687
      if self.children:
688
        self.children[0].RecordGrow(amount)
689
      self.size += amount
690
    else:
691
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
692
                                   " disk type %s" % self.dev_type)
693

    
694
  def Update(self, size=None, mode=None):
695
    """Apply changes to size and mode.
696

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

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

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

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

    
718
  def SetPhysicalID(self, target_node, nodes_ip):
719
    """Convert the logical ID to the physical ID.
720

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

723
    The routine descends down and updates its children also, because
724
    this helps when the only the top device is passed to the remote
725
    node.
726

727
    Arguments:
728
      - target_node: the node we wish to configure for
729
      - nodes_ip: a mapping of node name to ip
730

731
    The target_node must exist in in nodes_ip, and must be one of the
732
    nodes in the logical ID for each of the DRBD devices encountered
733
    in the disk tree.
734

735
    """
736
    if self.children:
737
      for child in self.children:
738
        child.SetPhysicalID(target_node, nodes_ip)
739

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

    
762
  def ToDict(self):
763
    """Disk-specific conversion to standard python types.
764

765
    This replaces the children lists of objects with lists of
766
    standard python types.
767

768
    """
769
    bo = super(Disk, self).ToDict()
770

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

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

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

    
795
  def __str__(self):
796
    """Custom str() formatter for disks.
797

798
    """
799
    if self.dev_type == constants.LD_LV:
800
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
801
    elif self.dev_type in constants.LDS_DRBD:
802
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
803
      val = "<DRBD8("
804
      if self.physical_id is None:
805
        phy = "unconfigured"
806
      else:
807
        phy = ("configured as %s:%s %s:%s" %
808
               (self.physical_id[0], self.physical_id[1],
809
                self.physical_id[2], self.physical_id[3]))
810

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

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

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

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

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

    
847
    # FIXME: Make this configurable in Ganeti 2.7
848
    self.params = {}
849
    # add here config upgrade for this disk
850

    
851
  @staticmethod
852
  def ComputeLDParams(disk_template, disk_params):
853
    """Computes Logical Disk parameters from Disk Template parameters.
854

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

864
    """
865
    if disk_template not in constants.DISK_TEMPLATES:
866
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
867

    
868
    assert disk_template in disk_params
869

    
870
    result = list()
871
    dt_params = disk_params[disk_template]
872
    if disk_template == constants.DT_DRBD8:
873
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8], {
874
        constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
875
        constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
876
        constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
877
        constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
878
        constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
879
        constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
880
        constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
881
        constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
882
        constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
883
        constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
884
        constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
885
        constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
886
        }))
887

    
888
      # data LV
889
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
890
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
891
        }))
892

    
893
      # metadata LV
894
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
895
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
896
        }))
897

    
898
    elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
899
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
900

    
901
    elif disk_template == constants.DT_PLAIN:
902
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
903
        constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
904
        }))
905

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

    
909
    elif disk_template == constants.DT_RBD:
910
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD], {
911
        constants.LDP_POOL: dt_params[constants.RBD_POOL],
912
        }))
913

    
914
    elif disk_template == constants.DT_EXT:
915
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_EXT])
916

    
917
    return result
918

    
919

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

923

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

927
  """
928
  @classmethod
929
  def CheckParameterSyntax(cls, ipolicy, check_std):
930
    """ Check the instance policy for validity.
931

932
    """
933
    for param in constants.ISPECS_PARAMETERS:
934
      InstancePolicy.CheckISpecSyntax(ipolicy, param, check_std)
935
    if constants.IPOLICY_DTS in ipolicy:
936
      InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
937
    for key in constants.IPOLICY_PARAMETERS:
938
      if key in ipolicy:
939
        InstancePolicy.CheckParameter(key, ipolicy[key])
940
    wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
941
    if wrong_keys:
942
      raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
943
                                      utils.CommaJoin(wrong_keys))
944

    
945
  @classmethod
946
  def CheckISpecSyntax(cls, ipolicy, name, check_std):
947
    """Check the instance policy for validity on a given key.
948

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

952
    @type ipolicy: dict
953
    @param ipolicy: dictionary with min, max, std specs
954
    @type name: string
955
    @param name: what are the limits for
956
    @type check_std: bool
957
    @param check_std: Whether to check std value or just assume compliance
958
    @raise errors.ConfigureError: when specs for given name are not valid
959

960
    """
961
    min_v = ipolicy[constants.ISPECS_MIN].get(name, 0)
962

    
963
    if check_std:
964
      std_v = ipolicy[constants.ISPECS_STD].get(name, min_v)
965
      std_msg = std_v
966
    else:
967
      std_v = min_v
968
      std_msg = "-"
969

    
970
    max_v = ipolicy[constants.ISPECS_MAX].get(name, std_v)
971
    err = ("Invalid specification of min/max/std values for %s: %s/%s/%s" %
972
           (name,
973
            ipolicy[constants.ISPECS_MIN].get(name, "-"),
974
            ipolicy[constants.ISPECS_MAX].get(name, "-"),
975
            std_msg))
976
    if min_v > std_v or std_v > max_v:
977
      raise errors.ConfigurationError(err)
978

    
979
  @classmethod
980
  def CheckDiskTemplates(cls, disk_templates):
981
    """Checks the disk templates for validity.
982

983
    """
984
    if not disk_templates:
985
      raise errors.ConfigurationError("Instance policy must contain" +
986
                                      " at least one disk template")
987
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
988
    if wrong:
989
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
990
                                      utils.CommaJoin(wrong))
991

    
992
  @classmethod
993
  def CheckParameter(cls, key, value):
994
    """Checks a parameter.
995

996
    Currently we expect all parameters to be float values.
997

998
    """
999
    try:
1000
      float(value)
1001
    except (TypeError, ValueError), err:
1002
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1003
                                      " '%s', error: %s" % (key, value, err))
1004

    
1005

    
1006
class Instance(TaggableObject):
1007
  """Config object representing an instance."""
1008
  __slots__ = [
1009
    "name",
1010
    "primary_node",
1011
    "os",
1012
    "hypervisor",
1013
    "hvparams",
1014
    "beparams",
1015
    "osparams",
1016
    "dev_idxs",
1017
    "admin_state",
1018
    "nics",
1019
    "disks",
1020
    "disk_template",
1021
    "network_port",
1022
    "serial_no",
1023
    ] + _TIMESTAMPS + _UUID
1024

    
1025
  def _ComputeSecondaryNodes(self):
1026
    """Compute the list of secondary nodes.
1027

1028
    This is a simple wrapper over _ComputeAllNodes.
1029

1030
    """
1031
    all_nodes = set(self._ComputeAllNodes())
1032
    all_nodes.discard(self.primary_node)
1033
    return tuple(all_nodes)
1034

    
1035
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1036
                             "List of names of secondary nodes")
1037

    
1038
  def _ComputeAllNodes(self):
1039
    """Compute the list of all nodes.
1040

1041
    Since the data is already there (in the drbd disks), keeping it as
1042
    a separate normal attribute is redundant and if not properly
1043
    synchronised can cause problems. Thus it's better to compute it
1044
    dynamically.
1045

1046
    """
1047
    def _Helper(nodes, device):
1048
      """Recursively computes nodes given a top device."""
1049
      if device.dev_type in constants.LDS_DRBD:
1050
        nodea, nodeb = device.logical_id[:2]
1051
        nodes.add(nodea)
1052
        nodes.add(nodeb)
1053
      if device.children:
1054
        for child in device.children:
1055
          _Helper(nodes, child)
1056

    
1057
    all_nodes = set()
1058
    all_nodes.add(self.primary_node)
1059
    for device in self.disks:
1060
      _Helper(all_nodes, device)
1061
    return tuple(all_nodes)
1062

    
1063
  all_nodes = property(_ComputeAllNodes, None, None,
1064
                       "List of names of all the nodes of the instance")
1065

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

1069
    This function figures out what logical volumes should belong on
1070
    which nodes, recursing through a device tree.
1071

1072
    @param lvmap: optional dictionary to receive the
1073
        'node' : ['lv', ...] data.
1074

1075
    @return: None if lvmap arg is given, otherwise, a dictionary of
1076
        the form { 'nodename' : ['volume1', 'volume2', ...], ... };
1077
        volumeN is of the form "vg_name/lv_name", compatible with
1078
        GetVolumeList()
1079

1080
    """
1081
    if node is None:
1082
      node = self.primary_node
1083

    
1084
    if lvmap is None:
1085
      lvmap = {
1086
        node: [],
1087
        }
1088
      ret = lvmap
1089
    else:
1090
      if not node in lvmap:
1091
        lvmap[node] = []
1092
      ret = None
1093

    
1094
    if not devs:
1095
      devs = self.disks
1096

    
1097
    for dev in devs:
1098
      if dev.dev_type == constants.LD_LV:
1099
        lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1100

    
1101
      elif dev.dev_type in constants.LDS_DRBD:
1102
        if dev.children:
1103
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1104
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1105

    
1106
      elif dev.children:
1107
        self.MapLVsByNode(lvmap, dev.children, node)
1108

    
1109
    return ret
1110

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

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

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

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

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

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

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

    
1143
    for attr in "nics", "disks":
1144
      alist = bo.get(attr, None)
1145
      if alist:
1146
        nlist = self._ContainerToDicts(alist)
1147
      else:
1148
        nlist = []
1149
      bo[attr] = nlist
1150
    return bo
1151

    
1152
  @classmethod
1153
  def FromDict(cls, val):
1154
    """Custom function for instances.
1155

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

    
1169
  def UpgradeConfig(self):
1170
    """Fill defaults for missing configuration values.
1171

1172
    """
1173
    for nic in self.nics:
1174
      nic.UpgradeConfig()
1175
    for disk in self.disks:
1176
      disk.UpgradeConfig()
1177
    if self.hvparams:
1178
      for key in constants.HVC_GLOBALS:
1179
        try:
1180
          del self.hvparams[key]
1181
        except KeyError:
1182
          pass
1183
    if self.osparams is None:
1184
      self.osparams = {}
1185
    UpgradeBeParams(self.beparams)
1186

    
1187

    
1188
class OS(ConfigObject):
1189
  """Config object representing an operating system.
1190

1191
  @type supported_parameters: list
1192
  @ivar supported_parameters: a list of tuples, name and description,
1193
      containing the supported parameters by this OS
1194

1195
  @type VARIANT_DELIM: string
1196
  @cvar VARIANT_DELIM: the variant delimiter
1197

1198
  """
1199
  __slots__ = [
1200
    "name",
1201
    "path",
1202
    "api_versions",
1203
    "create_script",
1204
    "export_script",
1205
    "import_script",
1206
    "rename_script",
1207
    "verify_script",
1208
    "supported_variants",
1209
    "supported_parameters",
1210
    ]
1211

    
1212
  VARIANT_DELIM = "+"
1213

    
1214
  @classmethod
1215
  def SplitNameVariant(cls, name):
1216
    """Splits the name into the proper name and variant.
1217

1218
    @param name: the OS (unprocessed) name
1219
    @rtype: list
1220
    @return: a list of two elements; if the original name didn't
1221
        contain a variant, it's returned as an empty string
1222

1223
    """
1224
    nv = name.split(cls.VARIANT_DELIM, 1)
1225
    if len(nv) == 1:
1226
      nv.append("")
1227
    return nv
1228

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

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

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

    
1238
  @classmethod
1239
  def GetVariant(cls, name):
1240
    """Returns the variant the os (without the base name).
1241

1242
    @param name: the OS (unprocessed) name
1243

1244
    """
1245
    return cls.SplitNameVariant(name)[1]
1246

    
1247

    
1248
class ExtStorage(ConfigObject):
1249
  """Config object representing an External Storage Provider.
1250

1251
  """
1252
  __slots__ = [
1253
    "name",
1254
    "path",
1255
    "create_script",
1256
    "remove_script",
1257
    "grow_script",
1258
    "attach_script",
1259
    "detach_script",
1260
    "setinfo_script",
1261
    "verify_script",
1262
    "supported_parameters",
1263
    ]
1264

    
1265

    
1266
class NodeHvState(ConfigObject):
1267
  """Hypvervisor state on a node.
1268

1269
  @ivar mem_total: Total amount of memory
1270
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1271
    available)
1272
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1273
    rounding
1274
  @ivar mem_inst: Memory used by instances living on node
1275
  @ivar cpu_total: Total node CPU core count
1276
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1277

1278
  """
1279
  __slots__ = [
1280
    "mem_total",
1281
    "mem_node",
1282
    "mem_hv",
1283
    "mem_inst",
1284
    "cpu_total",
1285
    "cpu_node",
1286
    ] + _TIMESTAMPS
1287

    
1288

    
1289
class NodeDiskState(ConfigObject):
1290
  """Disk state on a node.
1291

1292
  """
1293
  __slots__ = [
1294
    "total",
1295
    "reserved",
1296
    "overhead",
1297
    ] + _TIMESTAMPS
1298

    
1299

    
1300
class Node(TaggableObject):
1301
  """Config object representing a node.
1302

1303
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1304
  @ivar hv_state_static: Hypervisor state overriden by user
1305
  @ivar disk_state: Disk state (e.g. free space)
1306
  @ivar disk_state_static: Disk state overriden by user
1307

1308
  """
1309
  __slots__ = [
1310
    "name",
1311
    "primary_ip",
1312
    "secondary_ip",
1313
    "serial_no",
1314
    "master_candidate",
1315
    "offline",
1316
    "drained",
1317
    "group",
1318
    "master_capable",
1319
    "vm_capable",
1320
    "ndparams",
1321
    "powered",
1322
    "hv_state",
1323
    "hv_state_static",
1324
    "disk_state",
1325
    "disk_state_static",
1326
    ] + _TIMESTAMPS + _UUID
1327

    
1328
  def UpgradeConfig(self):
1329
    """Fill defaults for missing configuration values.
1330

1331
    """
1332
    # pylint: disable=E0203
1333
    # because these are "defined" via slots, not manually
1334
    if self.master_capable is None:
1335
      self.master_capable = True
1336

    
1337
    if self.vm_capable is None:
1338
      self.vm_capable = True
1339

    
1340
    if self.ndparams is None:
1341
      self.ndparams = {}
1342
    # And remove any global parameter
1343
    for key in constants.NDC_GLOBALS:
1344
      if key in self.ndparams:
1345
        logging.warning("Ignoring %s node parameter for node %s",
1346
                        key, self.name)
1347
        del self.ndparams[key]
1348

    
1349
    if self.powered is None:
1350
      self.powered = True
1351

    
1352
  def ToDict(self):
1353
    """Custom function for serializing.
1354

1355
    """
1356
    data = super(Node, self).ToDict()
1357

    
1358
    hv_state = data.get("hv_state", None)
1359
    if hv_state is not None:
1360
      data["hv_state"] = self._ContainerToDicts(hv_state)
1361

    
1362
    disk_state = data.get("disk_state", None)
1363
    if disk_state is not None:
1364
      data["disk_state"] = \
1365
        dict((key, self._ContainerToDicts(value))
1366
             for (key, value) in disk_state.items())
1367

    
1368
    return data
1369

    
1370
  @classmethod
1371
  def FromDict(cls, val):
1372
    """Custom function for deserializing.
1373

1374
    """
1375
    obj = super(Node, cls).FromDict(val)
1376

    
1377
    if obj.hv_state is not None:
1378
      obj.hv_state = cls._ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1379

    
1380
    if obj.disk_state is not None:
1381
      obj.disk_state = \
1382
        dict((key, cls._ContainerFromDicts(value, dict, NodeDiskState))
1383
             for (key, value) in obj.disk_state.items())
1384

    
1385
    return obj
1386

    
1387

    
1388
class NodeGroup(TaggableObject):
1389
  """Config object representing a node group."""
1390
  __slots__ = [
1391
    "name",
1392
    "members",
1393
    "ndparams",
1394
    "diskparams",
1395
    "ipolicy",
1396
    "serial_no",
1397
    "hv_state_static",
1398
    "disk_state_static",
1399
    "alloc_policy",
1400
    "networks",
1401
    ] + _TIMESTAMPS + _UUID
1402

    
1403
  def ToDict(self):
1404
    """Custom function for nodegroup.
1405

1406
    This discards the members object, which gets recalculated and is only kept
1407
    in memory.
1408

1409
    """
1410
    mydict = super(NodeGroup, self).ToDict()
1411
    del mydict["members"]
1412
    return mydict
1413

    
1414
  @classmethod
1415
  def FromDict(cls, val):
1416
    """Custom function for nodegroup.
1417

1418
    The members slot is initialized to an empty list, upon deserialization.
1419

1420
    """
1421
    obj = super(NodeGroup, cls).FromDict(val)
1422
    obj.members = []
1423
    return obj
1424

    
1425
  def UpgradeConfig(self):
1426
    """Fill defaults for missing configuration values.
1427

1428
    """
1429
    if self.ndparams is None:
1430
      self.ndparams = {}
1431

    
1432
    if self.serial_no is None:
1433
      self.serial_no = 1
1434

    
1435
    if self.alloc_policy is None:
1436
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1437

    
1438
    # We only update mtime, and not ctime, since we would not be able
1439
    # to provide a correct value for creation time.
1440
    if self.mtime is None:
1441
      self.mtime = time.time()
1442

    
1443
    if self.diskparams is None:
1444
      self.diskparams = {}
1445
    if self.ipolicy is None:
1446
      self.ipolicy = MakeEmptyIPolicy()
1447

    
1448
    if self.networks is None:
1449
      self.networks = {}
1450

    
1451
  def FillND(self, node):
1452
    """Return filled out ndparams for L{objects.Node}
1453

1454
    @type node: L{objects.Node}
1455
    @param node: A Node object to fill
1456
    @return a copy of the node's ndparams with defaults filled
1457

1458
    """
1459
    return self.SimpleFillND(node.ndparams)
1460

    
1461
  def SimpleFillND(self, ndparams):
1462
    """Fill a given ndparams dict with defaults.
1463

1464
    @type ndparams: dict
1465
    @param ndparams: the dict to fill
1466
    @rtype: dict
1467
    @return: a copy of the passed in ndparams with missing keys filled
1468
        from the node group defaults
1469

1470
    """
1471
    return FillDict(self.ndparams, ndparams)
1472

    
1473

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

    
1518
  def UpgradeConfig(self):
1519
    """Fill defaults for missing configuration values.
1520

1521
    """
1522
    # pylint: disable=E0203
1523
    # because these are "defined" via slots, not manually
1524
    if self.hvparams is None:
1525
      self.hvparams = constants.HVC_DEFAULTS
1526
    else:
1527
      for hypervisor in self.hvparams:
1528
        self.hvparams[hypervisor] = FillDict(
1529
            constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1530

    
1531
    if self.os_hvp is None:
1532
      self.os_hvp = {}
1533

    
1534
    # osparams added before 2.2
1535
    if self.osparams is None:
1536
      self.osparams = {}
1537

    
1538
    self.ndparams = UpgradeNDParams(self.ndparams)
1539

    
1540
    self.beparams = UpgradeGroupedParams(self.beparams,
1541
                                         constants.BEC_DEFAULTS)
1542
    for beparams_group in self.beparams:
1543
      UpgradeBeParams(self.beparams[beparams_group])
1544

    
1545
    migrate_default_bridge = not self.nicparams
1546
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1547
                                          constants.NICC_DEFAULTS)
1548
    if migrate_default_bridge:
1549
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1550
        self.default_bridge
1551

    
1552
    if self.modify_etc_hosts is None:
1553
      self.modify_etc_hosts = True
1554

    
1555
    if self.modify_ssh_setup is None:
1556
      self.modify_ssh_setup = True
1557

    
1558
    # default_bridge is no longer used in 2.1. The slot is left there to
1559
    # support auto-upgrading. It can be removed once we decide to deprecate
1560
    # upgrading straight from 2.0.
1561
    if self.default_bridge is not None:
1562
      self.default_bridge = None
1563

    
1564
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1565
    # code can be removed once upgrading straight from 2.0 is deprecated.
1566
    if self.default_hypervisor is not None:
1567
      self.enabled_hypervisors = ([self.default_hypervisor] +
1568
                                  [hvname for hvname in self.enabled_hypervisors
1569
                                   if hvname != self.default_hypervisor])
1570
      self.default_hypervisor = None
1571

    
1572
    # maintain_node_health added after 2.1.1
1573
    if self.maintain_node_health is None:
1574
      self.maintain_node_health = False
1575

    
1576
    if self.uid_pool is None:
1577
      self.uid_pool = []
1578

    
1579
    if self.default_iallocator is None:
1580
      self.default_iallocator = ""
1581

    
1582
    # reserved_lvs added before 2.2
1583
    if self.reserved_lvs is None:
1584
      self.reserved_lvs = []
1585

    
1586
    # hidden and blacklisted operating systems added before 2.2.1
1587
    if self.hidden_os is None:
1588
      self.hidden_os = []
1589

    
1590
    if self.blacklisted_os is None:
1591
      self.blacklisted_os = []
1592

    
1593
    # primary_ip_family added before 2.3
1594
    if self.primary_ip_family is None:
1595
      self.primary_ip_family = AF_INET
1596

    
1597
    if self.master_netmask is None:
1598
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1599
      self.master_netmask = ipcls.iplen
1600

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

    
1604
    # shared_file_storage_dir added before 2.5
1605
    if self.shared_file_storage_dir is None:
1606
      self.shared_file_storage_dir = ""
1607

    
1608
    if self.use_external_mip_script is None:
1609
      self.use_external_mip_script = False
1610

    
1611
    if self.diskparams:
1612
      self.diskparams = UpgradeDiskParams(self.diskparams)
1613
    else:
1614
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1615

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

    
1631
  @property
1632
  def primary_hypervisor(self):
1633
    """The first hypervisor is the primary.
1634

1635
    Useful, for example, for L{Node}'s hv/disk state.
1636

1637
    """
1638
    return self.enabled_hypervisors[0]
1639

    
1640
  def ToDict(self):
1641
    """Custom function for cluster.
1642

1643
    """
1644
    mydict = super(Cluster, self).ToDict()
1645
    mydict["tcpudp_port_pool"] = list(self.tcpudp_port_pool)
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
    if not isinstance(obj.tcpudp_port_pool, set):
1655
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1656
    return obj
1657

    
1658
  def SimpleFillDP(self, diskparams):
1659
    """Fill a given diskparams dict with cluster defaults.
1660

1661
    @param diskparams: The diskparams
1662
    @return: The defaults dict
1663

1664
    """
1665
    return FillDiskParams(self.diskparams, diskparams)
1666

    
1667
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1668
    """Get the default hypervisor parameters for the cluster.
1669

1670
    @param hypervisor: the hypervisor name
1671
    @param os_name: if specified, we'll also update the defaults for this OS
1672
    @param skip_keys: if passed, list of keys not to use
1673
    @return: the defaults dict
1674

1675
    """
1676
    if skip_keys is None:
1677
      skip_keys = []
1678

    
1679
    fill_stack = [self.hvparams.get(hypervisor, {})]
1680
    if os_name is not None:
1681
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1682
      fill_stack.append(os_hvp)
1683

    
1684
    ret_dict = {}
1685
    for o_dict in fill_stack:
1686
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1687

    
1688
    return ret_dict
1689

    
1690
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1691
    """Fill a given hvparams dict with cluster defaults.
1692

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

1704
    """
1705
    if skip_globals:
1706
      skip_keys = constants.HVC_GLOBALS
1707
    else:
1708
      skip_keys = []
1709

    
1710
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1711
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1712

    
1713
  def FillHV(self, instance, skip_globals=False):
1714
    """Fill an instance's hvparams dict with cluster defaults.
1715

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

1725
    """
1726
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1727
                             instance.hvparams, skip_globals)
1728

    
1729
  def SimpleFillBE(self, beparams):
1730
    """Fill a given beparams dict with cluster defaults.
1731

1732
    @type beparams: dict
1733
    @param beparams: the dict to fill
1734
    @rtype: dict
1735
    @return: a copy of the passed in beparams with missing keys filled
1736
        from the cluster defaults
1737

1738
    """
1739
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1740

    
1741
  def FillBE(self, instance):
1742
    """Fill an instance's beparams dict with cluster defaults.
1743

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

1750
    """
1751
    return self.SimpleFillBE(instance.beparams)
1752

    
1753
  def SimpleFillNIC(self, nicparams):
1754
    """Fill a given nicparams dict with cluster defaults.
1755

1756
    @type nicparams: dict
1757
    @param nicparams: the dict to fill
1758
    @rtype: dict
1759
    @return: a copy of the passed in nicparams with missing keys filled
1760
        from the cluster defaults
1761

1762
    """
1763
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1764

    
1765
  def SimpleFillOS(self, os_name, os_params):
1766
    """Fill an instance's osparams dict with cluster defaults.
1767

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

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

    
1785
  @staticmethod
1786
  def SimpleFillHvState(hv_state):
1787
    """Fill an hv_state sub dict with cluster defaults.
1788

1789
    """
1790
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1791

    
1792
  @staticmethod
1793
  def SimpleFillDiskState(disk_state):
1794
    """Fill an disk_state sub dict with cluster defaults.
1795

1796
    """
1797
    return FillDict(constants.DS_DEFAULTS, disk_state)
1798

    
1799
  def FillND(self, node, nodegroup):
1800
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1801

1802
    @type node: L{objects.Node}
1803
    @param node: A Node object to fill
1804
    @type nodegroup: L{objects.NodeGroup}
1805
    @param nodegroup: A Node object to fill
1806
    @return a copy of the node's ndparams with defaults filled
1807

1808
    """
1809
    return self.SimpleFillND(nodegroup.FillND(node))
1810

    
1811
  def SimpleFillND(self, ndparams):
1812
    """Fill a given ndparams dict with defaults.
1813

1814
    @type ndparams: dict
1815
    @param ndparams: the dict to fill
1816
    @rtype: dict
1817
    @return: a copy of the passed in ndparams with missing keys filled
1818
        from the cluster defaults
1819

1820
    """
1821
    return FillDict(self.ndparams, ndparams)
1822

    
1823
  def SimpleFillIPolicy(self, ipolicy):
1824
    """ Fill instance policy dict with defaults.
1825

1826
    @type ipolicy: dict
1827
    @param ipolicy: the dict to fill
1828
    @rtype: dict
1829
    @return: a copy of passed ipolicy with missing keys filled from
1830
      the cluster defaults
1831

1832
    """
1833
    return FillIPolicy(self.ipolicy, ipolicy)
1834

    
1835

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

    
1848

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

    
1863

    
1864
class ImportExportOptions(ConfigObject):
1865
  """Options for import/export daemon
1866

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

1874
  """
1875
  __slots__ = [
1876
    "key_name",
1877
    "ca_pem",
1878
    "compress",
1879
    "magic",
1880
    "ipv6",
1881
    "connect_timeout",
1882
    ]
1883

    
1884

    
1885
class ConfdRequest(ConfigObject):
1886
  """Object holding a confd request.
1887

1888
  @ivar protocol: confd protocol version
1889
  @ivar type: confd query type
1890
  @ivar query: query request
1891
  @ivar rsalt: requested reply salt
1892

1893
  """
1894
  __slots__ = [
1895
    "protocol",
1896
    "type",
1897
    "query",
1898
    "rsalt",
1899
    ]
1900

    
1901

    
1902
class ConfdReply(ConfigObject):
1903
  """Object holding a confd reply.
1904

1905
  @ivar protocol: confd protocol version
1906
  @ivar status: reply status code (ok, error)
1907
  @ivar answer: confd query reply
1908
  @ivar serial: configuration serial number
1909

1910
  """
1911
  __slots__ = [
1912
    "protocol",
1913
    "status",
1914
    "answer",
1915
    "serial",
1916
    ]
1917

    
1918

    
1919
class QueryFieldDefinition(ConfigObject):
1920
  """Object holding a query field definition.
1921

1922
  @ivar name: Field name
1923
  @ivar title: Human-readable title
1924
  @ivar kind: Field type
1925
  @ivar doc: Human-readable description
1926

1927
  """
1928
  __slots__ = [
1929
    "name",
1930
    "title",
1931
    "kind",
1932
    "doc",
1933
    ]
1934

    
1935

    
1936
class _QueryResponseBase(ConfigObject):
1937
  __slots__ = [
1938
    "fields",
1939
    ]
1940

    
1941
  def ToDict(self):
1942
    """Custom function for serializing.
1943

1944
    """
1945
    mydict = super(_QueryResponseBase, self).ToDict()
1946
    mydict["fields"] = self._ContainerToDicts(mydict["fields"])
1947
    return mydict
1948

    
1949
  @classmethod
1950
  def FromDict(cls, val):
1951
    """Custom function for de-serializing.
1952

1953
    """
1954
    obj = super(_QueryResponseBase, cls).FromDict(val)
1955
    obj.fields = cls._ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
1956
    return obj
1957

    
1958

    
1959
class QueryResponse(_QueryResponseBase):
1960
  """Object holding the response to a query.
1961

1962
  @ivar fields: List of L{QueryFieldDefinition} objects
1963
  @ivar data: Requested data
1964

1965
  """
1966
  __slots__ = [
1967
    "data",
1968
    ]
1969

    
1970

    
1971
class QueryFieldsRequest(ConfigObject):
1972
  """Object holding a request for querying available fields.
1973

1974
  """
1975
  __slots__ = [
1976
    "what",
1977
    "fields",
1978
    ]
1979

    
1980

    
1981
class QueryFieldsResponse(_QueryResponseBase):
1982
  """Object holding the response to a query for fields.
1983

1984
  @ivar fields: List of L{QueryFieldDefinition} objects
1985

1986
  """
1987
  __slots__ = []
1988

    
1989

    
1990
class MigrationStatus(ConfigObject):
1991
  """Object holding the status of a migration.
1992

1993
  """
1994
  __slots__ = [
1995
    "status",
1996
    "transferred_ram",
1997
    "total_ram",
1998
    ]
1999

    
2000

    
2001
class InstanceConsole(ConfigObject):
2002
  """Object describing how to access the console of an instance.
2003

2004
  """
2005
  __slots__ = [
2006
    "instance",
2007
    "kind",
2008
    "message",
2009
    "host",
2010
    "port",
2011
    "user",
2012
    "command",
2013
    "display",
2014
    ]
2015

    
2016
  def Validate(self):
2017
    """Validates contents of this object.
2018

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

    
2039

    
2040
class Network(TaggableObject):
2041
  """Object representing a network definition for ganeti.
2042

2043
  """
2044
  __slots__ = [
2045
    "name",
2046
    "serial_no",
2047
    "mac_prefix",
2048
    "network",
2049
    "network6",
2050
    "gateway",
2051
    "gateway6",
2052
    "reservations",
2053
    "ext_reservations",
2054
    ] + _TIMESTAMPS + _UUID
2055

    
2056
  def HooksDict(self, prefix=""):
2057
    """Export a dictionary used by hooks with a network's information.
2058

2059
    @type prefix: String
2060
    @param prefix: Prefix to prepend to the dict entries
2061

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

    
2079
    return result
2080

    
2081
  @classmethod
2082
  def FromDict(cls, val):
2083
    """Custom function for networks.
2084

2085
    Remove deprecated network_type and family.
2086

2087
    """
2088
    if "network_type" in val:
2089
      del val["network_type"]
2090
    if "family" in val:
2091
      del val["family"]
2092
    obj = super(Network, cls).FromDict(val)
2093
    return obj
2094

    
2095

    
2096
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2097
  """Simple wrapper over ConfigParse that allows serialization.
2098

2099
  This class is basically ConfigParser.SafeConfigParser with two
2100
  additional methods that allow it to serialize/unserialize to/from a
2101
  buffer.
2102

2103
  """
2104
  def Dumps(self):
2105
    """Dump this instance and return the string representation."""
2106
    buf = StringIO()
2107
    self.write(buf)
2108
    return buf.getvalue()
2109

    
2110
  @classmethod
2111
  def Loads(cls, data):
2112
    """Load data from a string."""
2113
    buf = StringIO(data)
2114
    cfp = cls()
2115
    cfp.readfp(buf)
2116
    return cfp
2117

    
2118

    
2119
class LvmPvInfo(ConfigObject):
2120
  """Information about an LVM physical volume (PV).
2121

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

    
2144
  def IsEmpty(self):
2145
    """Is this PV empty?
2146

2147
    """
2148
    return self.size <= (self.free + 1)
2149

    
2150
  def IsAllocatable(self):
2151
    """Is this PV allocatable?
2152

2153
    """
2154
    return ("a" in self.attributes)