Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ fbab083b

History | View | Annotate | Download (64.6 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 uuid: master nodes UUID
362
  @ivar ip: master IP
363
  @ivar netmask: master netmask
364
  @ivar netdev: master network device
365
  @ivar ip_family: master IP family
366

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

    
376

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

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

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

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

    
401
    return mydict
402

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

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

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

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

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

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

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

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

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

    
487

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

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

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

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

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

    
511

    
512
class Disk(ConfigObject):
513
  """Config object representing a block device."""
514
  __slots__ = (["name", "dev_type", "logical_id", "physical_id",
515
                "children", "iv_name", "size", "mode", "params",
516
                "spindles", "pci"] + _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_uuid):
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_uuid]
593
    elif self.dev_type in constants.LDS_DRBD:
594
      result = [self.logical_id[0], self.logical_id[1]]
595
      if node_uuid 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_uuid):
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 UUID, 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_uuid)
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, spindles=None):
678
    """Apply changes to size, spindles 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
    if spindles is not None:
692
      self.spindles = spindles
693

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

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

    
703
  def SetPhysicalID(self, target_node_uuid, nodes_ip):
704
    """Convert the logical ID to the physical ID.
705

706
    This is used only for drbd, which needs ip/port configuration.
707

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

712
    Arguments:
713
      - target_node_uuid: the node UUID we wish to configure for
714
      - nodes_ip: a mapping of node name to ip
715

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

720
    """
721
    if self.children:
722
      for child in self.children:
723
        child.SetPhysicalID(target_node_uuid, nodes_ip)
724

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

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

750
    This replaces the children lists of objects with lists of
751
    standard python types.
752

753
    """
754
    bo = super(Disk, self).ToDict()
755

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

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

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

    
780
  def __str__(self):
781
    """Custom str() formatter for disks.
782

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

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

    
817
  def Verify(self):
818
    """Checks that this disk is correctly configured.
819

820
    """
821
    all_errors = []
822
    if self.mode not in constants.DISK_ACCESS_SET:
823
      all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
824
    return all_errors
825

    
826
  def UpgradeConfig(self):
827
    """Fill defaults for missing configuration values.
828

829
    """
830
    if self.children:
831
      for child in self.children:
832
        child.UpgradeConfig()
833

    
834
    # FIXME: Make this configurable in Ganeti 2.7
835
    self.params = {}
836
    # add here config upgrade for this disk
837

    
838
  @staticmethod
839
  def ComputeLDParams(disk_template, disk_params):
840
    """Computes Logical Disk parameters from Disk Template parameters.
841

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

851
    """
852
    if disk_template not in constants.DISK_TEMPLATES:
853
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
854

    
855
    assert disk_template in disk_params
856

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

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

    
881
      # metadata LV
882
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
883
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
884
        }))
885

    
886
    elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
887
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
888

    
889
    elif disk_template == constants.DT_PLAIN:
890
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
891
        constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
892
        }))
893

    
894
    elif disk_template == constants.DT_BLOCK:
895
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
896

    
897
    elif disk_template == constants.DT_RBD:
898
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD], {
899
        constants.LDP_POOL: dt_params[constants.RBD_POOL],
900
        }))
901

    
902
    elif disk_template == constants.DT_EXT:
903
      result.append(constants.DISK_LD_DEFAULTS[constants.LD_EXT])
904

    
905
    return result
906

    
907

    
908
class InstancePolicy(ConfigObject):
909
  """Config object representing instance policy limits dictionary.
910

911
  Note that this object is not actually used in the config, it's just
912
  used as a placeholder for a few functions.
913

914
  """
915
  @classmethod
916
  def CheckParameterSyntax(cls, ipolicy, check_std):
917
    """ Check the instance policy for validity.
918

919
    @type ipolicy: dict
920
    @param ipolicy: dictionary with min/max/std specs and policies
921
    @type check_std: bool
922
    @param check_std: Whether to check std value or just assume compliance
923
    @raise errors.ConfigurationError: when the policy is not legal
924

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

    
937
  @classmethod
938
  def _CheckIncompleteSpec(cls, spec, keyname):
939
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
940
    if missing_params:
941
      msg = ("Missing instance specs parameters for %s: %s" %
942
             (keyname, utils.CommaJoin(missing_params)))
943
      raise errors.ConfigurationError(msg)
944

    
945
  @classmethod
946
  def CheckISpecSyntax(cls, ipolicy, check_std):
947
    """Check the instance policy specs for validity.
948

949
    @type ipolicy: dict
950
    @param ipolicy: dictionary with min/max/std specs
951
    @type check_std: bool
952
    @param check_std: Whether to check std value or just assume compliance
953
    @raise errors.ConfigurationError: when specs are not valid
954

955
    """
956
    if constants.ISPECS_MINMAX not in ipolicy:
957
      # Nothing to check
958
      return
959

    
960
    if check_std and constants.ISPECS_STD not in ipolicy:
961
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
962
      raise errors.ConfigurationError(msg)
963
    stdspec = ipolicy.get(constants.ISPECS_STD)
964
    if check_std:
965
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
966

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

    
978
      spec_std_ok = True
979
      for param in constants.ISPECS_PARAMETERS:
980
        par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
981
                                                           param, check_std)
982
        spec_std_ok = spec_std_ok and par_std_ok
983
      std_is_good = std_is_good or spec_std_ok
984
    if not std_is_good:
985
      raise errors.ConfigurationError("Invalid std specifications")
986

    
987
  @classmethod
988
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
989
    """Check the instance policy specs for validity on a given key.
990

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

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

1008
    """
1009
    minspec = minmaxspecs[constants.ISPECS_MIN]
1010
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1011
    min_v = minspec[name]
1012
    max_v = maxspec[name]
1013

    
1014
    if min_v > max_v:
1015
      err = ("Invalid specification of min/max values for %s: %s/%s" %
1016
             (name, min_v, max_v))
1017
      raise errors.ConfigurationError(err)
1018
    elif check_std:
1019
      std_v = stdspec.get(name, min_v)
1020
      return std_v >= min_v and std_v <= max_v
1021
    else:
1022
      return True
1023

    
1024
  @classmethod
1025
  def CheckDiskTemplates(cls, disk_templates):
1026
    """Checks the disk templates for validity.
1027

1028
    """
1029
    if not disk_templates:
1030
      raise errors.ConfigurationError("Instance policy must contain" +
1031
                                      " at least one disk template")
1032
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1033
    if wrong:
1034
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1035
                                      utils.CommaJoin(wrong))
1036

    
1037
  @classmethod
1038
  def CheckParameter(cls, key, value):
1039
    """Checks a parameter.
1040

1041
    Currently we expect all parameters to be float values.
1042

1043
    """
1044
    try:
1045
      float(value)
1046
    except (TypeError, ValueError), err:
1047
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1048
                                      " '%s', error: %s" % (key, value, err))
1049

    
1050

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

    
1070
  def _ComputeSecondaryNodes(self):
1071
    """Compute the list of secondary nodes.
1072

1073
    This is a simple wrapper over _ComputeAllNodes.
1074

1075
    """
1076
    all_nodes = set(self._ComputeAllNodes())
1077
    all_nodes.discard(self.primary_node)
1078
    return tuple(all_nodes)
1079

    
1080
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1081
                             "List of names of secondary nodes")
1082

    
1083
  def _ComputeAllNodes(self):
1084
    """Compute the list of all nodes.
1085

1086
    Since the data is already there (in the drbd disks), keeping it as
1087
    a separate normal attribute is redundant and if not properly
1088
    synchronised can cause problems. Thus it's better to compute it
1089
    dynamically.
1090

1091
    """
1092
    def _Helper(nodes, device):
1093
      """Recursively computes nodes given a top device."""
1094
      if device.dev_type in constants.LDS_DRBD:
1095
        nodea, nodeb = device.logical_id[:2]
1096
        nodes.add(nodea)
1097
        nodes.add(nodeb)
1098
      if device.children:
1099
        for child in device.children:
1100
          _Helper(nodes, child)
1101

    
1102
    all_nodes = set()
1103
    all_nodes.add(self.primary_node)
1104
    for device in self.disks:
1105
      _Helper(all_nodes, device)
1106
    return tuple(all_nodes)
1107

    
1108
  all_nodes = property(_ComputeAllNodes, None, None,
1109
                       "List of names of all the nodes of the instance")
1110

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

1114
    This function figures out what logical volumes should belong on
1115
    which nodes, recursing through a device tree.
1116

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

1131
    """
1132
    if node_uuid is None:
1133
      node_uuid = self.primary_node
1134

    
1135
    if lvmap is None:
1136
      lvmap = {
1137
        node_uuid: [],
1138
        }
1139
      ret = lvmap
1140
    else:
1141
      if not node_uuid in lvmap:
1142
        lvmap[node_uuid] = []
1143
      ret = None
1144

    
1145
    if not devs:
1146
      devs = self.disks
1147

    
1148
    for dev in devs:
1149
      if dev.dev_type == constants.LD_LV:
1150
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1151

    
1152
      elif dev.dev_type in constants.LDS_DRBD:
1153
        if dev.children:
1154
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1155
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1156

    
1157
      elif dev.children:
1158
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1159

    
1160
    return ret
1161

    
1162
  def FindDisk(self, idx):
1163
    """Find a disk given having a specified index.
1164

1165
    This is just a wrapper that does validation of the index.
1166

1167
    @type idx: int
1168
    @param idx: the disk index
1169
    @rtype: L{Disk}
1170
    @return: the corresponding disk
1171
    @raise errors.OpPrereqError: when the given index is not valid
1172

1173
    """
1174
    try:
1175
      idx = int(idx)
1176
      return self.disks[idx]
1177
    except (TypeError, ValueError), err:
1178
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1179
                                 errors.ECODE_INVAL)
1180
    except IndexError:
1181
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1182
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1183
                                 errors.ECODE_INVAL)
1184

    
1185
  def ToDict(self):
1186
    """Instance-specific conversion to standard python types.
1187

1188
    This replaces the children lists of objects with lists of standard
1189
    python types.
1190

1191
    """
1192
    bo = super(Instance, self).ToDict()
1193

    
1194
    for attr in "nics", "disks":
1195
      alist = bo.get(attr, None)
1196
      if alist:
1197
        nlist = outils.ContainerToDicts(alist)
1198
      else:
1199
        nlist = []
1200
      bo[attr] = nlist
1201
    return bo
1202

    
1203
  @classmethod
1204
  def FromDict(cls, val):
1205
    """Custom function for instances.
1206

1207
    """
1208
    if "admin_state" not in val:
1209
      if val.get("admin_up", False):
1210
        val["admin_state"] = constants.ADMINST_UP
1211
      else:
1212
        val["admin_state"] = constants.ADMINST_DOWN
1213
    if "admin_up" in val:
1214
      del val["admin_up"]
1215
    obj = super(Instance, cls).FromDict(val)
1216
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1217
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1218
    return obj
1219

    
1220
  def UpgradeConfig(self):
1221
    """Fill defaults for missing configuration values.
1222

1223
    """
1224
    for nic in self.nics:
1225
      nic.UpgradeConfig()
1226
    for disk in self.disks:
1227
      disk.UpgradeConfig()
1228
    if self.hvparams:
1229
      for key in constants.HVC_GLOBALS:
1230
        try:
1231
          del self.hvparams[key]
1232
        except KeyError:
1233
          pass
1234
    if self.osparams is None:
1235
      self.osparams = {}
1236
    UpgradeBeParams(self.beparams)
1237
    if self.disks_active is None:
1238
      self.disks_active = self.admin_state == constants.ADMINST_UP
1239

    
1240

    
1241
class OS(ConfigObject):
1242
  """Config object representing an operating system.
1243

1244
  @type supported_parameters: list
1245
  @ivar supported_parameters: a list of tuples, name and description,
1246
      containing the supported parameters by this OS
1247

1248
  @type VARIANT_DELIM: string
1249
  @cvar VARIANT_DELIM: the variant delimiter
1250

1251
  """
1252
  __slots__ = [
1253
    "name",
1254
    "path",
1255
    "api_versions",
1256
    "create_script",
1257
    "export_script",
1258
    "import_script",
1259
    "rename_script",
1260
    "verify_script",
1261
    "supported_variants",
1262
    "supported_parameters",
1263
    ]
1264

    
1265
  VARIANT_DELIM = "+"
1266

    
1267
  @classmethod
1268
  def SplitNameVariant(cls, name):
1269
    """Splits the name into the proper name and variant.
1270

1271
    @param name: the OS (unprocessed) name
1272
    @rtype: list
1273
    @return: a list of two elements; if the original name didn't
1274
        contain a variant, it's returned as an empty string
1275

1276
    """
1277
    nv = name.split(cls.VARIANT_DELIM, 1)
1278
    if len(nv) == 1:
1279
      nv.append("")
1280
    return nv
1281

    
1282
  @classmethod
1283
  def GetName(cls, name):
1284
    """Returns the proper name of the os (without the variant).
1285

1286
    @param name: the OS (unprocessed) name
1287

1288
    """
1289
    return cls.SplitNameVariant(name)[0]
1290

    
1291
  @classmethod
1292
  def GetVariant(cls, name):
1293
    """Returns the variant the os (without the base name).
1294

1295
    @param name: the OS (unprocessed) name
1296

1297
    """
1298
    return cls.SplitNameVariant(name)[1]
1299

    
1300

    
1301
class ExtStorage(ConfigObject):
1302
  """Config object representing an External Storage Provider.
1303

1304
  """
1305
  __slots__ = [
1306
    "name",
1307
    "path",
1308
    "create_script",
1309
    "remove_script",
1310
    "grow_script",
1311
    "attach_script",
1312
    "detach_script",
1313
    "setinfo_script",
1314
    "verify_script",
1315
    "supported_parameters",
1316
    ]
1317

    
1318

    
1319
class NodeHvState(ConfigObject):
1320
  """Hypvervisor state on a node.
1321

1322
  @ivar mem_total: Total amount of memory
1323
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1324
    available)
1325
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1326
    rounding
1327
  @ivar mem_inst: Memory used by instances living on node
1328
  @ivar cpu_total: Total node CPU core count
1329
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1330

1331
  """
1332
  __slots__ = [
1333
    "mem_total",
1334
    "mem_node",
1335
    "mem_hv",
1336
    "mem_inst",
1337
    "cpu_total",
1338
    "cpu_node",
1339
    ] + _TIMESTAMPS
1340

    
1341

    
1342
class NodeDiskState(ConfigObject):
1343
  """Disk state on a node.
1344

1345
  """
1346
  __slots__ = [
1347
    "total",
1348
    "reserved",
1349
    "overhead",
1350
    ] + _TIMESTAMPS
1351

    
1352

    
1353
class Node(TaggableObject):
1354
  """Config object representing a node.
1355

1356
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1357
  @ivar hv_state_static: Hypervisor state overriden by user
1358
  @ivar disk_state: Disk state (e.g. free space)
1359
  @ivar disk_state_static: Disk state overriden by user
1360

1361
  """
1362
  __slots__ = [
1363
    "name",
1364
    "primary_ip",
1365
    "secondary_ip",
1366
    "serial_no",
1367
    "master_candidate",
1368
    "offline",
1369
    "drained",
1370
    "group",
1371
    "master_capable",
1372
    "vm_capable",
1373
    "ndparams",
1374
    "powered",
1375
    "hv_state",
1376
    "hv_state_static",
1377
    "disk_state",
1378
    "disk_state_static",
1379
    ] + _TIMESTAMPS + _UUID
1380

    
1381
  def UpgradeConfig(self):
1382
    """Fill defaults for missing configuration values.
1383

1384
    """
1385
    # pylint: disable=E0203
1386
    # because these are "defined" via slots, not manually
1387
    if self.master_capable is None:
1388
      self.master_capable = True
1389

    
1390
    if self.vm_capable is None:
1391
      self.vm_capable = True
1392

    
1393
    if self.ndparams is None:
1394
      self.ndparams = {}
1395
    # And remove any global parameter
1396
    for key in constants.NDC_GLOBALS:
1397
      if key in self.ndparams:
1398
        logging.warning("Ignoring %s node parameter for node %s",
1399
                        key, self.name)
1400
        del self.ndparams[key]
1401

    
1402
    if self.powered is None:
1403
      self.powered = True
1404

    
1405
  def ToDict(self):
1406
    """Custom function for serializing.
1407

1408
    """
1409
    data = super(Node, self).ToDict()
1410

    
1411
    hv_state = data.get("hv_state", None)
1412
    if hv_state is not None:
1413
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1414

    
1415
    disk_state = data.get("disk_state", None)
1416
    if disk_state is not None:
1417
      data["disk_state"] = \
1418
        dict((key, outils.ContainerToDicts(value))
1419
             for (key, value) in disk_state.items())
1420

    
1421
    return data
1422

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

1427
    """
1428
    obj = super(Node, cls).FromDict(val)
1429

    
1430
    if obj.hv_state is not None:
1431
      obj.hv_state = \
1432
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1433

    
1434
    if obj.disk_state is not None:
1435
      obj.disk_state = \
1436
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1437
             for (key, value) in obj.disk_state.items())
1438

    
1439
    return obj
1440

    
1441

    
1442
class NodeGroup(TaggableObject):
1443
  """Config object representing a node group."""
1444
  __slots__ = [
1445
    "name",
1446
    "members",
1447
    "ndparams",
1448
    "diskparams",
1449
    "ipolicy",
1450
    "serial_no",
1451
    "hv_state_static",
1452
    "disk_state_static",
1453
    "alloc_policy",
1454
    "networks",
1455
    ] + _TIMESTAMPS + _UUID
1456

    
1457
  def ToDict(self):
1458
    """Custom function for nodegroup.
1459

1460
    This discards the members object, which gets recalculated and is only kept
1461
    in memory.
1462

1463
    """
1464
    mydict = super(NodeGroup, self).ToDict()
1465
    del mydict["members"]
1466
    return mydict
1467

    
1468
  @classmethod
1469
  def FromDict(cls, val):
1470
    """Custom function for nodegroup.
1471

1472
    The members slot is initialized to an empty list, upon deserialization.
1473

1474
    """
1475
    obj = super(NodeGroup, cls).FromDict(val)
1476
    obj.members = []
1477
    return obj
1478

    
1479
  def UpgradeConfig(self):
1480
    """Fill defaults for missing configuration values.
1481

1482
    """
1483
    if self.ndparams is None:
1484
      self.ndparams = {}
1485

    
1486
    if self.serial_no is None:
1487
      self.serial_no = 1
1488

    
1489
    if self.alloc_policy is None:
1490
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1491

    
1492
    # We only update mtime, and not ctime, since we would not be able
1493
    # to provide a correct value for creation time.
1494
    if self.mtime is None:
1495
      self.mtime = time.time()
1496

    
1497
    if self.diskparams is None:
1498
      self.diskparams = {}
1499
    if self.ipolicy is None:
1500
      self.ipolicy = MakeEmptyIPolicy()
1501

    
1502
    if self.networks is None:
1503
      self.networks = {}
1504

    
1505
  def FillND(self, node):
1506
    """Return filled out ndparams for L{objects.Node}
1507

1508
    @type node: L{objects.Node}
1509
    @param node: A Node object to fill
1510
    @return a copy of the node's ndparams with defaults filled
1511

1512
    """
1513
    return self.SimpleFillND(node.ndparams)
1514

    
1515
  def SimpleFillND(self, ndparams):
1516
    """Fill a given ndparams dict with defaults.
1517

1518
    @type ndparams: dict
1519
    @param ndparams: the dict to fill
1520
    @rtype: dict
1521
    @return: a copy of the passed in ndparams with missing keys filled
1522
        from the node group defaults
1523

1524
    """
1525
    return FillDict(self.ndparams, ndparams)
1526

    
1527

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

    
1573
  def UpgradeConfig(self):
1574
    """Fill defaults for missing configuration values.
1575

1576
    """
1577
    # pylint: disable=E0203
1578
    # because these are "defined" via slots, not manually
1579
    if self.hvparams is None:
1580
      self.hvparams = constants.HVC_DEFAULTS
1581
    else:
1582
      for hypervisor in self.hvparams:
1583
        self.hvparams[hypervisor] = FillDict(
1584
            constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1585

    
1586
    if self.os_hvp is None:
1587
      self.os_hvp = {}
1588

    
1589
    # osparams added before 2.2
1590
    if self.osparams is None:
1591
      self.osparams = {}
1592

    
1593
    self.ndparams = UpgradeNDParams(self.ndparams)
1594

    
1595
    self.beparams = UpgradeGroupedParams(self.beparams,
1596
                                         constants.BEC_DEFAULTS)
1597
    for beparams_group in self.beparams:
1598
      UpgradeBeParams(self.beparams[beparams_group])
1599

    
1600
    migrate_default_bridge = not self.nicparams
1601
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1602
                                          constants.NICC_DEFAULTS)
1603
    if migrate_default_bridge:
1604
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1605
        self.default_bridge
1606

    
1607
    if self.modify_etc_hosts is None:
1608
      self.modify_etc_hosts = True
1609

    
1610
    if self.modify_ssh_setup is None:
1611
      self.modify_ssh_setup = True
1612

    
1613
    # default_bridge is no longer used in 2.1. The slot is left there to
1614
    # support auto-upgrading. It can be removed once we decide to deprecate
1615
    # upgrading straight from 2.0.
1616
    if self.default_bridge is not None:
1617
      self.default_bridge = None
1618

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

    
1627
    # maintain_node_health added after 2.1.1
1628
    if self.maintain_node_health is None:
1629
      self.maintain_node_health = False
1630

    
1631
    if self.uid_pool is None:
1632
      self.uid_pool = []
1633

    
1634
    if self.default_iallocator is None:
1635
      self.default_iallocator = ""
1636

    
1637
    # reserved_lvs added before 2.2
1638
    if self.reserved_lvs is None:
1639
      self.reserved_lvs = []
1640

    
1641
    # hidden and blacklisted operating systems added before 2.2.1
1642
    if self.hidden_os is None:
1643
      self.hidden_os = []
1644

    
1645
    if self.blacklisted_os is None:
1646
      self.blacklisted_os = []
1647

    
1648
    # primary_ip_family added before 2.3
1649
    if self.primary_ip_family is None:
1650
      self.primary_ip_family = AF_INET
1651

    
1652
    if self.master_netmask is None:
1653
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1654
      self.master_netmask = ipcls.iplen
1655

    
1656
    if self.prealloc_wipe_disks is None:
1657
      self.prealloc_wipe_disks = False
1658

    
1659
    # shared_file_storage_dir added before 2.5
1660
    if self.shared_file_storage_dir is None:
1661
      self.shared_file_storage_dir = ""
1662

    
1663
    if self.use_external_mip_script is None:
1664
      self.use_external_mip_script = False
1665

    
1666
    if self.diskparams:
1667
      self.diskparams = UpgradeDiskParams(self.diskparams)
1668
    else:
1669
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1670

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

    
1686
  @property
1687
  def primary_hypervisor(self):
1688
    """The first hypervisor is the primary.
1689

1690
    Useful, for example, for L{Node}'s hv/disk state.
1691

1692
    """
1693
    return self.enabled_hypervisors[0]
1694

    
1695
  def ToDict(self):
1696
    """Custom function for cluster.
1697

1698
    """
1699
    mydict = super(Cluster, self).ToDict()
1700

    
1701
    if self.tcpudp_port_pool is None:
1702
      tcpudp_port_pool = []
1703
    else:
1704
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1705

    
1706
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1707

    
1708
    return mydict
1709

    
1710
  @classmethod
1711
  def FromDict(cls, val):
1712
    """Custom function for cluster.
1713

1714
    """
1715
    obj = super(Cluster, cls).FromDict(val)
1716

    
1717
    if obj.tcpudp_port_pool is None:
1718
      obj.tcpudp_port_pool = set()
1719
    elif not isinstance(obj.tcpudp_port_pool, set):
1720
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1721

    
1722
    return obj
1723

    
1724
  def SimpleFillDP(self, diskparams):
1725
    """Fill a given diskparams dict with cluster defaults.
1726

1727
    @param diskparams: The diskparams
1728
    @return: The defaults dict
1729

1730
    """
1731
    return FillDiskParams(self.diskparams, diskparams)
1732

    
1733
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1734
    """Get the default hypervisor parameters for the cluster.
1735

1736
    @param hypervisor: the hypervisor name
1737
    @param os_name: if specified, we'll also update the defaults for this OS
1738
    @param skip_keys: if passed, list of keys not to use
1739
    @return: the defaults dict
1740

1741
    """
1742
    if skip_keys is None:
1743
      skip_keys = []
1744

    
1745
    fill_stack = [self.hvparams.get(hypervisor, {})]
1746
    if os_name is not None:
1747
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1748
      fill_stack.append(os_hvp)
1749

    
1750
    ret_dict = {}
1751
    for o_dict in fill_stack:
1752
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1753

    
1754
    return ret_dict
1755

    
1756
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1757
    """Fill a given hvparams dict with cluster defaults.
1758

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

1770
    """
1771
    if skip_globals:
1772
      skip_keys = constants.HVC_GLOBALS
1773
    else:
1774
      skip_keys = []
1775

    
1776
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1777
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1778

    
1779
  def FillHV(self, instance, skip_globals=False):
1780
    """Fill an instance's hvparams dict with cluster defaults.
1781

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

1791
    """
1792
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1793
                             instance.hvparams, skip_globals)
1794

    
1795
  def SimpleFillBE(self, beparams):
1796
    """Fill a given beparams dict with cluster defaults.
1797

1798
    @type beparams: dict
1799
    @param beparams: the dict to fill
1800
    @rtype: dict
1801
    @return: a copy of the passed in beparams with missing keys filled
1802
        from the cluster defaults
1803

1804
    """
1805
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1806

    
1807
  def FillBE(self, instance):
1808
    """Fill an instance's beparams dict with cluster defaults.
1809

1810
    @type instance: L{objects.Instance}
1811
    @param instance: the instance parameter to fill
1812
    @rtype: dict
1813
    @return: a copy of the instance's beparams with missing keys filled from
1814
        the cluster defaults
1815

1816
    """
1817
    return self.SimpleFillBE(instance.beparams)
1818

    
1819
  def SimpleFillNIC(self, nicparams):
1820
    """Fill a given nicparams dict with cluster defaults.
1821

1822
    @type nicparams: dict
1823
    @param nicparams: the dict to fill
1824
    @rtype: dict
1825
    @return: a copy of the passed in nicparams with missing keys filled
1826
        from the cluster defaults
1827

1828
    """
1829
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1830

    
1831
  def SimpleFillOS(self, os_name, os_params):
1832
    """Fill an instance's osparams dict with cluster defaults.
1833

1834
    @type os_name: string
1835
    @param os_name: the OS name to use
1836
    @type os_params: dict
1837
    @param os_params: the dict to fill with default values
1838
    @rtype: dict
1839
    @return: a copy of the instance's osparams with missing keys filled from
1840
        the cluster defaults
1841

1842
    """
1843
    name_only = os_name.split("+", 1)[0]
1844
    # base OS
1845
    result = self.osparams.get(name_only, {})
1846
    # OS with variant
1847
    result = FillDict(result, self.osparams.get(os_name, {}))
1848
    # specified params
1849
    return FillDict(result, os_params)
1850

    
1851
  @staticmethod
1852
  def SimpleFillHvState(hv_state):
1853
    """Fill an hv_state sub dict with cluster defaults.
1854

1855
    """
1856
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1857

    
1858
  @staticmethod
1859
  def SimpleFillDiskState(disk_state):
1860
    """Fill an disk_state sub dict with cluster defaults.
1861

1862
    """
1863
    return FillDict(constants.DS_DEFAULTS, disk_state)
1864

    
1865
  def FillND(self, node, nodegroup):
1866
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1867

1868
    @type node: L{objects.Node}
1869
    @param node: A Node object to fill
1870
    @type nodegroup: L{objects.NodeGroup}
1871
    @param nodegroup: A Node object to fill
1872
    @return a copy of the node's ndparams with defaults filled
1873

1874
    """
1875
    return self.SimpleFillND(nodegroup.FillND(node))
1876

    
1877
  def SimpleFillND(self, ndparams):
1878
    """Fill a given ndparams dict with defaults.
1879

1880
    @type ndparams: dict
1881
    @param ndparams: the dict to fill
1882
    @rtype: dict
1883
    @return: a copy of the passed in ndparams with missing keys filled
1884
        from the cluster defaults
1885

1886
    """
1887
    return FillDict(self.ndparams, ndparams)
1888

    
1889
  def SimpleFillIPolicy(self, ipolicy):
1890
    """ Fill instance policy dict with defaults.
1891

1892
    @type ipolicy: dict
1893
    @param ipolicy: the dict to fill
1894
    @rtype: dict
1895
    @return: a copy of passed ipolicy with missing keys filled from
1896
      the cluster defaults
1897

1898
    """
1899
    return FillIPolicy(self.ipolicy, ipolicy)
1900

    
1901
  def IsDiskTemplateEnabled(self, disk_template):
1902
    """Checks if a particular disk template is enabled.
1903

1904
    """
1905
    return utils.storage.IsDiskTemplateEnabled(
1906
        disk_template, self.enabled_disk_templates)
1907

    
1908
  def IsFileStorageEnabled(self):
1909
    """Checks if file storage is enabled.
1910

1911
    """
1912
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1913

    
1914
  def IsSharedFileStorageEnabled(self):
1915
    """Checks if shared file storage is enabled.
1916

1917
    """
1918
    return utils.storage.IsSharedFileStorageEnabled(
1919
        self.enabled_disk_templates)
1920

    
1921

    
1922
class BlockDevStatus(ConfigObject):
1923
  """Config object representing the status of a block device."""
1924
  __slots__ = [
1925
    "dev_path",
1926
    "major",
1927
    "minor",
1928
    "sync_percent",
1929
    "estimated_time",
1930
    "is_degraded",
1931
    "ldisk_status",
1932
    ]
1933

    
1934

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

    
1949

    
1950
class ImportExportOptions(ConfigObject):
1951
  """Options for import/export daemon
1952

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

1960
  """
1961
  __slots__ = [
1962
    "key_name",
1963
    "ca_pem",
1964
    "compress",
1965
    "magic",
1966
    "ipv6",
1967
    "connect_timeout",
1968
    ]
1969

    
1970

    
1971
class ConfdRequest(ConfigObject):
1972
  """Object holding a confd request.
1973

1974
  @ivar protocol: confd protocol version
1975
  @ivar type: confd query type
1976
  @ivar query: query request
1977
  @ivar rsalt: requested reply salt
1978

1979
  """
1980
  __slots__ = [
1981
    "protocol",
1982
    "type",
1983
    "query",
1984
    "rsalt",
1985
    ]
1986

    
1987

    
1988
class ConfdReply(ConfigObject):
1989
  """Object holding a confd reply.
1990

1991
  @ivar protocol: confd protocol version
1992
  @ivar status: reply status code (ok, error)
1993
  @ivar answer: confd query reply
1994
  @ivar serial: configuration serial number
1995

1996
  """
1997
  __slots__ = [
1998
    "protocol",
1999
    "status",
2000
    "answer",
2001
    "serial",
2002
    ]
2003

    
2004

    
2005
class QueryFieldDefinition(ConfigObject):
2006
  """Object holding a query field definition.
2007

2008
  @ivar name: Field name
2009
  @ivar title: Human-readable title
2010
  @ivar kind: Field type
2011
  @ivar doc: Human-readable description
2012

2013
  """
2014
  __slots__ = [
2015
    "name",
2016
    "title",
2017
    "kind",
2018
    "doc",
2019
    ]
2020

    
2021

    
2022
class _QueryResponseBase(ConfigObject):
2023
  __slots__ = [
2024
    "fields",
2025
    ]
2026

    
2027
  def ToDict(self):
2028
    """Custom function for serializing.
2029

2030
    """
2031
    mydict = super(_QueryResponseBase, self).ToDict()
2032
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2033
    return mydict
2034

    
2035
  @classmethod
2036
  def FromDict(cls, val):
2037
    """Custom function for de-serializing.
2038

2039
    """
2040
    obj = super(_QueryResponseBase, cls).FromDict(val)
2041
    obj.fields = \
2042
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2043
    return obj
2044

    
2045

    
2046
class QueryResponse(_QueryResponseBase):
2047
  """Object holding the response to a query.
2048

2049
  @ivar fields: List of L{QueryFieldDefinition} objects
2050
  @ivar data: Requested data
2051

2052
  """
2053
  __slots__ = [
2054
    "data",
2055
    ]
2056

    
2057

    
2058
class QueryFieldsRequest(ConfigObject):
2059
  """Object holding a request for querying available fields.
2060

2061
  """
2062
  __slots__ = [
2063
    "what",
2064
    "fields",
2065
    ]
2066

    
2067

    
2068
class QueryFieldsResponse(_QueryResponseBase):
2069
  """Object holding the response to a query for fields.
2070

2071
  @ivar fields: List of L{QueryFieldDefinition} objects
2072

2073
  """
2074
  __slots__ = []
2075

    
2076

    
2077
class MigrationStatus(ConfigObject):
2078
  """Object holding the status of a migration.
2079

2080
  """
2081
  __slots__ = [
2082
    "status",
2083
    "transferred_ram",
2084
    "total_ram",
2085
    ]
2086

    
2087

    
2088
class InstanceConsole(ConfigObject):
2089
  """Object describing how to access the console of an instance.
2090

2091
  """
2092
  __slots__ = [
2093
    "instance",
2094
    "kind",
2095
    "message",
2096
    "host",
2097
    "port",
2098
    "user",
2099
    "command",
2100
    "display",
2101
    ]
2102

    
2103
  def Validate(self):
2104
    """Validates contents of this object.
2105

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

    
2126

    
2127
class Network(TaggableObject):
2128
  """Object representing a network definition for ganeti.
2129

2130
  """
2131
  __slots__ = [
2132
    "name",
2133
    "serial_no",
2134
    "mac_prefix",
2135
    "network",
2136
    "network6",
2137
    "gateway",
2138
    "gateway6",
2139
    "reservations",
2140
    "ext_reservations",
2141
    ] + _TIMESTAMPS + _UUID
2142

    
2143
  def HooksDict(self, prefix=""):
2144
    """Export a dictionary used by hooks with a network's information.
2145

2146
    @type prefix: String
2147
    @param prefix: Prefix to prepend to the dict entries
2148

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

    
2166
    return result
2167

    
2168
  @classmethod
2169
  def FromDict(cls, val):
2170
    """Custom function for networks.
2171

2172
    Remove deprecated network_type and family.
2173

2174
    """
2175
    if "network_type" in val:
2176
      del val["network_type"]
2177
    if "family" in val:
2178
      del val["family"]
2179
    obj = super(Network, cls).FromDict(val)
2180
    return obj
2181

    
2182

    
2183
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2184
  """Simple wrapper over ConfigParse that allows serialization.
2185

2186
  This class is basically ConfigParser.SafeConfigParser with two
2187
  additional methods that allow it to serialize/unserialize to/from a
2188
  buffer.
2189

2190
  """
2191
  def Dumps(self):
2192
    """Dump this instance and return the string representation."""
2193
    buf = StringIO()
2194
    self.write(buf)
2195
    return buf.getvalue()
2196

    
2197
  @classmethod
2198
  def Loads(cls, data):
2199
    """Load data from a string."""
2200
    buf = StringIO(data)
2201
    cfp = cls()
2202
    cfp.readfp(buf)
2203
    return cfp
2204

    
2205

    
2206
class LvmPvInfo(ConfigObject):
2207
  """Information about an LVM physical volume (PV).
2208

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

    
2231
  def IsEmpty(self):
2232
    """Is this PV empty?
2233

2234
    """
2235
    return self.size <= (self.free + 1)
2236

    
2237
  def IsAllocatable(self):
2238
    """Is this PV allocatable?
2239

2240
    """
2241
    return ("a" in self.attributes)