Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ b342c9dd

History | View | Annotate | Download (63.1 kB)

1
#
2
#
3

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

    
21

    
22
"""Transportable objects for Ganeti.
23

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

27
"""
28

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

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

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

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

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

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

    
51
from socket import AF_INET
52

    
53

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

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

    
60

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

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

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

    
84

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

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

    
98

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

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

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

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

    
111

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

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

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

    
128

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

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

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

    
142

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

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

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

    
157
  return result
158

    
159

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

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

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

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

    
178

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

182
  """
183
  return {}
184

    
185

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

189
  It has the following properties:
190

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

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

198
  """
199
  __slots__ = []
200

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

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

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

216
    """
217

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

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

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

    
235
  __getstate__ = ToDict
236

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

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

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

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

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

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

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

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

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

275
    """
276
    pass
277

    
278

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

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

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

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

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

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

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

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

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

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

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

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

337
    This replaces the tags set with a list.
338

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

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

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

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

    
357

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

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

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

    
376

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

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

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

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

    
401
    return mydict
402

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

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

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

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

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

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

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

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

462
    """
463
    # enabled_disk_templates in the cluster config were introduced in 2.8.
464
    # Remove this code once upgrading from earlier versions is deprecated.
465
    if not self.cluster.enabled_disk_templates:
466
      template_set = \
467
        set([inst.disk_template for inst in self.instances.values()])
468
      # Add drbd and plain, if lvm is enabled (by specifying a volume group)
469
      if self.cluster.volume_group_name:
470
        template_set.add(constants.DT_DRBD8)
471
        template_set.add(constants.DT_PLAIN)
472
      # FIXME: Adapt this when dis/enabling at configure time is removed.
473
      # Enable 'file' and 'sharedfile', if they are enabled, even though they
474
      # might currently not be used.
475
      if constants.ENABLE_FILE_STORAGE:
476
        template_set.add(constants.DT_FILE)
477
      if constants.ENABLE_SHARED_FILE_STORAGE:
478
        template_set.add(constants.DT_SHARED_FILE)
479
      # Set enabled_disk_templates to the inferred disk templates. Order them
480
      # according to a preference list that is based on Ganeti's history of
481
      # supported disk templates.
482
      self.cluster.enabled_disk_templates = []
483
      for preferred_template in constants.DISK_TEMPLATE_PREFERENCE:
484
        if preferred_template in template_set:
485
          self.cluster.enabled_disk_templates.append(preferred_template)
486
          template_set.remove(preferred_template)
487
      self.cluster.enabled_disk_templates.extend(list(template_set))
488

    
489

    
490
class NIC(ConfigObject):
491
  """Config object representing a network card."""
492
  __slots__ = ["name", "mac", "ip", "network", "nicparams", "netinfo"] + _UUID
493

    
494
  @classmethod
495
  def CheckParameterSyntax(cls, nicparams):
496
    """Check the given parameters for validity.
497

498
    @type nicparams:  dict
499
    @param nicparams: dictionary with parameter names/value
500
    @raise errors.ConfigurationError: when a parameter is not valid
501

502
    """
503
    mode = nicparams[constants.NIC_MODE]
504
    if (mode not in constants.NIC_VALID_MODES and
505
        mode != constants.VALUE_AUTO):
506
      raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
507

    
508
    if (mode == constants.NIC_MODE_BRIDGED and
509
        not nicparams[constants.NIC_LINK]):
510
      raise errors.ConfigurationError("Missing bridged NIC link")
511

    
512

    
513
class Disk(ConfigObject):
514
  """Config object representing a block device."""
515
  __slots__ = ["name", "dev_type", "logical_id", "physical_id",
516
               "children", "iv_name", "size", "mode", "params"] + _UUID
517

    
518
  def CreateOnSecondary(self):
519
    """Test if this device needs to be created on a secondary node."""
520
    return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
521

    
522
  def AssembleOnSecondary(self):
523
    """Test if this device needs to be assembled on a secondary node."""
524
    return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
525

    
526
  def OpenOnSecondary(self):
527
    """Test if this device needs to be opened on a secondary node."""
528
    return self.dev_type in (constants.LD_LV,)
529

    
530
  def StaticDevPath(self):
531
    """Return the device path if this device type has a static one.
532

533
    Some devices (LVM for example) live always at the same /dev/ path,
534
    irrespective of their status. For such devices, we return this
535
    path, for others we return None.
536

537
    @warning: The path returned is not a normalized pathname; callers
538
        should check that it is a valid path.
539

540
    """
541
    if self.dev_type == constants.LD_LV:
542
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
543
    elif self.dev_type == constants.LD_BLOCKDEV:
544
      return self.logical_id[1]
545
    elif self.dev_type == constants.LD_RBD:
546
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
547
    return None
548

    
549
  def ChildrenNeeded(self):
550
    """Compute the needed number of children for activation.
551

552
    This method will return either -1 (all children) or a positive
553
    number denoting the minimum number of children needed for
554
    activation (only mirrored devices will usually return >=0).
555

556
    Currently, only DRBD8 supports diskless activation (therefore we
557
    return 0), for all other we keep the previous semantics and return
558
    -1.
559

560
    """
561
    if self.dev_type == constants.LD_DRBD8:
562
      return 0
563
    return -1
564

    
565
  def IsBasedOnDiskType(self, dev_type):
566
    """Check if the disk or its children are based on the given type.
567

568
    @type dev_type: L{constants.LDS_BLOCK}
569
    @param dev_type: the type to look for
570
    @rtype: boolean
571
    @return: boolean indicating if a device of the given type was found or not
572

573
    """
574
    if self.children:
575
      for child in self.children:
576
        if child.IsBasedOnDiskType(dev_type):
577
          return True
578
    return self.dev_type == dev_type
579

    
580
  def GetNodes(self, node):
581
    """This function returns the nodes this device lives on.
582

583
    Given the node on which the parent of the device lives on (or, in
584
    case of a top-level device, the primary node of the devices'
585
    instance), this function will return a list of nodes on which this
586
    devices needs to (or can) be assembled.
587

588
    """
589
    if self.dev_type in [constants.LD_LV, constants.LD_FILE,
590
                         constants.LD_BLOCKDEV, constants.LD_RBD,
591
                         constants.LD_EXT]:
592
      result = [node]
593
    elif self.dev_type in constants.LDS_DRBD:
594
      result = [self.logical_id[0], self.logical_id[1]]
595
      if node not in result:
596
        raise errors.ConfigurationError("DRBD device passed unknown node")
597
    else:
598
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
599
    return result
600

    
601
  def ComputeNodeTree(self, parent_node):
602
    """Compute the node/disk tree for this disk and its children.
603

604
    This method, given the node on which the parent disk lives, will
605
    return the list of all (node, disk) pairs which describe the disk
606
    tree in the most compact way. For example, a drbd/lvm stack
607
    will be returned as (primary_node, drbd) and (secondary_node, drbd)
608
    which represents all the top-level devices on the nodes.
609

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

    
636
  def ComputeGrowth(self, amount):
637
    """Compute the per-VG growth requirements.
638

639
    This only works for VG-based disks.
640

641
    @type amount: integer
642
    @param amount: the desired increase in (user-visible) disk space
643
    @rtype: dict
644
    @return: a dictionary of volume-groups and the required size
645

646
    """
647
    if self.dev_type == constants.LD_LV:
648
      return {self.logical_id[0]: amount}
649
    elif self.dev_type == constants.LD_DRBD8:
650
      if self.children:
651
        return self.children[0].ComputeGrowth(amount)
652
      else:
653
        return {}
654
    else:
655
      # Other disk types do not require VG space
656
      return {}
657

    
658
  def RecordGrow(self, amount):
659
    """Update the size of this disk after growth.
660

661
    This method recurses over the disks's children and updates their
662
    size correspondigly. The method needs to be kept in sync with the
663
    actual algorithms from bdev.
664

665
    """
666
    if self.dev_type in (constants.LD_LV, constants.LD_FILE,
667
                         constants.LD_RBD, constants.LD_EXT):
668
      self.size += amount
669
    elif self.dev_type == constants.LD_DRBD8:
670
      if self.children:
671
        self.children[0].RecordGrow(amount)
672
      self.size += amount
673
    else:
674
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
675
                                   " disk type %s" % self.dev_type)
676

    
677
  def Update(self, size=None, mode=None):
678
    """Apply changes to size and mode.
679

680
    """
681
    if self.dev_type == constants.LD_DRBD8:
682
      if self.children:
683
        self.children[0].Update(size=size, mode=mode)
684
    else:
685
      assert not self.children
686

    
687
    if size is not None:
688
      self.size = size
689
    if mode is not None:
690
      self.mode = mode
691

    
692
  def UnsetSize(self):
693
    """Sets recursively the size to zero for the disk and its children.
694

695
    """
696
    if self.children:
697
      for child in self.children:
698
        child.UnsetSize()
699
    self.size = 0
700

    
701
  def SetPhysicalID(self, target_node, nodes_ip):
702
    """Convert the logical ID to the physical ID.
703

704
    This is used only for drbd, which needs ip/port configuration.
705

706
    The routine descends down and updates its children also, because
707
    this helps when the only the top device is passed to the remote
708
    node.
709

710
    Arguments:
711
      - target_node: the node we wish to configure for
712
      - nodes_ip: a mapping of node name to ip
713

714
    The target_node must exist in in nodes_ip, and must be one of the
715
    nodes in the logical ID for each of the DRBD devices encountered
716
    in the disk tree.
717

718
    """
719
    if self.children:
720
      for child in self.children:
721
        child.SetPhysicalID(target_node, nodes_ip)
722

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

    
745
  def ToDict(self):
746
    """Disk-specific conversion to standard python types.
747

748
    This replaces the children lists of objects with lists of
749
    standard python types.
750

751
    """
752
    bo = super(Disk, self).ToDict()
753

    
754
    for attr in ("children",):
755
      alist = bo.get(attr, None)
756
      if alist:
757
        bo[attr] = outils.ContainerToDicts(alist)
758
    return bo
759

    
760
  @classmethod
761
  def FromDict(cls, val):
762
    """Custom function for Disks
763

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

    
778
  def __str__(self):
779
    """Custom str() formatter for disks.
780

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

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

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

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

    
822
  def UpgradeConfig(self):
823
    """Fill defaults for missing configuration values.
824

825
    """
826
    if self.children:
827
      for child in self.children:
828
        child.UpgradeConfig()
829

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

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

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

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

    
851
    assert disk_template in disk_params
852

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

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

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

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

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

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

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

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

    
900
    return result
901

    
902

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

999
    """
1000
    minspec = minmaxspecs[constants.ISPECS_MIN]
1001
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1002
    min_v = minspec[name]
1003
    max_v = maxspec[name]
1004

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

    
1015
  @classmethod
1016
  def CheckDiskTemplates(cls, disk_templates):
1017
    """Checks the disk templates for validity.
1018

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

    
1028
  @classmethod
1029
  def CheckParameter(cls, key, value):
1030
    """Checks a parameter.
1031

1032
    Currently we expect all parameters to be float values.
1033

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

    
1041

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

    
1060
  def _ComputeSecondaryNodes(self):
1061
    """Compute the list of secondary nodes.
1062

1063
    This is a simple wrapper over _ComputeAllNodes.
1064

1065
    """
1066
    all_nodes = set(self._ComputeAllNodes())
1067
    all_nodes.discard(self.primary_node)
1068
    return tuple(all_nodes)
1069

    
1070
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1071
                             "List of names of secondary nodes")
1072

    
1073
  def _ComputeAllNodes(self):
1074
    """Compute the list of all nodes.
1075

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

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

    
1092
    all_nodes = set()
1093
    all_nodes.add(self.primary_node)
1094
    for device in self.disks:
1095
      _Helper(all_nodes, device)
1096
    return tuple(all_nodes)
1097

    
1098
  all_nodes = property(_ComputeAllNodes, None, None,
1099
                       "List of names of all the nodes of the instance")
1100

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

1104
    This function figures out what logical volumes should belong on
1105
    which nodes, recursing through a device tree.
1106

1107
    @param lvmap: optional dictionary to receive the
1108
        'node' : ['lv', ...] data.
1109

1110
    @return: None if lvmap arg is given, otherwise, a dictionary of
1111
        the form { 'nodename' : ['volume1', 'volume2', ...], ... };
1112
        volumeN is of the form "vg_name/lv_name", compatible with
1113
        GetVolumeList()
1114

1115
    """
1116
    if node is None:
1117
      node = self.primary_node
1118

    
1119
    if lvmap is None:
1120
      lvmap = {
1121
        node: [],
1122
        }
1123
      ret = lvmap
1124
    else:
1125
      if not node in lvmap:
1126
        lvmap[node] = []
1127
      ret = None
1128

    
1129
    if not devs:
1130
      devs = self.disks
1131

    
1132
    for dev in devs:
1133
      if dev.dev_type == constants.LD_LV:
1134
        lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1135

    
1136
      elif dev.dev_type in constants.LDS_DRBD:
1137
        if dev.children:
1138
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1139
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1140

    
1141
      elif dev.children:
1142
        self.MapLVsByNode(lvmap, dev.children, node)
1143

    
1144
    return ret
1145

    
1146
  def FindDisk(self, idx):
1147
    """Find a disk given having a specified index.
1148

1149
    This is just a wrapper that does validation of the index.
1150

1151
    @type idx: int
1152
    @param idx: the disk index
1153
    @rtype: L{Disk}
1154
    @return: the corresponding disk
1155
    @raise errors.OpPrereqError: when the given index is not valid
1156

1157
    """
1158
    try:
1159
      idx = int(idx)
1160
      return self.disks[idx]
1161
    except (TypeError, ValueError), err:
1162
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1163
                                 errors.ECODE_INVAL)
1164
    except IndexError:
1165
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1166
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1167
                                 errors.ECODE_INVAL)
1168

    
1169
  def ToDict(self):
1170
    """Instance-specific conversion to standard python types.
1171

1172
    This replaces the children lists of objects with lists of standard
1173
    python types.
1174

1175
    """
1176
    bo = super(Instance, self).ToDict()
1177

    
1178
    for attr in "nics", "disks":
1179
      alist = bo.get(attr, None)
1180
      if alist:
1181
        nlist = outils.ContainerToDicts(alist)
1182
      else:
1183
        nlist = []
1184
      bo[attr] = nlist
1185
    return bo
1186

    
1187
  @classmethod
1188
  def FromDict(cls, val):
1189
    """Custom function for instances.
1190

1191
    """
1192
    if "admin_state" not in val:
1193
      if val.get("admin_up", False):
1194
        val["admin_state"] = constants.ADMINST_UP
1195
      else:
1196
        val["admin_state"] = constants.ADMINST_DOWN
1197
    if "admin_up" in val:
1198
      del val["admin_up"]
1199
    obj = super(Instance, cls).FromDict(val)
1200
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1201
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1202
    return obj
1203

    
1204
  def UpgradeConfig(self):
1205
    """Fill defaults for missing configuration values.
1206

1207
    """
1208
    for nic in self.nics:
1209
      nic.UpgradeConfig()
1210
    for disk in self.disks:
1211
      disk.UpgradeConfig()
1212
    if self.hvparams:
1213
      for key in constants.HVC_GLOBALS:
1214
        try:
1215
          del self.hvparams[key]
1216
        except KeyError:
1217
          pass
1218
    if self.osparams is None:
1219
      self.osparams = {}
1220
    UpgradeBeParams(self.beparams)
1221

    
1222

    
1223
class OS(ConfigObject):
1224
  """Config object representing an operating system.
1225

1226
  @type supported_parameters: list
1227
  @ivar supported_parameters: a list of tuples, name and description,
1228
      containing the supported parameters by this OS
1229

1230
  @type VARIANT_DELIM: string
1231
  @cvar VARIANT_DELIM: the variant delimiter
1232

1233
  """
1234
  __slots__ = [
1235
    "name",
1236
    "path",
1237
    "api_versions",
1238
    "create_script",
1239
    "export_script",
1240
    "import_script",
1241
    "rename_script",
1242
    "verify_script",
1243
    "supported_variants",
1244
    "supported_parameters",
1245
    ]
1246

    
1247
  VARIANT_DELIM = "+"
1248

    
1249
  @classmethod
1250
  def SplitNameVariant(cls, name):
1251
    """Splits the name into the proper name and variant.
1252

1253
    @param name: the OS (unprocessed) name
1254
    @rtype: list
1255
    @return: a list of two elements; if the original name didn't
1256
        contain a variant, it's returned as an empty string
1257

1258
    """
1259
    nv = name.split(cls.VARIANT_DELIM, 1)
1260
    if len(nv) == 1:
1261
      nv.append("")
1262
    return nv
1263

    
1264
  @classmethod
1265
  def GetName(cls, name):
1266
    """Returns the proper name of the os (without the variant).
1267

1268
    @param name: the OS (unprocessed) name
1269

1270
    """
1271
    return cls.SplitNameVariant(name)[0]
1272

    
1273
  @classmethod
1274
  def GetVariant(cls, name):
1275
    """Returns the variant the os (without the base name).
1276

1277
    @param name: the OS (unprocessed) name
1278

1279
    """
1280
    return cls.SplitNameVariant(name)[1]
1281

    
1282

    
1283
class ExtStorage(ConfigObject):
1284
  """Config object representing an External Storage Provider.
1285

1286
  """
1287
  __slots__ = [
1288
    "name",
1289
    "path",
1290
    "create_script",
1291
    "remove_script",
1292
    "grow_script",
1293
    "attach_script",
1294
    "detach_script",
1295
    "setinfo_script",
1296
    "verify_script",
1297
    "supported_parameters",
1298
    ]
1299

    
1300

    
1301
class NodeHvState(ConfigObject):
1302
  """Hypvervisor state on a node.
1303

1304
  @ivar mem_total: Total amount of memory
1305
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1306
    available)
1307
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1308
    rounding
1309
  @ivar mem_inst: Memory used by instances living on node
1310
  @ivar cpu_total: Total node CPU core count
1311
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1312

1313
  """
1314
  __slots__ = [
1315
    "mem_total",
1316
    "mem_node",
1317
    "mem_hv",
1318
    "mem_inst",
1319
    "cpu_total",
1320
    "cpu_node",
1321
    ] + _TIMESTAMPS
1322

    
1323

    
1324
class NodeDiskState(ConfigObject):
1325
  """Disk state on a node.
1326

1327
  """
1328
  __slots__ = [
1329
    "total",
1330
    "reserved",
1331
    "overhead",
1332
    ] + _TIMESTAMPS
1333

    
1334

    
1335
class Node(TaggableObject):
1336
  """Config object representing a node.
1337

1338
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1339
  @ivar hv_state_static: Hypervisor state overriden by user
1340
  @ivar disk_state: Disk state (e.g. free space)
1341
  @ivar disk_state_static: Disk state overriden by user
1342

1343
  """
1344
  __slots__ = [
1345
    "name",
1346
    "primary_ip",
1347
    "secondary_ip",
1348
    "serial_no",
1349
    "master_candidate",
1350
    "offline",
1351
    "drained",
1352
    "group",
1353
    "master_capable",
1354
    "vm_capable",
1355
    "ndparams",
1356
    "powered",
1357
    "hv_state",
1358
    "hv_state_static",
1359
    "disk_state",
1360
    "disk_state_static",
1361
    ] + _TIMESTAMPS + _UUID
1362

    
1363
  def UpgradeConfig(self):
1364
    """Fill defaults for missing configuration values.
1365

1366
    """
1367
    # pylint: disable=E0203
1368
    # because these are "defined" via slots, not manually
1369
    if self.master_capable is None:
1370
      self.master_capable = True
1371

    
1372
    if self.vm_capable is None:
1373
      self.vm_capable = True
1374

    
1375
    if self.ndparams is None:
1376
      self.ndparams = {}
1377
    # And remove any global parameter
1378
    for key in constants.NDC_GLOBALS:
1379
      if key in self.ndparams:
1380
        logging.warning("Ignoring %s node parameter for node %s",
1381
                        key, self.name)
1382
        del self.ndparams[key]
1383

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

    
1387
  def ToDict(self):
1388
    """Custom function for serializing.
1389

1390
    """
1391
    data = super(Node, self).ToDict()
1392

    
1393
    hv_state = data.get("hv_state", None)
1394
    if hv_state is not None:
1395
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1396

    
1397
    disk_state = data.get("disk_state", None)
1398
    if disk_state is not None:
1399
      data["disk_state"] = \
1400
        dict((key, outils.ContainerToDicts(value))
1401
             for (key, value) in disk_state.items())
1402

    
1403
    return data
1404

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

1409
    """
1410
    obj = super(Node, cls).FromDict(val)
1411

    
1412
    if obj.hv_state is not None:
1413
      obj.hv_state = \
1414
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1415

    
1416
    if obj.disk_state is not None:
1417
      obj.disk_state = \
1418
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1419
             for (key, value) in obj.disk_state.items())
1420

    
1421
    return obj
1422

    
1423

    
1424
class NodeGroup(TaggableObject):
1425
  """Config object representing a node group."""
1426
  __slots__ = [
1427
    "name",
1428
    "members",
1429
    "ndparams",
1430
    "diskparams",
1431
    "ipolicy",
1432
    "serial_no",
1433
    "hv_state_static",
1434
    "disk_state_static",
1435
    "alloc_policy",
1436
    "networks",
1437
    ] + _TIMESTAMPS + _UUID
1438

    
1439
  def ToDict(self):
1440
    """Custom function for nodegroup.
1441

1442
    This discards the members object, which gets recalculated and is only kept
1443
    in memory.
1444

1445
    """
1446
    mydict = super(NodeGroup, self).ToDict()
1447
    del mydict["members"]
1448
    return mydict
1449

    
1450
  @classmethod
1451
  def FromDict(cls, val):
1452
    """Custom function for nodegroup.
1453

1454
    The members slot is initialized to an empty list, upon deserialization.
1455

1456
    """
1457
    obj = super(NodeGroup, cls).FromDict(val)
1458
    obj.members = []
1459
    return obj
1460

    
1461
  def UpgradeConfig(self):
1462
    """Fill defaults for missing configuration values.
1463

1464
    """
1465
    if self.ndparams is None:
1466
      self.ndparams = {}
1467

    
1468
    if self.serial_no is None:
1469
      self.serial_no = 1
1470

    
1471
    if self.alloc_policy is None:
1472
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1473

    
1474
    # We only update mtime, and not ctime, since we would not be able
1475
    # to provide a correct value for creation time.
1476
    if self.mtime is None:
1477
      self.mtime = time.time()
1478

    
1479
    if self.diskparams is None:
1480
      self.diskparams = {}
1481
    if self.ipolicy is None:
1482
      self.ipolicy = MakeEmptyIPolicy()
1483

    
1484
    if self.networks is None:
1485
      self.networks = {}
1486

    
1487
  def FillND(self, node):
1488
    """Return filled out ndparams for L{objects.Node}
1489

1490
    @type node: L{objects.Node}
1491
    @param node: A Node object to fill
1492
    @return a copy of the node's ndparams with defaults filled
1493

1494
    """
1495
    return self.SimpleFillND(node.ndparams)
1496

    
1497
  def SimpleFillND(self, ndparams):
1498
    """Fill a given ndparams dict with defaults.
1499

1500
    @type ndparams: dict
1501
    @param ndparams: the dict to fill
1502
    @rtype: dict
1503
    @return: a copy of the passed in ndparams with missing keys filled
1504
        from the node group defaults
1505

1506
    """
1507
    return FillDict(self.ndparams, ndparams)
1508

    
1509

    
1510
class Cluster(TaggableObject):
1511
  """Config object representing the cluster."""
1512
  __slots__ = [
1513
    "serial_no",
1514
    "rsahostkeypub",
1515
    "highest_used_port",
1516
    "tcpudp_port_pool",
1517
    "mac_prefix",
1518
    "volume_group_name",
1519
    "reserved_lvs",
1520
    "drbd_usermode_helper",
1521
    "default_bridge",
1522
    "default_hypervisor",
1523
    "master_node",
1524
    "master_ip",
1525
    "master_netdev",
1526
    "master_netmask",
1527
    "use_external_mip_script",
1528
    "cluster_name",
1529
    "file_storage_dir",
1530
    "shared_file_storage_dir",
1531
    "enabled_hypervisors",
1532
    "hvparams",
1533
    "ipolicy",
1534
    "os_hvp",
1535
    "beparams",
1536
    "osparams",
1537
    "nicparams",
1538
    "ndparams",
1539
    "diskparams",
1540
    "candidate_pool_size",
1541
    "modify_etc_hosts",
1542
    "modify_ssh_setup",
1543
    "maintain_node_health",
1544
    "uid_pool",
1545
    "default_iallocator",
1546
    "hidden_os",
1547
    "blacklisted_os",
1548
    "primary_ip_family",
1549
    "prealloc_wipe_disks",
1550
    "hv_state_static",
1551
    "disk_state_static",
1552
    "enabled_disk_templates",
1553
    ] + _TIMESTAMPS + _UUID
1554

    
1555
  def UpgradeConfig(self):
1556
    """Fill defaults for missing configuration values.
1557

1558
    """
1559
    # pylint: disable=E0203
1560
    # because these are "defined" via slots, not manually
1561
    if self.hvparams is None:
1562
      self.hvparams = constants.HVC_DEFAULTS
1563
    else:
1564
      for hypervisor in self.hvparams:
1565
        self.hvparams[hypervisor] = FillDict(
1566
            constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1567

    
1568
    if self.os_hvp is None:
1569
      self.os_hvp = {}
1570

    
1571
    # osparams added before 2.2
1572
    if self.osparams is None:
1573
      self.osparams = {}
1574

    
1575
    self.ndparams = UpgradeNDParams(self.ndparams)
1576

    
1577
    self.beparams = UpgradeGroupedParams(self.beparams,
1578
                                         constants.BEC_DEFAULTS)
1579
    for beparams_group in self.beparams:
1580
      UpgradeBeParams(self.beparams[beparams_group])
1581

    
1582
    migrate_default_bridge = not self.nicparams
1583
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1584
                                          constants.NICC_DEFAULTS)
1585
    if migrate_default_bridge:
1586
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1587
        self.default_bridge
1588

    
1589
    if self.modify_etc_hosts is None:
1590
      self.modify_etc_hosts = True
1591

    
1592
    if self.modify_ssh_setup is None:
1593
      self.modify_ssh_setup = True
1594

    
1595
    # default_bridge is no longer used in 2.1. The slot is left there to
1596
    # support auto-upgrading. It can be removed once we decide to deprecate
1597
    # upgrading straight from 2.0.
1598
    if self.default_bridge is not None:
1599
      self.default_bridge = None
1600

    
1601
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1602
    # code can be removed once upgrading straight from 2.0 is deprecated.
1603
    if self.default_hypervisor is not None:
1604
      self.enabled_hypervisors = ([self.default_hypervisor] +
1605
                                  [hvname for hvname in self.enabled_hypervisors
1606
                                   if hvname != self.default_hypervisor])
1607
      self.default_hypervisor = None
1608

    
1609
    # maintain_node_health added after 2.1.1
1610
    if self.maintain_node_health is None:
1611
      self.maintain_node_health = False
1612

    
1613
    if self.uid_pool is None:
1614
      self.uid_pool = []
1615

    
1616
    if self.default_iallocator is None:
1617
      self.default_iallocator = ""
1618

    
1619
    # reserved_lvs added before 2.2
1620
    if self.reserved_lvs is None:
1621
      self.reserved_lvs = []
1622

    
1623
    # hidden and blacklisted operating systems added before 2.2.1
1624
    if self.hidden_os is None:
1625
      self.hidden_os = []
1626

    
1627
    if self.blacklisted_os is None:
1628
      self.blacklisted_os = []
1629

    
1630
    # primary_ip_family added before 2.3
1631
    if self.primary_ip_family is None:
1632
      self.primary_ip_family = AF_INET
1633

    
1634
    if self.master_netmask is None:
1635
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1636
      self.master_netmask = ipcls.iplen
1637

    
1638
    if self.prealloc_wipe_disks is None:
1639
      self.prealloc_wipe_disks = False
1640

    
1641
    # shared_file_storage_dir added before 2.5
1642
    if self.shared_file_storage_dir is None:
1643
      self.shared_file_storage_dir = ""
1644

    
1645
    if self.use_external_mip_script is None:
1646
      self.use_external_mip_script = False
1647

    
1648
    if self.diskparams:
1649
      self.diskparams = UpgradeDiskParams(self.diskparams)
1650
    else:
1651
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1652

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

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

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

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

    
1677
  def ToDict(self):
1678
    """Custom function for cluster.
1679

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

    
1683
    if self.tcpudp_port_pool is None:
1684
      tcpudp_port_pool = []
1685
    else:
1686
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1687

    
1688
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1689

    
1690
    return mydict
1691

    
1692
  @classmethod
1693
  def FromDict(cls, val):
1694
    """Custom function for cluster.
1695

1696
    """
1697
    obj = super(Cluster, cls).FromDict(val)
1698

    
1699
    if obj.tcpudp_port_pool is None:
1700
      obj.tcpudp_port_pool = set()
1701
    elif not isinstance(obj.tcpudp_port_pool, set):
1702
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1703

    
1704
    return obj
1705

    
1706
  def SimpleFillDP(self, diskparams):
1707
    """Fill a given diskparams dict with cluster defaults.
1708

1709
    @param diskparams: The diskparams
1710
    @return: The defaults dict
1711

1712
    """
1713
    return FillDiskParams(self.diskparams, diskparams)
1714

    
1715
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1716
    """Get the default hypervisor parameters for the cluster.
1717

1718
    @param hypervisor: the hypervisor name
1719
    @param os_name: if specified, we'll also update the defaults for this OS
1720
    @param skip_keys: if passed, list of keys not to use
1721
    @return: the defaults dict
1722

1723
    """
1724
    if skip_keys is None:
1725
      skip_keys = []
1726

    
1727
    fill_stack = [self.hvparams.get(hypervisor, {})]
1728
    if os_name is not None:
1729
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1730
      fill_stack.append(os_hvp)
1731

    
1732
    ret_dict = {}
1733
    for o_dict in fill_stack:
1734
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1735

    
1736
    return ret_dict
1737

    
1738
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1739
    """Fill a given hvparams dict with cluster defaults.
1740

1741
    @type hv_name: string
1742
    @param hv_name: the hypervisor to use
1743
    @type os_name: string
1744
    @param os_name: the OS to use for overriding the hypervisor defaults
1745
    @type skip_globals: boolean
1746
    @param skip_globals: if True, the global hypervisor parameters will
1747
        not be filled
1748
    @rtype: dict
1749
    @return: a copy of the given hvparams with missing keys filled from
1750
        the cluster defaults
1751

1752
    """
1753
    if skip_globals:
1754
      skip_keys = constants.HVC_GLOBALS
1755
    else:
1756
      skip_keys = []
1757

    
1758
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1759
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1760

    
1761
  def FillHV(self, instance, skip_globals=False):
1762
    """Fill an instance's hvparams dict with cluster defaults.
1763

1764
    @type instance: L{objects.Instance}
1765
    @param instance: the instance parameter to fill
1766
    @type skip_globals: boolean
1767
    @param skip_globals: if True, the global hypervisor parameters will
1768
        not be filled
1769
    @rtype: dict
1770
    @return: a copy of the instance's hvparams with missing keys filled from
1771
        the cluster defaults
1772

1773
    """
1774
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1775
                             instance.hvparams, skip_globals)
1776

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

1780
    @type beparams: dict
1781
    @param beparams: the dict to fill
1782
    @rtype: dict
1783
    @return: a copy of the passed in beparams with missing keys filled
1784
        from the cluster defaults
1785

1786
    """
1787
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1788

    
1789
  def FillBE(self, instance):
1790
    """Fill an instance's beparams dict with cluster defaults.
1791

1792
    @type instance: L{objects.Instance}
1793
    @param instance: the instance parameter to fill
1794
    @rtype: dict
1795
    @return: a copy of the instance's beparams with missing keys filled from
1796
        the cluster defaults
1797

1798
    """
1799
    return self.SimpleFillBE(instance.beparams)
1800

    
1801
  def SimpleFillNIC(self, nicparams):
1802
    """Fill a given nicparams dict with cluster defaults.
1803

1804
    @type nicparams: dict
1805
    @param nicparams: the dict to fill
1806
    @rtype: dict
1807
    @return: a copy of the passed in nicparams with missing keys filled
1808
        from the cluster defaults
1809

1810
    """
1811
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1812

    
1813
  def SimpleFillOS(self, os_name, os_params):
1814
    """Fill an instance's osparams dict with cluster defaults.
1815

1816
    @type os_name: string
1817
    @param os_name: the OS name to use
1818
    @type os_params: dict
1819
    @param os_params: the dict to fill with default values
1820
    @rtype: dict
1821
    @return: a copy of the instance's osparams with missing keys filled from
1822
        the cluster defaults
1823

1824
    """
1825
    name_only = os_name.split("+", 1)[0]
1826
    # base OS
1827
    result = self.osparams.get(name_only, {})
1828
    # OS with variant
1829
    result = FillDict(result, self.osparams.get(os_name, {}))
1830
    # specified params
1831
    return FillDict(result, os_params)
1832

    
1833
  @staticmethod
1834
  def SimpleFillHvState(hv_state):
1835
    """Fill an hv_state sub dict with cluster defaults.
1836

1837
    """
1838
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1839

    
1840
  @staticmethod
1841
  def SimpleFillDiskState(disk_state):
1842
    """Fill an disk_state sub dict with cluster defaults.
1843

1844
    """
1845
    return FillDict(constants.DS_DEFAULTS, disk_state)
1846

    
1847
  def FillND(self, node, nodegroup):
1848
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1849

1850
    @type node: L{objects.Node}
1851
    @param node: A Node object to fill
1852
    @type nodegroup: L{objects.NodeGroup}
1853
    @param nodegroup: A Node object to fill
1854
    @return a copy of the node's ndparams with defaults filled
1855

1856
    """
1857
    return self.SimpleFillND(nodegroup.FillND(node))
1858

    
1859
  def SimpleFillND(self, ndparams):
1860
    """Fill a given ndparams dict with defaults.
1861

1862
    @type ndparams: dict
1863
    @param ndparams: the dict to fill
1864
    @rtype: dict
1865
    @return: a copy of the passed in ndparams with missing keys filled
1866
        from the cluster defaults
1867

1868
    """
1869
    return FillDict(self.ndparams, ndparams)
1870

    
1871
  def SimpleFillIPolicy(self, ipolicy):
1872
    """ Fill instance policy dict with defaults.
1873

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

1880
    """
1881
    return FillIPolicy(self.ipolicy, ipolicy)
1882

    
1883

    
1884
class BlockDevStatus(ConfigObject):
1885
  """Config object representing the status of a block device."""
1886
  __slots__ = [
1887
    "dev_path",
1888
    "major",
1889
    "minor",
1890
    "sync_percent",
1891
    "estimated_time",
1892
    "is_degraded",
1893
    "ldisk_status",
1894
    ]
1895

    
1896

    
1897
class ImportExportStatus(ConfigObject):
1898
  """Config object representing the status of an import or export."""
1899
  __slots__ = [
1900
    "recent_output",
1901
    "listen_port",
1902
    "connected",
1903
    "progress_mbytes",
1904
    "progress_throughput",
1905
    "progress_eta",
1906
    "progress_percent",
1907
    "exit_status",
1908
    "error_message",
1909
    ] + _TIMESTAMPS
1910

    
1911

    
1912
class ImportExportOptions(ConfigObject):
1913
  """Options for import/export daemon
1914

1915
  @ivar key_name: X509 key name (None for cluster certificate)
1916
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1917
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
1918
  @ivar magic: Used to ensure the connection goes to the right disk
1919
  @ivar ipv6: Whether to use IPv6
1920
  @ivar connect_timeout: Number of seconds for establishing connection
1921

1922
  """
1923
  __slots__ = [
1924
    "key_name",
1925
    "ca_pem",
1926
    "compress",
1927
    "magic",
1928
    "ipv6",
1929
    "connect_timeout",
1930
    ]
1931

    
1932

    
1933
class ConfdRequest(ConfigObject):
1934
  """Object holding a confd request.
1935

1936
  @ivar protocol: confd protocol version
1937
  @ivar type: confd query type
1938
  @ivar query: query request
1939
  @ivar rsalt: requested reply salt
1940

1941
  """
1942
  __slots__ = [
1943
    "protocol",
1944
    "type",
1945
    "query",
1946
    "rsalt",
1947
    ]
1948

    
1949

    
1950
class ConfdReply(ConfigObject):
1951
  """Object holding a confd reply.
1952

1953
  @ivar protocol: confd protocol version
1954
  @ivar status: reply status code (ok, error)
1955
  @ivar answer: confd query reply
1956
  @ivar serial: configuration serial number
1957

1958
  """
1959
  __slots__ = [
1960
    "protocol",
1961
    "status",
1962
    "answer",
1963
    "serial",
1964
    ]
1965

    
1966

    
1967
class QueryFieldDefinition(ConfigObject):
1968
  """Object holding a query field definition.
1969

1970
  @ivar name: Field name
1971
  @ivar title: Human-readable title
1972
  @ivar kind: Field type
1973
  @ivar doc: Human-readable description
1974

1975
  """
1976
  __slots__ = [
1977
    "name",
1978
    "title",
1979
    "kind",
1980
    "doc",
1981
    ]
1982

    
1983

    
1984
class _QueryResponseBase(ConfigObject):
1985
  __slots__ = [
1986
    "fields",
1987
    ]
1988

    
1989
  def ToDict(self):
1990
    """Custom function for serializing.
1991

1992
    """
1993
    mydict = super(_QueryResponseBase, self).ToDict()
1994
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
1995
    return mydict
1996

    
1997
  @classmethod
1998
  def FromDict(cls, val):
1999
    """Custom function for de-serializing.
2000

2001
    """
2002
    obj = super(_QueryResponseBase, cls).FromDict(val)
2003
    obj.fields = \
2004
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2005
    return obj
2006

    
2007

    
2008
class QueryResponse(_QueryResponseBase):
2009
  """Object holding the response to a query.
2010

2011
  @ivar fields: List of L{QueryFieldDefinition} objects
2012
  @ivar data: Requested data
2013

2014
  """
2015
  __slots__ = [
2016
    "data",
2017
    ]
2018

    
2019

    
2020
class QueryFieldsRequest(ConfigObject):
2021
  """Object holding a request for querying available fields.
2022

2023
  """
2024
  __slots__ = [
2025
    "what",
2026
    "fields",
2027
    ]
2028

    
2029

    
2030
class QueryFieldsResponse(_QueryResponseBase):
2031
  """Object holding the response to a query for fields.
2032

2033
  @ivar fields: List of L{QueryFieldDefinition} objects
2034

2035
  """
2036
  __slots__ = []
2037

    
2038

    
2039
class MigrationStatus(ConfigObject):
2040
  """Object holding the status of a migration.
2041

2042
  """
2043
  __slots__ = [
2044
    "status",
2045
    "transferred_ram",
2046
    "total_ram",
2047
    ]
2048

    
2049

    
2050
class InstanceConsole(ConfigObject):
2051
  """Object describing how to access the console of an instance.
2052

2053
  """
2054
  __slots__ = [
2055
    "instance",
2056
    "kind",
2057
    "message",
2058
    "host",
2059
    "port",
2060
    "user",
2061
    "command",
2062
    "display",
2063
    ]
2064

    
2065
  def Validate(self):
2066
    """Validates contents of this object.
2067

2068
    """
2069
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2070
    assert self.instance, "Missing instance name"
2071
    assert self.message or self.kind in [constants.CONS_SSH,
2072
                                         constants.CONS_SPICE,
2073
                                         constants.CONS_VNC]
2074
    assert self.host or self.kind == constants.CONS_MESSAGE
2075
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2076
                                      constants.CONS_SSH]
2077
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2078
                                      constants.CONS_SPICE,
2079
                                      constants.CONS_VNC]
2080
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2081
                                         constants.CONS_SPICE,
2082
                                         constants.CONS_VNC]
2083
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2084
                                         constants.CONS_SPICE,
2085
                                         constants.CONS_SSH]
2086
    return True
2087

    
2088

    
2089
class Network(TaggableObject):
2090
  """Object representing a network definition for ganeti.
2091

2092
  """
2093
  __slots__ = [
2094
    "name",
2095
    "serial_no",
2096
    "mac_prefix",
2097
    "network",
2098
    "network6",
2099
    "gateway",
2100
    "gateway6",
2101
    "reservations",
2102
    "ext_reservations",
2103
    ] + _TIMESTAMPS + _UUID
2104

    
2105
  def HooksDict(self, prefix=""):
2106
    """Export a dictionary used by hooks with a network's information.
2107

2108
    @type prefix: String
2109
    @param prefix: Prefix to prepend to the dict entries
2110

2111
    """
2112
    result = {
2113
      "%sNETWORK_NAME" % prefix: self.name,
2114
      "%sNETWORK_UUID" % prefix: self.uuid,
2115
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2116
    }
2117
    if self.network:
2118
      result["%sNETWORK_SUBNET" % prefix] = self.network
2119
    if self.gateway:
2120
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2121
    if self.network6:
2122
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2123
    if self.gateway6:
2124
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2125
    if self.mac_prefix:
2126
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2127

    
2128
    return result
2129

    
2130
  @classmethod
2131
  def FromDict(cls, val):
2132
    """Custom function for networks.
2133

2134
    Remove deprecated network_type and family.
2135

2136
    """
2137
    if "network_type" in val:
2138
      del val["network_type"]
2139
    if "family" in val:
2140
      del val["family"]
2141
    obj = super(Network, cls).FromDict(val)
2142
    return obj
2143

    
2144

    
2145
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2146
  """Simple wrapper over ConfigParse that allows serialization.
2147

2148
  This class is basically ConfigParser.SafeConfigParser with two
2149
  additional methods that allow it to serialize/unserialize to/from a
2150
  buffer.
2151

2152
  """
2153
  def Dumps(self):
2154
    """Dump this instance and return the string representation."""
2155
    buf = StringIO()
2156
    self.write(buf)
2157
    return buf.getvalue()
2158

    
2159
  @classmethod
2160
  def Loads(cls, data):
2161
    """Load data from a string."""
2162
    buf = StringIO(data)
2163
    cfp = cls()
2164
    cfp.readfp(buf)
2165
    return cfp
2166

    
2167

    
2168
class LvmPvInfo(ConfigObject):
2169
  """Information about an LVM physical volume (PV).
2170

2171
  @type name: string
2172
  @ivar name: name of the PV
2173
  @type vg_name: string
2174
  @ivar vg_name: name of the volume group containing the PV
2175
  @type size: float
2176
  @ivar size: size of the PV in MiB
2177
  @type free: float
2178
  @ivar free: free space in the PV, in MiB
2179
  @type attributes: string
2180
  @ivar attributes: PV attributes
2181
  @type lv_list: list of strings
2182
  @ivar lv_list: names of the LVs hosted on the PV
2183
  """
2184
  __slots__ = [
2185
    "name",
2186
    "vg_name",
2187
    "size",
2188
    "free",
2189
    "attributes",
2190
    "lv_list"
2191
    ]
2192

    
2193
  def IsEmpty(self):
2194
    """Is this PV empty?
2195

2196
    """
2197
    return self.size <= (self.free + 1)
2198

    
2199
  def IsAllocatable(self):
2200
    """Is this PV allocatable?
2201

2202
    """
2203
    return ("a" in self.attributes)