Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ 84ad6b78

History | View | Annotate | Download (64.9 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
    if self.nodegroups is None:
447
      self.nodegroups = {}
448
    for nodegroup in self.nodegroups.values():
449
      nodegroup.UpgradeConfig()
450
    if self.cluster.drbd_usermode_helper is None:
451
      if self.cluster.IsDiskTemplateEnabled(constants.DT_DRBD8):
452
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
453
    if self.networks is None:
454
      self.networks = {}
455
    for network in self.networks.values():
456
      network.UpgradeConfig()
457
    self._UpgradeEnabledDiskTemplates()
458

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

463
    """
464
    # enabled_disk_templates in the cluster config were introduced in 2.8.
465
    # Remove this code once upgrading from earlier versions is deprecated.
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

    
483

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

    
488
  @classmethod
489
  def CheckParameterSyntax(cls, nicparams):
490
    """Check the given parameters for validity.
491

492
    @type nicparams:  dict
493
    @param nicparams: dictionary with parameter names/value
494
    @raise errors.ConfigurationError: when a parameter is not valid
495

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

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

    
506

    
507
class Disk(ConfigObject):
508
  """Config object representing a block device."""
509
  __slots__ = (["name", "dev_type", "logical_id", "children", "iv_name",
510
                "size", "mode", "params", "spindles"] + _UUID +
511
               # dynamic_params is special. It depends on the node this instance
512
               # is sent to, and should not be persisted.
513
               ["dynamic_params"])
514

    
515
  def CreateOnSecondary(self):
516
    """Test if this device needs to be created on a secondary node."""
517
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
518

    
519
  def AssembleOnSecondary(self):
520
    """Test if this device needs to be assembled on a secondary node."""
521
    return self.dev_type in (constants.DT_DRBD8, constants.DT_PLAIN)
522

    
523
  def OpenOnSecondary(self):
524
    """Test if this device needs to be opened on a secondary node."""
525
    return self.dev_type in (constants.DT_PLAIN,)
526

    
527
  def StaticDevPath(self):
528
    """Return the device path if this device type has a static one.
529

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

534
    @warning: The path returned is not a normalized pathname; callers
535
        should check that it is a valid path.
536

537
    """
538
    if self.dev_type == constants.DT_PLAIN:
539
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
540
    elif self.dev_type == constants.DT_BLOCK:
541
      return self.logical_id[1]
542
    elif self.dev_type == constants.DT_RBD:
543
      return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
544
    return None
545

    
546
  def ChildrenNeeded(self):
547
    """Compute the needed number of children for activation.
548

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

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

557
    """
558
    if self.dev_type == constants.DT_DRBD8:
559
      return 0
560
    return -1
561

    
562
  def IsBasedOnDiskType(self, dev_type):
563
    """Check if the disk or its children are based on the given type.
564

565
    @type dev_type: L{constants.DTS_BLOCK}
566
    @param dev_type: the type to look for
567
    @rtype: boolean
568
    @return: boolean indicating if a device of the given type was found or not
569

570
    """
571
    if self.children:
572
      for child in self.children:
573
        if child.IsBasedOnDiskType(dev_type):
574
          return True
575
    return self.dev_type == dev_type
576

    
577
  def GetNodes(self, node_uuid):
578
    """This function returns the nodes this device lives on.
579

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

585
    """
586
    if self.dev_type in [constants.DT_PLAIN, constants.DT_FILE,
587
                         constants.DT_BLOCK, constants.DT_RBD,
588
                         constants.DT_EXT, constants.DT_SHARED_FILE]:
589
      result = [node_uuid]
590
    elif self.dev_type in constants.LDS_DRBD:
591
      result = [self.logical_id[0], self.logical_id[1]]
592
      if node_uuid not in result:
593
        raise errors.ConfigurationError("DRBD device passed unknown node")
594
    else:
595
      raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
596
    return result
597

    
598
  def ComputeNodeTree(self, parent_node_uuid):
599
    """Compute the node/disk tree for this disk and its children.
600

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

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

    
633
  def ComputeGrowth(self, amount):
634
    """Compute the per-VG growth requirements.
635

636
    This only works for VG-based disks.
637

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

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

    
655
  def RecordGrow(self, amount):
656
    """Update the size of this disk after growth.
657

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

662
    """
663
    if self.dev_type in (constants.DT_PLAIN, constants.DT_FILE,
664
                         constants.DT_RBD, constants.DT_EXT,
665
                         constants.DT_SHARED_FILE):
666
      self.size += amount
667
    elif self.dev_type == constants.DT_DRBD8:
668
      if self.children:
669
        self.children[0].RecordGrow(amount)
670
      self.size += amount
671
    else:
672
      raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
673
                                   " disk type %s" % self.dev_type)
674

    
675
  def Update(self, size=None, mode=None, spindles=None):
676
    """Apply changes to size, spindles and mode.
677

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

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

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

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

    
701
  def UpdateDynamicDiskParams(self, target_node_uuid, nodes_ip):
702
    """Updates the dynamic disk params for the given node.
703

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

706
    Arguments:
707
      - target_node_uuid: the node UUID we wish to configure for
708
      - nodes_ip: a mapping of node name to ip
709

710
    The target_node must exist in nodes_ip, and should be one of the
711
    nodes in the logical ID if this device is a DRBD device.
712

713
    """
714
    if self.children:
715
      for child in self.children:
716
        child.UpdateDynamicDiskParams(target_node_uuid, nodes_ip)
717

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

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

    
744
    self.dynamic_params = dyn_disk_params
745

    
746
  # pylint: disable=W0221
747
  def ToDict(self, include_dynamic_params=False):
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
    if not include_dynamic_params and "dynamic_params" in bo:
756
      del bo["dynamic_params"]
757

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

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

768
    """
769
    obj = super(Disk, cls).FromDict(val)
770
    if obj.children:
771
      obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
772
    if obj.logical_id and isinstance(obj.logical_id, list):
773
      obj.logical_id = tuple(obj.logical_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.DT_PLAIN:
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

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

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

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

    
820
  def UpgradeConfig(self):
821
    """Fill defaults for missing configuration values.
822

823
    """
824
    if self.children:
825
      for child in self.children:
826
        child.UpgradeConfig()
827

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

    
832
    # map of legacy device types (mapping differing LD constants to new
833
    # DT constants)
834
    LEG_DEV_TYPE_MAP = {"lvm": constants.DT_PLAIN, "drbd8": constants.DT_DRBD8}
835
    if self.dev_type in LEG_DEV_TYPE_MAP:
836
      self.dev_type = LEG_DEV_TYPE_MAP[self.dev_type]
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.DT_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.DT_PLAIN], {
878
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
879
        }))
880

    
881
      # metadata LV
882
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
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[disk_template])
888

    
889
    elif disk_template == constants.DT_PLAIN:
890
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
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.DT_BLOCK])
896

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

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

    
906
    return result
907

    
908

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1051

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

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

1074
    This is a simple wrapper over _ComputeAllNodes.
1075

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1161
    return ret
1162

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

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

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

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

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

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

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

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

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

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

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

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

    
1241

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

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

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

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

    
1266
  VARIANT_DELIM = "+"
1267

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

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

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

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

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

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

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

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

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

    
1301

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

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

    
1319

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

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

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

    
1342

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

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

    
1353

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

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

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

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

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

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

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

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

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

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

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

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

    
1422
    return data
1423

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

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

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

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

    
1440
    return obj
1441

    
1442

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1528

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

    
1575
  def UpgradeConfig(self):
1576
    """Fill defaults for missing configuration values.
1577

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

    
1588
    if self.os_hvp is None:
1589
      self.os_hvp = {}
1590

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

    
1595
    self.ndparams = UpgradeNDParams(self.ndparams)
1596

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

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

    
1609
    if self.modify_etc_hosts is None:
1610
      self.modify_etc_hosts = True
1611

    
1612
    if self.modify_ssh_setup is None:
1613
      self.modify_ssh_setup = True
1614

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

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

    
1629
    # maintain_node_health added after 2.1.1
1630
    if self.maintain_node_health is None:
1631
      self.maintain_node_health = False
1632

    
1633
    if self.uid_pool is None:
1634
      self.uid_pool = []
1635

    
1636
    if self.default_iallocator is None:
1637
      self.default_iallocator = ""
1638

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

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

    
1647
    if self.blacklisted_os is None:
1648
      self.blacklisted_os = []
1649

    
1650
    # primary_ip_family added before 2.3
1651
    if self.primary_ip_family is None:
1652
      self.primary_ip_family = AF_INET
1653

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

    
1658
    if self.prealloc_wipe_disks is None:
1659
      self.prealloc_wipe_disks = False
1660

    
1661
    # shared_file_storage_dir added before 2.5
1662
    if self.shared_file_storage_dir is None:
1663
      self.shared_file_storage_dir = ""
1664

    
1665
    if self.use_external_mip_script is None:
1666
      self.use_external_mip_script = False
1667

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

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

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

1692
    Useful, for example, for L{Node}'s hv/disk state.
1693

1694
    """
1695
    return self.enabled_hypervisors[0]
1696

    
1697
  def ToDict(self):
1698
    """Custom function for cluster.
1699

1700
    """
1701
    mydict = super(Cluster, self).ToDict()
1702

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

    
1708
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1709

    
1710
    return mydict
1711

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

1716
    """
1717
    obj = super(Cluster, cls).FromDict(val)
1718

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

    
1724
    return obj
1725

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

1729
    @param diskparams: The diskparams
1730
    @return: The defaults dict
1731

1732
    """
1733
    return FillDiskParams(self.diskparams, diskparams)
1734

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

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

1743
    """
1744
    if skip_keys is None:
1745
      skip_keys = []
1746

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

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

    
1756
    return ret_dict
1757

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

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

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

    
1778
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1779
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1780

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

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

1793
    """
1794
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1795
                             instance.hvparams, skip_globals)
1796

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

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

1806
    """
1807
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1808

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

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

1818
    """
1819
    return self.SimpleFillBE(instance.beparams)
1820

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

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

1830
    """
1831
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1832

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

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

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

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

1857
    """
1858
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1859

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

1864
    """
1865
    return FillDict(constants.DS_DEFAULTS, disk_state)
1866

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

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

1876
    """
1877
    return self.SimpleFillND(nodegroup.FillND(node))
1878

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

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

1888
    """
1889
    return FillDict(self.ndparams, ndparams)
1890

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

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

1900
    """
1901
    return FillIPolicy(self.ipolicy, ipolicy)
1902

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

1906
    """
1907
    return utils.storage.IsDiskTemplateEnabled(
1908
        disk_template, self.enabled_disk_templates)
1909

    
1910
  def IsFileStorageEnabled(self):
1911
    """Checks if file storage is enabled.
1912

1913
    """
1914
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1915

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

1919
    """
1920
    return utils.storage.IsSharedFileStorageEnabled(
1921
        self.enabled_disk_templates)
1922

    
1923

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

    
1936

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

    
1951

    
1952
class ImportExportOptions(ConfigObject):
1953
  """Options for import/export daemon
1954

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

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

    
1972

    
1973
class ConfdRequest(ConfigObject):
1974
  """Object holding a confd request.
1975

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

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

    
1989

    
1990
class ConfdReply(ConfigObject):
1991
  """Object holding a confd reply.
1992

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

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

    
2006

    
2007
class QueryFieldDefinition(ConfigObject):
2008
  """Object holding a query field definition.
2009

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

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

    
2023

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

    
2029
  def ToDict(self):
2030
    """Custom function for serializing.
2031

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

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

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

    
2047

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

2051
  @ivar fields: List of L{QueryFieldDefinition} objects
2052
  @ivar data: Requested data
2053

2054
  """
2055
  __slots__ = [
2056
    "data",
2057
    ]
2058

    
2059

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

2063
  """
2064
  __slots__ = [
2065
    "what",
2066
    "fields",
2067
    ]
2068

    
2069

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

2073
  @ivar fields: List of L{QueryFieldDefinition} objects
2074

2075
  """
2076
  __slots__ = []
2077

    
2078

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

2082
  """
2083
  __slots__ = [
2084
    "status",
2085
    "transferred_ram",
2086
    "total_ram",
2087
    ]
2088

    
2089

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

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

    
2105
  def Validate(self):
2106
    """Validates contents of this object.
2107

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

    
2128

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

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

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

2148
    @type prefix: String
2149
    @param prefix: Prefix to prepend to the dict entries
2150

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

    
2168
    return result
2169

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

2174
    Remove deprecated network_type and family.
2175

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

    
2184

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

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

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

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

    
2207

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

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

    
2233
  def IsEmpty(self):
2234
    """Is this PV empty?
2235

2236
    """
2237
    return self.size <= (self.free + 1)
2238

    
2239
  def IsAllocatable(self):
2240
    """Is this PV allocatable?
2241

2242
    """
2243
    return ("a" in self.attributes)