Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 4a67e386

History | View | Annotate | Download (65.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 __eq__(self, other):
270
    """Implement __eq__ for ConfigObjects."""
271
    return isinstance(other, self.__class__) and self.ToDict() == other.ToDict()
272

    
273
  def UpgradeConfig(self):
274
    """Fill defaults for missing configuration values.
275

276
    This method will be called at configuration load time, and its
277
    implementation will be object dependent.
278

279
    """
280
    pass
281

    
282

    
283
class TaggableObject(ConfigObject):
284
  """An generic class supporting tags.
285

286
  """
287
  __slots__ = ["tags"]
288
  VALID_TAG_RE = re.compile(r"^[\w.+*/:@-]+$")
289

    
290
  @classmethod
291
  def ValidateTag(cls, tag):
292
    """Check if a tag is valid.
293

294
    If the tag is invalid, an errors.TagError will be raised. The
295
    function has no return value.
296

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

    
308
  def GetTags(self):
309
    """Return the tags list.
310

311
    """
312
    tags = getattr(self, "tags", None)
313
    if tags is None:
314
      tags = self.tags = set()
315
    return tags
316

    
317
  def AddTag(self, tag):
318
    """Add a new tag.
319

320
    """
321
    self.ValidateTag(tag)
322
    tags = self.GetTags()
323
    if len(tags) >= constants.MAX_TAGS_PER_OBJ:
324
      raise errors.TagError("Too many tags")
325
    self.GetTags().add(tag)
326

    
327
  def RemoveTag(self, tag):
328
    """Remove a tag.
329

330
    """
331
    self.ValidateTag(tag)
332
    tags = self.GetTags()
333
    try:
334
      tags.remove(tag)
335
    except KeyError:
336
      raise errors.TagError("Tag not found")
337

    
338
  def ToDict(self):
339
    """Taggable-object-specific conversion to standard python types.
340

341
    This replaces the tags set with a list.
342

343
    """
344
    bo = super(TaggableObject, self).ToDict()
345

    
346
    tags = bo.get("tags", None)
347
    if isinstance(tags, set):
348
      bo["tags"] = list(tags)
349
    return bo
350

    
351
  @classmethod
352
  def FromDict(cls, val):
353
    """Custom function for instances.
354

355
    """
356
    obj = super(TaggableObject, cls).FromDict(val)
357
    if hasattr(obj, "tags") and isinstance(obj.tags, list):
358
      obj.tags = set(obj.tags)
359
    return obj
360

    
361

    
362
class MasterNetworkParameters(ConfigObject):
363
  """Network configuration parameters for the master
364

365
  @ivar uuid: master nodes UUID
366
  @ivar ip: master IP
367
  @ivar netmask: master netmask
368
  @ivar netdev: master network device
369
  @ivar ip_family: master IP family
370

371
  """
372
  __slots__ = [
373
    "uuid",
374
    "ip",
375
    "netmask",
376
    "netdev",
377
    "ip_family",
378
    ]
379

    
380

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

    
393
  def ToDict(self):
394
    """Custom function for top-level config data.
395

396
    This just replaces the list of instances, nodes and the cluster
397
    with standard python types.
398

399
    """
400
    mydict = super(ConfigData, self).ToDict()
401
    mydict["cluster"] = mydict["cluster"].ToDict()
402
    for key in "nodes", "instances", "nodegroups", "networks":
403
      mydict[key] = outils.ContainerToDicts(mydict[key])
404

    
405
    return mydict
406

    
407
  @classmethod
408
  def FromDict(cls, val):
409
    """Custom function for top-level config data
410

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

    
422
  def HasAnyDiskOfType(self, dev_type):
423
    """Check if in there is at disk of the given type in the configuration.
424

425
    @type dev_type: L{constants.DTS_BLOCK}
426
    @param dev_type: the type to look for
427
    @rtype: boolean
428
    @return: boolean indicating if a disk of the given type was found or not
429

430
    """
431
    for instance in self.instances.values():
432
      for disk in instance.disks:
433
        if disk.IsBasedOnDiskType(dev_type):
434
          return True
435
    return False
436

    
437
  def UpgradeConfig(self):
438
    """Fill defaults for missing configuration values.
439

440
    """
441
    self.cluster.UpgradeConfig()
442
    for node in self.nodes.values():
443
      node.UpgradeConfig()
444
    for instance in self.instances.values():
445
      instance.UpgradeConfig()
446
    self._UpgradeEnabledDiskTemplates()
447
    if self.nodegroups is None:
448
      self.nodegroups = {}
449
    for nodegroup in self.nodegroups.values():
450
      nodegroup.UpgradeConfig()
451
      InstancePolicy.UpgradeDiskTemplates(
452
        nodegroup.ipolicy, self.cluster.enabled_disk_templates)
453
    if self.cluster.drbd_usermode_helper is None:
454
      if self.cluster.IsDiskTemplateEnabled(constants.DT_DRBD8):
455
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
456
    if self.networks is None:
457
      self.networks = {}
458
    for network in self.networks.values():
459
      network.UpgradeConfig()
460

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

465
    """
466
    if not self.cluster.enabled_disk_templates:
467
      template_set = \
468
        set([inst.disk_template for inst in self.instances.values()])
469
      # Add drbd and plain, if lvm is enabled (by specifying a volume group)
470
      if self.cluster.volume_group_name:
471
        template_set.add(constants.DT_DRBD8)
472
        template_set.add(constants.DT_PLAIN)
473
      # Set enabled_disk_templates to the inferred disk templates. Order them
474
      # according to a preference list that is based on Ganeti's history of
475
      # supported disk templates.
476
      self.cluster.enabled_disk_templates = []
477
      for preferred_template in constants.DISK_TEMPLATE_PREFERENCE:
478
        if preferred_template in template_set:
479
          self.cluster.enabled_disk_templates.append(preferred_template)
480
          template_set.remove(preferred_template)
481
      self.cluster.enabled_disk_templates.extend(list(template_set))
482
    InstancePolicy.UpgradeDiskTemplates(
483
      self.cluster.ipolicy, self.cluster.enabled_disk_templates)
484

    
485

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

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

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

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

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

    
509

    
510
class Disk(ConfigObject):
511
  """Config object representing a block device."""
512
  __slots__ = (["name", "dev_type", "logical_id", "children", "iv_name",
513
                "size", "mode", "params", "spindles", "pci"] + _UUID +
514
               # dynamic_params is special. It depends on the node this instance
515
               # is sent to, and should not be persisted.
516
               ["dynamic_params"])
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.DT_DRBD8, constants.DT_PLAIN)
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.DT_DRBD8, constants.DT_PLAIN)
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.DT_PLAIN,)
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.DT_PLAIN:
542
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
543
    elif self.dev_type == constants.DT_BLOCK:
544
      return self.logical_id[1]
545
    elif self.dev_type == constants.DT_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.DT_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.DTS_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.DT_PLAIN, constants.DT_FILE,
590
                         constants.DT_BLOCK, constants.DT_RBD,
591
                         constants.DT_EXT, constants.DT_SHARED_FILE]:
592
      result = [node_uuid]
593
    elif self.dev_type in constants.DTS_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.DT_PLAIN:
648
      return {self.logical_id[0]: amount}
649
    elif self.dev_type == constants.DT_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.DT_PLAIN, constants.DT_FILE,
667
                         constants.DT_RBD, constants.DT_EXT,
668
                         constants.DT_SHARED_FILE):
669
      self.size += amount
670
    elif self.dev_type == constants.DT_DRBD8:
671
      if self.children:
672
        self.children[0].RecordGrow(amount)
673
      self.size += amount
674
    else:
675
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
676
                                   " disk type %s" % self.dev_type)
677

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

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

    
688
    if size is not None:
689
      self.size = size
690
    if mode is not None:
691
      self.mode = mode
692
    if spindles is not None:
693
      self.spindles = spindles
694

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

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

    
704
  def UpdateDynamicDiskParams(self, target_node_uuid, nodes_ip):
705
    """Updates the dynamic disk params for the given node.
706

707
    This is mainly used for drbd, which needs ip/port configuration.
708

709
    Arguments:
710
      - target_node_uuid: the node UUID we wish to configure for
711
      - nodes_ip: a mapping of node name to ip
712

713
    The target_node must exist in nodes_ip, and should be one of the
714
    nodes in the logical ID if this device is a DRBD device.
715

716
    """
717
    if self.children:
718
      for child in self.children:
719
        child.UpdateDynamicDiskParams(target_node_uuid, nodes_ip)
720

    
721
    dyn_disk_params = {}
722
    if self.logical_id is not None and self.dev_type in constants.DTS_DRBD:
723
      pnode_uuid, snode_uuid, _, pminor, sminor, _ = self.logical_id
724
      if target_node_uuid not in (pnode_uuid, snode_uuid):
725
        # disk object is being sent to neither the primary nor the secondary
726
        # node. reset the dynamic parameters, the target node is not
727
        # supposed to use them.
728
        self.dynamic_params = dyn_disk_params
729
        return
730

    
731
      pnode_ip = nodes_ip.get(pnode_uuid, None)
732
      snode_ip = nodes_ip.get(snode_uuid, None)
733
      if pnode_ip is None or snode_ip is None:
734
        raise errors.ConfigurationError("Can't find primary or secondary node"
735
                                        " for %s" % str(self))
736
      if pnode_uuid == target_node_uuid:
737
        dyn_disk_params[constants.DDP_LOCAL_IP] = pnode_ip
738
        dyn_disk_params[constants.DDP_REMOTE_IP] = snode_ip
739
        dyn_disk_params[constants.DDP_LOCAL_MINOR] = pminor
740
        dyn_disk_params[constants.DDP_REMOTE_MINOR] = sminor
741
      else: # it must be secondary, we tested above
742
        dyn_disk_params[constants.DDP_LOCAL_IP] = snode_ip
743
        dyn_disk_params[constants.DDP_REMOTE_IP] = pnode_ip
744
        dyn_disk_params[constants.DDP_LOCAL_MINOR] = sminor
745
        dyn_disk_params[constants.DDP_REMOTE_MINOR] = pminor
746

    
747
    self.dynamic_params = dyn_disk_params
748

    
749
  # pylint: disable=W0221
750
  def ToDict(self, include_dynamic_params=False):
751
    """Disk-specific conversion to standard python types.
752

753
    This replaces the children lists of objects with lists of
754
    standard python types.
755

756
    """
757
    bo = super(Disk, self).ToDict()
758
    if not include_dynamic_params and "dynamic_params" in bo:
759
      del bo["dynamic_params"]
760

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

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

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

    
783
  def __str__(self):
784
    """Custom str() formatter for disks.
785

786
    """
787
    if self.dev_type == constants.DT_PLAIN:
788
      val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
789
    elif self.dev_type in constants.DTS_DRBD:
790
      node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
791
      val = "<DRBD8("
792

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

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

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

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

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

    
831
    # FIXME: Make this configurable in Ganeti 2.7
832
    # Params should be an empty dict that gets filled any time needed
833
    # In case of ext template we allow arbitrary params that should not
834
    # be overrided during a config reload/upgrade.
835
    if not self.params or not isinstance(self.params, dict):
836
      self.params = {}
837

    
838
    # add here config upgrade for this disk
839

    
840
    # map of legacy device types (mapping differing LD constants to new
841
    # DT constants)
842
    LEG_DEV_TYPE_MAP = {"lvm": constants.DT_PLAIN, "drbd8": constants.DT_DRBD8}
843
    if self.dev_type in LEG_DEV_TYPE_MAP:
844
      self.dev_type = LEG_DEV_TYPE_MAP[self.dev_type]
845

    
846
  @staticmethod
847
  def ComputeLDParams(disk_template, disk_params):
848
    """Computes Logical Disk parameters from Disk Template parameters.
849

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

859
    """
860
    if disk_template not in constants.DISK_TEMPLATES:
861
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
862

    
863
    assert disk_template in disk_params
864

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

    
884
      # data LV
885
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
886
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
887
        }))
888

    
889
      # metadata LV
890
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
891
        constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
892
        }))
893

    
894
    elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
895
      result.append(constants.DISK_LD_DEFAULTS[disk_template])
896

    
897
    elif disk_template == constants.DT_PLAIN:
898
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
899
        constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
900
        }))
901

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

    
905
    elif disk_template == constants.DT_RBD:
906
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_RBD], {
907
        constants.LDP_POOL: dt_params[constants.RBD_POOL],
908
        constants.LDP_ACCESS: dt_params[constants.RBD_ACCESS],
909
        }))
910

    
911
    elif disk_template == constants.DT_EXT:
912
      result.append(constants.DISK_LD_DEFAULTS[constants.DT_EXT])
913

    
914
    return result
915

    
916

    
917
class InstancePolicy(ConfigObject):
918
  """Config object representing instance policy limits dictionary.
919

920
  Note that this object is not actually used in the config, it's just
921
  used as a placeholder for a few functions.
922

923
  """
924
  @classmethod
925
  def UpgradeDiskTemplates(cls, ipolicy, enabled_disk_templates):
926
    """Upgrades the ipolicy configuration."""
927
    if constants.IPOLICY_DTS in ipolicy:
928
      if not set(ipolicy[constants.IPOLICY_DTS]).issubset(
929
        set(enabled_disk_templates)):
930
        ipolicy[constants.IPOLICY_DTS] = list(
931
          set(ipolicy[constants.IPOLICY_DTS]) & set(enabled_disk_templates))
932

    
933
  @classmethod
934
  def CheckParameterSyntax(cls, ipolicy, check_std):
935
    """ Check the instance policy for validity.
936

937
    @type ipolicy: dict
938
    @param ipolicy: dictionary with min/max/std specs and policies
939
    @type check_std: bool
940
    @param check_std: Whether to check std value or just assume compliance
941
    @raise errors.ConfigurationError: when the policy is not legal
942

943
    """
944
    InstancePolicy.CheckISpecSyntax(ipolicy, check_std)
945
    if constants.IPOLICY_DTS in ipolicy:
946
      InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
947
    for key in constants.IPOLICY_PARAMETERS:
948
      if key in ipolicy:
949
        InstancePolicy.CheckParameter(key, ipolicy[key])
950
    wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
951
    if wrong_keys:
952
      raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
953
                                      utils.CommaJoin(wrong_keys))
954

    
955
  @classmethod
956
  def _CheckIncompleteSpec(cls, spec, keyname):
957
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
958
    if missing_params:
959
      msg = ("Missing instance specs parameters for %s: %s" %
960
             (keyname, utils.CommaJoin(missing_params)))
961
      raise errors.ConfigurationError(msg)
962

    
963
  @classmethod
964
  def CheckISpecSyntax(cls, ipolicy, check_std):
965
    """Check the instance policy specs for validity.
966

967
    @type ipolicy: dict
968
    @param ipolicy: dictionary with min/max/std specs
969
    @type check_std: bool
970
    @param check_std: Whether to check std value or just assume compliance
971
    @raise errors.ConfigurationError: when specs are not valid
972

973
    """
974
    if constants.ISPECS_MINMAX not in ipolicy:
975
      # Nothing to check
976
      return
977

    
978
    if check_std and constants.ISPECS_STD not in ipolicy:
979
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
980
      raise errors.ConfigurationError(msg)
981
    stdspec = ipolicy.get(constants.ISPECS_STD)
982
    if check_std:
983
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
984

    
985
    if not ipolicy[constants.ISPECS_MINMAX]:
986
      raise errors.ConfigurationError("Empty minmax specifications")
987
    std_is_good = False
988
    for minmaxspecs in ipolicy[constants.ISPECS_MINMAX]:
989
      missing = constants.ISPECS_MINMAX_KEYS - frozenset(minmaxspecs.keys())
990
      if missing:
991
        msg = "Missing instance specification: %s" % utils.CommaJoin(missing)
992
        raise errors.ConfigurationError(msg)
993
      for (key, spec) in minmaxspecs.items():
994
        InstancePolicy._CheckIncompleteSpec(spec, key)
995

    
996
      spec_std_ok = True
997
      for param in constants.ISPECS_PARAMETERS:
998
        par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
999
                                                           param, check_std)
1000
        spec_std_ok = spec_std_ok and par_std_ok
1001
      std_is_good = std_is_good or spec_std_ok
1002
    if not std_is_good:
1003
      raise errors.ConfigurationError("Invalid std specifications")
1004

    
1005
  @classmethod
1006
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
1007
    """Check the instance policy specs for validity on a given key.
1008

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

1012
    @type minmaxspecs: dict
1013
    @param minmaxspecs: dictionary with min and max instance spec
1014
    @type stdspec: dict
1015
    @param stdspec: dictionary with standard instance spec
1016
    @type name: string
1017
    @param name: what are the limits for
1018
    @type check_std: bool
1019
    @param check_std: Whether to check std value or just assume compliance
1020
    @rtype: bool
1021
    @return: C{True} when specs are valid, C{False} when standard spec for the
1022
        given name is not valid
1023
    @raise errors.ConfigurationError: when min/max specs for the given name
1024
        are not valid
1025

1026
    """
1027
    minspec = minmaxspecs[constants.ISPECS_MIN]
1028
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1029
    min_v = minspec[name]
1030
    max_v = maxspec[name]
1031

    
1032
    if min_v > max_v:
1033
      err = ("Invalid specification of min/max values for %s: %s/%s" %
1034
             (name, min_v, max_v))
1035
      raise errors.ConfigurationError(err)
1036
    elif check_std:
1037
      std_v = stdspec.get(name, min_v)
1038
      return std_v >= min_v and std_v <= max_v
1039
    else:
1040
      return True
1041

    
1042
  @classmethod
1043
  def CheckDiskTemplates(cls, disk_templates):
1044
    """Checks the disk templates for validity.
1045

1046
    """
1047
    if not disk_templates:
1048
      raise errors.ConfigurationError("Instance policy must contain" +
1049
                                      " at least one disk template")
1050
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1051
    if wrong:
1052
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1053
                                      utils.CommaJoin(wrong))
1054

    
1055
  @classmethod
1056
  def CheckParameter(cls, key, value):
1057
    """Checks a parameter.
1058

1059
    Currently we expect all parameters to be float values.
1060

1061
    """
1062
    try:
1063
      float(value)
1064
    except (TypeError, ValueError), err:
1065
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1066
                                      " '%s', error: %s" % (key, value, err))
1067

    
1068

    
1069
class Instance(TaggableObject):
1070
  """Config object representing an instance."""
1071
  __slots__ = [
1072
    "name",
1073
    "primary_node",
1074
    "os",
1075
    "hypervisor",
1076
    "hvparams",
1077
    "beparams",
1078
    "osparams",
1079
    "admin_state",
1080
    "nics",
1081
    "disks",
1082
    "disk_template",
1083
    "disks_active",
1084
    "network_port",
1085
    "serial_no",
1086
    ] + _TIMESTAMPS + _UUID
1087

    
1088
  def _ComputeSecondaryNodes(self):
1089
    """Compute the list of secondary nodes.
1090

1091
    This is a simple wrapper over _ComputeAllNodes.
1092

1093
    """
1094
    all_nodes = set(self._ComputeAllNodes())
1095
    all_nodes.discard(self.primary_node)
1096
    return tuple(all_nodes)
1097

    
1098
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1099
                             "List of names of secondary nodes")
1100

    
1101
  def _ComputeAllNodes(self):
1102
    """Compute the list of all nodes.
1103

1104
    Since the data is already there (in the drbd disks), keeping it as
1105
    a separate normal attribute is redundant and if not properly
1106
    synchronised can cause problems. Thus it's better to compute it
1107
    dynamically.
1108

1109
    """
1110
    def _Helper(nodes, device):
1111
      """Recursively computes nodes given a top device."""
1112
      if device.dev_type in constants.DTS_DRBD:
1113
        nodea, nodeb = device.logical_id[:2]
1114
        nodes.add(nodea)
1115
        nodes.add(nodeb)
1116
      if device.children:
1117
        for child in device.children:
1118
          _Helper(nodes, child)
1119

    
1120
    all_nodes = set()
1121
    all_nodes.add(self.primary_node)
1122
    for device in self.disks:
1123
      _Helper(all_nodes, device)
1124
    return tuple(all_nodes)
1125

    
1126
  all_nodes = property(_ComputeAllNodes, None, None,
1127
                       "List of names of all the nodes of the instance")
1128

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

1132
    This function figures out what logical volumes should belong on
1133
    which nodes, recursing through a device tree.
1134

1135
    @type lvmap: dict
1136
    @param lvmap: optional dictionary to receive the
1137
        'node' : ['lv', ...] data.
1138
    @type devs: list of L{Disk}
1139
    @param devs: disks to get the LV name for. If None, all disk of this
1140
        instance are used.
1141
    @type node_uuid: string
1142
    @param node_uuid: UUID of the node to get the LV names for. If None, the
1143
        primary node of this instance is used.
1144
    @return: None if lvmap arg is given, otherwise, a dictionary of
1145
        the form { 'node_uuid' : ['volume1', 'volume2', ...], ... };
1146
        volumeN is of the form "vg_name/lv_name", compatible with
1147
        GetVolumeList()
1148

1149
    """
1150
    if node_uuid is None:
1151
      node_uuid = self.primary_node
1152

    
1153
    if lvmap is None:
1154
      lvmap = {
1155
        node_uuid: [],
1156
        }
1157
      ret = lvmap
1158
    else:
1159
      if not node_uuid in lvmap:
1160
        lvmap[node_uuid] = []
1161
      ret = None
1162

    
1163
    if not devs:
1164
      devs = self.disks
1165

    
1166
    for dev in devs:
1167
      if dev.dev_type == constants.DT_PLAIN:
1168
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1169

    
1170
      elif dev.dev_type in constants.DTS_DRBD:
1171
        if dev.children:
1172
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1173
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1174

    
1175
      elif dev.children:
1176
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1177

    
1178
    return ret
1179

    
1180
  def FindDisk(self, idx):
1181
    """Find a disk given having a specified index.
1182

1183
    This is just a wrapper that does validation of the index.
1184

1185
    @type idx: int
1186
    @param idx: the disk index
1187
    @rtype: L{Disk}
1188
    @return: the corresponding disk
1189
    @raise errors.OpPrereqError: when the given index is not valid
1190

1191
    """
1192
    try:
1193
      idx = int(idx)
1194
      return self.disks[idx]
1195
    except (TypeError, ValueError), err:
1196
      raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1197
                                 errors.ECODE_INVAL)
1198
    except IndexError:
1199
      raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1200
                                 " 0 to %d" % (idx, len(self.disks) - 1),
1201
                                 errors.ECODE_INVAL)
1202

    
1203
  def ToDict(self):
1204
    """Instance-specific conversion to standard python types.
1205

1206
    This replaces the children lists of objects with lists of standard
1207
    python types.
1208

1209
    """
1210
    bo = super(Instance, self).ToDict()
1211

    
1212
    for attr in "nics", "disks":
1213
      alist = bo.get(attr, None)
1214
      if alist:
1215
        nlist = outils.ContainerToDicts(alist)
1216
      else:
1217
        nlist = []
1218
      bo[attr] = nlist
1219
    return bo
1220

    
1221
  @classmethod
1222
  def FromDict(cls, val):
1223
    """Custom function for instances.
1224

1225
    """
1226
    if "admin_state" not in val:
1227
      if val.get("admin_up", False):
1228
        val["admin_state"] = constants.ADMINST_UP
1229
      else:
1230
        val["admin_state"] = constants.ADMINST_DOWN
1231
    if "admin_up" in val:
1232
      del val["admin_up"]
1233
    obj = super(Instance, cls).FromDict(val)
1234
    obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1235
    obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1236
    return obj
1237

    
1238
  def UpgradeConfig(self):
1239
    """Fill defaults for missing configuration values.
1240

1241
    """
1242
    for nic in self.nics:
1243
      nic.UpgradeConfig()
1244
    for disk in self.disks:
1245
      disk.UpgradeConfig()
1246
    if self.hvparams:
1247
      for key in constants.HVC_GLOBALS:
1248
        try:
1249
          del self.hvparams[key]
1250
        except KeyError:
1251
          pass
1252
    if self.osparams is None:
1253
      self.osparams = {}
1254
    UpgradeBeParams(self.beparams)
1255
    if self.disks_active is None:
1256
      self.disks_active = self.admin_state == constants.ADMINST_UP
1257

    
1258

    
1259
class OS(ConfigObject):
1260
  """Config object representing an operating system.
1261

1262
  @type supported_parameters: list
1263
  @ivar supported_parameters: a list of tuples, name and description,
1264
      containing the supported parameters by this OS
1265

1266
  @type VARIANT_DELIM: string
1267
  @cvar VARIANT_DELIM: the variant delimiter
1268

1269
  """
1270
  __slots__ = [
1271
    "name",
1272
    "path",
1273
    "api_versions",
1274
    "create_script",
1275
    "export_script",
1276
    "import_script",
1277
    "rename_script",
1278
    "verify_script",
1279
    "supported_variants",
1280
    "supported_parameters",
1281
    ]
1282

    
1283
  VARIANT_DELIM = "+"
1284

    
1285
  @classmethod
1286
  def SplitNameVariant(cls, name):
1287
    """Splits the name into the proper name and variant.
1288

1289
    @param name: the OS (unprocessed) name
1290
    @rtype: list
1291
    @return: a list of two elements; if the original name didn't
1292
        contain a variant, it's returned as an empty string
1293

1294
    """
1295
    nv = name.split(cls.VARIANT_DELIM, 1)
1296
    if len(nv) == 1:
1297
      nv.append("")
1298
    return nv
1299

    
1300
  @classmethod
1301
  def GetName(cls, name):
1302
    """Returns the proper name of the os (without the variant).
1303

1304
    @param name: the OS (unprocessed) name
1305

1306
    """
1307
    return cls.SplitNameVariant(name)[0]
1308

    
1309
  @classmethod
1310
  def GetVariant(cls, name):
1311
    """Returns the variant the os (without the base name).
1312

1313
    @param name: the OS (unprocessed) name
1314

1315
    """
1316
    return cls.SplitNameVariant(name)[1]
1317

    
1318

    
1319
class ExtStorage(ConfigObject):
1320
  """Config object representing an External Storage Provider.
1321

1322
  """
1323
  __slots__ = [
1324
    "name",
1325
    "path",
1326
    "create_script",
1327
    "remove_script",
1328
    "grow_script",
1329
    "attach_script",
1330
    "detach_script",
1331
    "setinfo_script",
1332
    "verify_script",
1333
    "supported_parameters",
1334
    ]
1335

    
1336

    
1337
class NodeHvState(ConfigObject):
1338
  """Hypvervisor state on a node.
1339

1340
  @ivar mem_total: Total amount of memory
1341
  @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1342
    available)
1343
  @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1344
    rounding
1345
  @ivar mem_inst: Memory used by instances living on node
1346
  @ivar cpu_total: Total node CPU core count
1347
  @ivar cpu_node: Number of CPU cores reserved for the node itself
1348

1349
  """
1350
  __slots__ = [
1351
    "mem_total",
1352
    "mem_node",
1353
    "mem_hv",
1354
    "mem_inst",
1355
    "cpu_total",
1356
    "cpu_node",
1357
    ] + _TIMESTAMPS
1358

    
1359

    
1360
class NodeDiskState(ConfigObject):
1361
  """Disk state on a node.
1362

1363
  """
1364
  __slots__ = [
1365
    "total",
1366
    "reserved",
1367
    "overhead",
1368
    ] + _TIMESTAMPS
1369

    
1370

    
1371
class Node(TaggableObject):
1372
  """Config object representing a node.
1373

1374
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1375
  @ivar hv_state_static: Hypervisor state overriden by user
1376
  @ivar disk_state: Disk state (e.g. free space)
1377
  @ivar disk_state_static: Disk state overriden by user
1378

1379
  """
1380
  __slots__ = [
1381
    "name",
1382
    "primary_ip",
1383
    "secondary_ip",
1384
    "serial_no",
1385
    "master_candidate",
1386
    "offline",
1387
    "drained",
1388
    "group",
1389
    "master_capable",
1390
    "vm_capable",
1391
    "ndparams",
1392
    "powered",
1393
    "hv_state",
1394
    "hv_state_static",
1395
    "disk_state",
1396
    "disk_state_static",
1397
    ] + _TIMESTAMPS + _UUID
1398

    
1399
  def UpgradeConfig(self):
1400
    """Fill defaults for missing configuration values.
1401

1402
    """
1403
    # pylint: disable=E0203
1404
    # because these are "defined" via slots, not manually
1405
    if self.master_capable is None:
1406
      self.master_capable = True
1407

    
1408
    if self.vm_capable is None:
1409
      self.vm_capable = True
1410

    
1411
    if self.ndparams is None:
1412
      self.ndparams = {}
1413
    # And remove any global parameter
1414
    for key in constants.NDC_GLOBALS:
1415
      if key in self.ndparams:
1416
        logging.warning("Ignoring %s node parameter for node %s",
1417
                        key, self.name)
1418
        del self.ndparams[key]
1419

    
1420
    if self.powered is None:
1421
      self.powered = True
1422

    
1423
  def ToDict(self):
1424
    """Custom function for serializing.
1425

1426
    """
1427
    data = super(Node, self).ToDict()
1428

    
1429
    hv_state = data.get("hv_state", None)
1430
    if hv_state is not None:
1431
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1432

    
1433
    disk_state = data.get("disk_state", None)
1434
    if disk_state is not None:
1435
      data["disk_state"] = \
1436
        dict((key, outils.ContainerToDicts(value))
1437
             for (key, value) in disk_state.items())
1438

    
1439
    return data
1440

    
1441
  @classmethod
1442
  def FromDict(cls, val):
1443
    """Custom function for deserializing.
1444

1445
    """
1446
    obj = super(Node, cls).FromDict(val)
1447

    
1448
    if obj.hv_state is not None:
1449
      obj.hv_state = \
1450
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1451

    
1452
    if obj.disk_state is not None:
1453
      obj.disk_state = \
1454
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1455
             for (key, value) in obj.disk_state.items())
1456

    
1457
    return obj
1458

    
1459

    
1460
class NodeGroup(TaggableObject):
1461
  """Config object representing a node group."""
1462
  __slots__ = [
1463
    "name",
1464
    "members",
1465
    "ndparams",
1466
    "diskparams",
1467
    "ipolicy",
1468
    "serial_no",
1469
    "hv_state_static",
1470
    "disk_state_static",
1471
    "alloc_policy",
1472
    "networks",
1473
    ] + _TIMESTAMPS + _UUID
1474

    
1475
  def ToDict(self):
1476
    """Custom function for nodegroup.
1477

1478
    This discards the members object, which gets recalculated and is only kept
1479
    in memory.
1480

1481
    """
1482
    mydict = super(NodeGroup, self).ToDict()
1483
    del mydict["members"]
1484
    return mydict
1485

    
1486
  @classmethod
1487
  def FromDict(cls, val):
1488
    """Custom function for nodegroup.
1489

1490
    The members slot is initialized to an empty list, upon deserialization.
1491

1492
    """
1493
    obj = super(NodeGroup, cls).FromDict(val)
1494
    obj.members = []
1495
    return obj
1496

    
1497
  def UpgradeConfig(self):
1498
    """Fill defaults for missing configuration values.
1499

1500
    """
1501
    if self.ndparams is None:
1502
      self.ndparams = {}
1503

    
1504
    if self.serial_no is None:
1505
      self.serial_no = 1
1506

    
1507
    if self.alloc_policy is None:
1508
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1509

    
1510
    # We only update mtime, and not ctime, since we would not be able
1511
    # to provide a correct value for creation time.
1512
    if self.mtime is None:
1513
      self.mtime = time.time()
1514

    
1515
    if self.diskparams is None:
1516
      self.diskparams = {}
1517
    if self.ipolicy is None:
1518
      self.ipolicy = MakeEmptyIPolicy()
1519

    
1520
    if self.networks is None:
1521
      self.networks = {}
1522

    
1523
  def FillND(self, node):
1524
    """Return filled out ndparams for L{objects.Node}
1525

1526
    @type node: L{objects.Node}
1527
    @param node: A Node object to fill
1528
    @return a copy of the node's ndparams with defaults filled
1529

1530
    """
1531
    return self.SimpleFillND(node.ndparams)
1532

    
1533
  def SimpleFillND(self, ndparams):
1534
    """Fill a given ndparams dict with defaults.
1535

1536
    @type ndparams: dict
1537
    @param ndparams: the dict to fill
1538
    @rtype: dict
1539
    @return: a copy of the passed in ndparams with missing keys filled
1540
        from the node group defaults
1541

1542
    """
1543
    return FillDict(self.ndparams, ndparams)
1544

    
1545

    
1546
class Cluster(TaggableObject):
1547
  """Config object representing the cluster."""
1548
  __slots__ = [
1549
    "serial_no",
1550
    "rsahostkeypub",
1551
    "dsahostkeypub",
1552
    "highest_used_port",
1553
    "tcpudp_port_pool",
1554
    "mac_prefix",
1555
    "volume_group_name",
1556
    "reserved_lvs",
1557
    "drbd_usermode_helper",
1558
    "default_bridge",
1559
    "default_hypervisor",
1560
    "master_node",
1561
    "master_ip",
1562
    "master_netdev",
1563
    "master_netmask",
1564
    "use_external_mip_script",
1565
    "cluster_name",
1566
    "file_storage_dir",
1567
    "shared_file_storage_dir",
1568
    "enabled_hypervisors",
1569
    "hvparams",
1570
    "ipolicy",
1571
    "os_hvp",
1572
    "beparams",
1573
    "osparams",
1574
    "nicparams",
1575
    "ndparams",
1576
    "diskparams",
1577
    "candidate_pool_size",
1578
    "modify_etc_hosts",
1579
    "modify_ssh_setup",
1580
    "maintain_node_health",
1581
    "uid_pool",
1582
    "default_iallocator",
1583
    "hidden_os",
1584
    "blacklisted_os",
1585
    "primary_ip_family",
1586
    "prealloc_wipe_disks",
1587
    "hv_state_static",
1588
    "disk_state_static",
1589
    "enabled_disk_templates",
1590
    ] + _TIMESTAMPS + _UUID
1591

    
1592
  def UpgradeConfig(self):
1593
    """Fill defaults for missing configuration values.
1594

1595
    """
1596
    # pylint: disable=E0203
1597
    # because these are "defined" via slots, not manually
1598
    if self.hvparams is None:
1599
      self.hvparams = constants.HVC_DEFAULTS
1600
    else:
1601
      for hypervisor in self.hvparams:
1602
        self.hvparams[hypervisor] = FillDict(
1603
            constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1604

    
1605
    if self.os_hvp is None:
1606
      self.os_hvp = {}
1607

    
1608
    # osparams added before 2.2
1609
    if self.osparams is None:
1610
      self.osparams = {}
1611

    
1612
    self.ndparams = UpgradeNDParams(self.ndparams)
1613

    
1614
    self.beparams = UpgradeGroupedParams(self.beparams,
1615
                                         constants.BEC_DEFAULTS)
1616
    for beparams_group in self.beparams:
1617
      UpgradeBeParams(self.beparams[beparams_group])
1618

    
1619
    migrate_default_bridge = not self.nicparams
1620
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1621
                                          constants.NICC_DEFAULTS)
1622
    if migrate_default_bridge:
1623
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1624
        self.default_bridge
1625

    
1626
    if self.modify_etc_hosts is None:
1627
      self.modify_etc_hosts = True
1628

    
1629
    if self.modify_ssh_setup is None:
1630
      self.modify_ssh_setup = True
1631

    
1632
    # default_bridge is no longer used in 2.1. The slot is left there to
1633
    # support auto-upgrading. It can be removed once we decide to deprecate
1634
    # upgrading straight from 2.0.
1635
    if self.default_bridge is not None:
1636
      self.default_bridge = None
1637

    
1638
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1639
    # code can be removed once upgrading straight from 2.0 is deprecated.
1640
    if self.default_hypervisor is not None:
1641
      self.enabled_hypervisors = ([self.default_hypervisor] +
1642
                                  [hvname for hvname in self.enabled_hypervisors
1643
                                   if hvname != self.default_hypervisor])
1644
      self.default_hypervisor = None
1645

    
1646
    # maintain_node_health added after 2.1.1
1647
    if self.maintain_node_health is None:
1648
      self.maintain_node_health = False
1649

    
1650
    if self.uid_pool is None:
1651
      self.uid_pool = []
1652

    
1653
    if self.default_iallocator is None:
1654
      self.default_iallocator = ""
1655

    
1656
    # reserved_lvs added before 2.2
1657
    if self.reserved_lvs is None:
1658
      self.reserved_lvs = []
1659

    
1660
    # hidden and blacklisted operating systems added before 2.2.1
1661
    if self.hidden_os is None:
1662
      self.hidden_os = []
1663

    
1664
    if self.blacklisted_os is None:
1665
      self.blacklisted_os = []
1666

    
1667
    # primary_ip_family added before 2.3
1668
    if self.primary_ip_family is None:
1669
      self.primary_ip_family = AF_INET
1670

    
1671
    if self.master_netmask is None:
1672
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1673
      self.master_netmask = ipcls.iplen
1674

    
1675
    if self.prealloc_wipe_disks is None:
1676
      self.prealloc_wipe_disks = False
1677

    
1678
    # shared_file_storage_dir added before 2.5
1679
    if self.shared_file_storage_dir is None:
1680
      self.shared_file_storage_dir = ""
1681

    
1682
    if self.use_external_mip_script is None:
1683
      self.use_external_mip_script = False
1684

    
1685
    if self.diskparams:
1686
      self.diskparams = UpgradeDiskParams(self.diskparams)
1687
    else:
1688
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1689

    
1690
    # instance policy added before 2.6
1691
    if self.ipolicy is None:
1692
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1693
    else:
1694
      # we can either make sure to upgrade the ipolicy always, or only
1695
      # do it in some corner cases (e.g. missing keys); note that this
1696
      # will break any removal of keys from the ipolicy dict
1697
      wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1698
      if wrongkeys:
1699
        # These keys would be silently removed by FillIPolicy()
1700
        msg = ("Cluster instance policy contains spurious keys: %s" %
1701
               utils.CommaJoin(wrongkeys))
1702
        raise errors.ConfigurationError(msg)
1703
      self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1704

    
1705
  @property
1706
  def primary_hypervisor(self):
1707
    """The first hypervisor is the primary.
1708

1709
    Useful, for example, for L{Node}'s hv/disk state.
1710

1711
    """
1712
    return self.enabled_hypervisors[0]
1713

    
1714
  def ToDict(self):
1715
    """Custom function for cluster.
1716

1717
    """
1718
    mydict = super(Cluster, self).ToDict()
1719

    
1720
    if self.tcpudp_port_pool is None:
1721
      tcpudp_port_pool = []
1722
    else:
1723
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1724

    
1725
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1726

    
1727
    return mydict
1728

    
1729
  @classmethod
1730
  def FromDict(cls, val):
1731
    """Custom function for cluster.
1732

1733
    """
1734
    obj = super(Cluster, cls).FromDict(val)
1735

    
1736
    if obj.tcpudp_port_pool is None:
1737
      obj.tcpudp_port_pool = set()
1738
    elif not isinstance(obj.tcpudp_port_pool, set):
1739
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1740

    
1741
    return obj
1742

    
1743
  def SimpleFillDP(self, diskparams):
1744
    """Fill a given diskparams dict with cluster defaults.
1745

1746
    @param diskparams: The diskparams
1747
    @return: The defaults dict
1748

1749
    """
1750
    return FillDiskParams(self.diskparams, diskparams)
1751

    
1752
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1753
    """Get the default hypervisor parameters for the cluster.
1754

1755
    @param hypervisor: the hypervisor name
1756
    @param os_name: if specified, we'll also update the defaults for this OS
1757
    @param skip_keys: if passed, list of keys not to use
1758
    @return: the defaults dict
1759

1760
    """
1761
    if skip_keys is None:
1762
      skip_keys = []
1763

    
1764
    fill_stack = [self.hvparams.get(hypervisor, {})]
1765
    if os_name is not None:
1766
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1767
      fill_stack.append(os_hvp)
1768

    
1769
    ret_dict = {}
1770
    for o_dict in fill_stack:
1771
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1772

    
1773
    return ret_dict
1774

    
1775
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1776
    """Fill a given hvparams dict with cluster defaults.
1777

1778
    @type hv_name: string
1779
    @param hv_name: the hypervisor to use
1780
    @type os_name: string
1781
    @param os_name: the OS to use for overriding the hypervisor defaults
1782
    @type skip_globals: boolean
1783
    @param skip_globals: if True, the global hypervisor parameters will
1784
        not be filled
1785
    @rtype: dict
1786
    @return: a copy of the given hvparams with missing keys filled from
1787
        the cluster defaults
1788

1789
    """
1790
    if skip_globals:
1791
      skip_keys = constants.HVC_GLOBALS
1792
    else:
1793
      skip_keys = []
1794

    
1795
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1796
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1797

    
1798
  def FillHV(self, instance, skip_globals=False):
1799
    """Fill an instance's hvparams dict with cluster defaults.
1800

1801
    @type instance: L{objects.Instance}
1802
    @param instance: the instance parameter to fill
1803
    @type skip_globals: boolean
1804
    @param skip_globals: if True, the global hypervisor parameters will
1805
        not be filled
1806
    @rtype: dict
1807
    @return: a copy of the instance's hvparams with missing keys filled from
1808
        the cluster defaults
1809

1810
    """
1811
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1812
                             instance.hvparams, skip_globals)
1813

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

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

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

    
1826
  def FillBE(self, instance):
1827
    """Fill an instance's beparams dict with cluster defaults.
1828

1829
    @type instance: L{objects.Instance}
1830
    @param instance: the instance parameter to fill
1831
    @rtype: dict
1832
    @return: a copy of the instance's beparams with missing keys filled from
1833
        the cluster defaults
1834

1835
    """
1836
    return self.SimpleFillBE(instance.beparams)
1837

    
1838
  def SimpleFillNIC(self, nicparams):
1839
    """Fill a given nicparams dict with cluster defaults.
1840

1841
    @type nicparams: dict
1842
    @param nicparams: the dict to fill
1843
    @rtype: dict
1844
    @return: a copy of the passed in nicparams with missing keys filled
1845
        from the cluster defaults
1846

1847
    """
1848
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1849

    
1850
  def SimpleFillOS(self, os_name, os_params):
1851
    """Fill an instance's osparams dict with cluster defaults.
1852

1853
    @type os_name: string
1854
    @param os_name: the OS name to use
1855
    @type os_params: dict
1856
    @param os_params: the dict to fill with default values
1857
    @rtype: dict
1858
    @return: a copy of the instance's osparams with missing keys filled from
1859
        the cluster defaults
1860

1861
    """
1862
    name_only = os_name.split("+", 1)[0]
1863
    # base OS
1864
    result = self.osparams.get(name_only, {})
1865
    # OS with variant
1866
    result = FillDict(result, self.osparams.get(os_name, {}))
1867
    # specified params
1868
    return FillDict(result, os_params)
1869

    
1870
  @staticmethod
1871
  def SimpleFillHvState(hv_state):
1872
    """Fill an hv_state sub dict with cluster defaults.
1873

1874
    """
1875
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1876

    
1877
  @staticmethod
1878
  def SimpleFillDiskState(disk_state):
1879
    """Fill an disk_state sub dict with cluster defaults.
1880

1881
    """
1882
    return FillDict(constants.DS_DEFAULTS, disk_state)
1883

    
1884
  def FillND(self, node, nodegroup):
1885
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1886

1887
    @type node: L{objects.Node}
1888
    @param node: A Node object to fill
1889
    @type nodegroup: L{objects.NodeGroup}
1890
    @param nodegroup: A Node object to fill
1891
    @return a copy of the node's ndparams with defaults filled
1892

1893
    """
1894
    return self.SimpleFillND(nodegroup.FillND(node))
1895

    
1896
  def SimpleFillND(self, ndparams):
1897
    """Fill a given ndparams dict with defaults.
1898

1899
    @type ndparams: dict
1900
    @param ndparams: the dict to fill
1901
    @rtype: dict
1902
    @return: a copy of the passed in ndparams with missing keys filled
1903
        from the cluster defaults
1904

1905
    """
1906
    return FillDict(self.ndparams, ndparams)
1907

    
1908
  def SimpleFillIPolicy(self, ipolicy):
1909
    """ Fill instance policy dict with defaults.
1910

1911
    @type ipolicy: dict
1912
    @param ipolicy: the dict to fill
1913
    @rtype: dict
1914
    @return: a copy of passed ipolicy with missing keys filled from
1915
      the cluster defaults
1916

1917
    """
1918
    return FillIPolicy(self.ipolicy, ipolicy)
1919

    
1920
  def IsDiskTemplateEnabled(self, disk_template):
1921
    """Checks if a particular disk template is enabled.
1922

1923
    """
1924
    return utils.storage.IsDiskTemplateEnabled(
1925
        disk_template, self.enabled_disk_templates)
1926

    
1927
  def IsFileStorageEnabled(self):
1928
    """Checks if file storage is enabled.
1929

1930
    """
1931
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1932

    
1933
  def IsSharedFileStorageEnabled(self):
1934
    """Checks if shared file storage is enabled.
1935

1936
    """
1937
    return utils.storage.IsSharedFileStorageEnabled(
1938
        self.enabled_disk_templates)
1939

    
1940

    
1941
class BlockDevStatus(ConfigObject):
1942
  """Config object representing the status of a block device."""
1943
  __slots__ = [
1944
    "dev_path",
1945
    "major",
1946
    "minor",
1947
    "sync_percent",
1948
    "estimated_time",
1949
    "is_degraded",
1950
    "ldisk_status",
1951
    ]
1952

    
1953

    
1954
class ImportExportStatus(ConfigObject):
1955
  """Config object representing the status of an import or export."""
1956
  __slots__ = [
1957
    "recent_output",
1958
    "listen_port",
1959
    "connected",
1960
    "progress_mbytes",
1961
    "progress_throughput",
1962
    "progress_eta",
1963
    "progress_percent",
1964
    "exit_status",
1965
    "error_message",
1966
    ] + _TIMESTAMPS
1967

    
1968

    
1969
class ImportExportOptions(ConfigObject):
1970
  """Options for import/export daemon
1971

1972
  @ivar key_name: X509 key name (None for cluster certificate)
1973
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1974
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
1975
  @ivar magic: Used to ensure the connection goes to the right disk
1976
  @ivar ipv6: Whether to use IPv6
1977
  @ivar connect_timeout: Number of seconds for establishing connection
1978

1979
  """
1980
  __slots__ = [
1981
    "key_name",
1982
    "ca_pem",
1983
    "compress",
1984
    "magic",
1985
    "ipv6",
1986
    "connect_timeout",
1987
    ]
1988

    
1989

    
1990
class ConfdRequest(ConfigObject):
1991
  """Object holding a confd request.
1992

1993
  @ivar protocol: confd protocol version
1994
  @ivar type: confd query type
1995
  @ivar query: query request
1996
  @ivar rsalt: requested reply salt
1997

1998
  """
1999
  __slots__ = [
2000
    "protocol",
2001
    "type",
2002
    "query",
2003
    "rsalt",
2004
    ]
2005

    
2006

    
2007
class ConfdReply(ConfigObject):
2008
  """Object holding a confd reply.
2009

2010
  @ivar protocol: confd protocol version
2011
  @ivar status: reply status code (ok, error)
2012
  @ivar answer: confd query reply
2013
  @ivar serial: configuration serial number
2014

2015
  """
2016
  __slots__ = [
2017
    "protocol",
2018
    "status",
2019
    "answer",
2020
    "serial",
2021
    ]
2022

    
2023

    
2024
class QueryFieldDefinition(ConfigObject):
2025
  """Object holding a query field definition.
2026

2027
  @ivar name: Field name
2028
  @ivar title: Human-readable title
2029
  @ivar kind: Field type
2030
  @ivar doc: Human-readable description
2031

2032
  """
2033
  __slots__ = [
2034
    "name",
2035
    "title",
2036
    "kind",
2037
    "doc",
2038
    ]
2039

    
2040

    
2041
class _QueryResponseBase(ConfigObject):
2042
  __slots__ = [
2043
    "fields",
2044
    ]
2045

    
2046
  def ToDict(self):
2047
    """Custom function for serializing.
2048

2049
    """
2050
    mydict = super(_QueryResponseBase, self).ToDict()
2051
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2052
    return mydict
2053

    
2054
  @classmethod
2055
  def FromDict(cls, val):
2056
    """Custom function for de-serializing.
2057

2058
    """
2059
    obj = super(_QueryResponseBase, cls).FromDict(val)
2060
    obj.fields = \
2061
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2062
    return obj
2063

    
2064

    
2065
class QueryResponse(_QueryResponseBase):
2066
  """Object holding the response to a query.
2067

2068
  @ivar fields: List of L{QueryFieldDefinition} objects
2069
  @ivar data: Requested data
2070

2071
  """
2072
  __slots__ = [
2073
    "data",
2074
    ]
2075

    
2076

    
2077
class QueryFieldsRequest(ConfigObject):
2078
  """Object holding a request for querying available fields.
2079

2080
  """
2081
  __slots__ = [
2082
    "what",
2083
    "fields",
2084
    ]
2085

    
2086

    
2087
class QueryFieldsResponse(_QueryResponseBase):
2088
  """Object holding the response to a query for fields.
2089

2090
  @ivar fields: List of L{QueryFieldDefinition} objects
2091

2092
  """
2093
  __slots__ = []
2094

    
2095

    
2096
class MigrationStatus(ConfigObject):
2097
  """Object holding the status of a migration.
2098

2099
  """
2100
  __slots__ = [
2101
    "status",
2102
    "transferred_ram",
2103
    "total_ram",
2104
    ]
2105

    
2106

    
2107
class InstanceConsole(ConfigObject):
2108
  """Object describing how to access the console of an instance.
2109

2110
  """
2111
  __slots__ = [
2112
    "instance",
2113
    "kind",
2114
    "message",
2115
    "host",
2116
    "port",
2117
    "user",
2118
    "command",
2119
    "display",
2120
    ]
2121

    
2122
  def Validate(self):
2123
    """Validates contents of this object.
2124

2125
    """
2126
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2127
    assert self.instance, "Missing instance name"
2128
    assert self.message or self.kind in [constants.CONS_SSH,
2129
                                         constants.CONS_SPICE,
2130
                                         constants.CONS_VNC]
2131
    assert self.host or self.kind == constants.CONS_MESSAGE
2132
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2133
                                      constants.CONS_SSH]
2134
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2135
                                      constants.CONS_SPICE,
2136
                                      constants.CONS_VNC]
2137
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2138
                                         constants.CONS_SPICE,
2139
                                         constants.CONS_VNC]
2140
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2141
                                         constants.CONS_SPICE,
2142
                                         constants.CONS_SSH]
2143
    return True
2144

    
2145

    
2146
class Network(TaggableObject):
2147
  """Object representing a network definition for ganeti.
2148

2149
  """
2150
  __slots__ = [
2151
    "name",
2152
    "serial_no",
2153
    "mac_prefix",
2154
    "network",
2155
    "network6",
2156
    "gateway",
2157
    "gateway6",
2158
    "reservations",
2159
    "ext_reservations",
2160
    ] + _TIMESTAMPS + _UUID
2161

    
2162
  def HooksDict(self, prefix=""):
2163
    """Export a dictionary used by hooks with a network's information.
2164

2165
    @type prefix: String
2166
    @param prefix: Prefix to prepend to the dict entries
2167

2168
    """
2169
    result = {
2170
      "%sNETWORK_NAME" % prefix: self.name,
2171
      "%sNETWORK_UUID" % prefix: self.uuid,
2172
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2173
    }
2174
    if self.network:
2175
      result["%sNETWORK_SUBNET" % prefix] = self.network
2176
    if self.gateway:
2177
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2178
    if self.network6:
2179
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2180
    if self.gateway6:
2181
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2182
    if self.mac_prefix:
2183
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2184

    
2185
    return result
2186

    
2187
  @classmethod
2188
  def FromDict(cls, val):
2189
    """Custom function for networks.
2190

2191
    Remove deprecated network_type and family.
2192

2193
    """
2194
    if "network_type" in val:
2195
      del val["network_type"]
2196
    if "family" in val:
2197
      del val["family"]
2198
    obj = super(Network, cls).FromDict(val)
2199
    return obj
2200

    
2201

    
2202
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2203
  """Simple wrapper over ConfigParse that allows serialization.
2204

2205
  This class is basically ConfigParser.SafeConfigParser with two
2206
  additional methods that allow it to serialize/unserialize to/from a
2207
  buffer.
2208

2209
  """
2210
  def Dumps(self):
2211
    """Dump this instance and return the string representation."""
2212
    buf = StringIO()
2213
    self.write(buf)
2214
    return buf.getvalue()
2215

    
2216
  @classmethod
2217
  def Loads(cls, data):
2218
    """Load data from a string."""
2219
    buf = StringIO(data)
2220
    cfp = cls()
2221
    cfp.readfp(buf)
2222
    return cfp
2223

    
2224

    
2225
class LvmPvInfo(ConfigObject):
2226
  """Information about an LVM physical volume (PV).
2227

2228
  @type name: string
2229
  @ivar name: name of the PV
2230
  @type vg_name: string
2231
  @ivar vg_name: name of the volume group containing the PV
2232
  @type size: float
2233
  @ivar size: size of the PV in MiB
2234
  @type free: float
2235
  @ivar free: free space in the PV, in MiB
2236
  @type attributes: string
2237
  @ivar attributes: PV attributes
2238
  @type lv_list: list of strings
2239
  @ivar lv_list: names of the LVs hosted on the PV
2240
  """
2241
  __slots__ = [
2242
    "name",
2243
    "vg_name",
2244
    "size",
2245
    "free",
2246
    "attributes",
2247
    "lv_list"
2248
    ]
2249

    
2250
  def IsEmpty(self):
2251
    """Is this PV empty?
2252

2253
    """
2254
    return self.size <= (self.free + 1)
2255

    
2256
  def IsAllocatable(self):
2257
    """Is this PV allocatable?
2258

2259
    """
2260
    return ("a" in self.attributes)