Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ fc6ccde4

History | View | Annotate | Download (65.7 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
      if k in ret_dict:
79
        del ret_dict[k]
80
  return ret_dict
81

    
82

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

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

    
96

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

100
  @see: L{FillDict} for parameters and return value
101

102
  """
103
  assert frozenset(default_dparams.keys()) == constants.DISK_TEMPLATES
104

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

    
109

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

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

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

    
126

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

130
  @type target: dict
131
  @param target: "be" parameters dict
132

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

    
140

    
141
def UpgradeDiskParams(diskparams):
142
  """Upgrade the disk parameters.
143

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

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

    
155
  return result
156

    
157

    
158
def UpgradeNDParams(ndparams):
159
  """Upgrade ndparams structure.
160

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

166
  """
167
  if ndparams is None:
168
    ndparams = {}
169

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

    
176

    
177
def MakeEmptyIPolicy():
178
  """Create empty IPolicy dictionary.
179

180
  """
181
  return {}
182

    
183

    
184
class ConfigObject(outils.ValidatedSlots):
185
  """A generic config object.
186

187
  It has the following properties:
188

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

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

196
  """
197
  __slots__ = []
198

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

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

    
211
  def Validate(self):
212
    """Validates the slots.
213

214
    """
215

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

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

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

    
233
  __getstate__ = ToDict
234

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

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

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

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

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

258
    """
259
    dict_form = self.ToDict()
260
    clone_obj = self.__class__.FromDict(dict_form)
261
    return clone_obj
262

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

    
267
  def __eq__(self, other):
268
    """Implement __eq__ for ConfigObjects."""
269
    return isinstance(other, self.__class__) and self.ToDict() == other.ToDict()
270

    
271
  def UpgradeConfig(self):
272
    """Fill defaults for missing configuration values.
273

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

277
    """
278
    pass
279

    
280

    
281
class TaggableObject(ConfigObject):
282
  """An generic class supporting tags.
283

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

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

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

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

    
306
  def GetTags(self):
307
    """Return the tags list.
308

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

    
315
  def AddTag(self, tag):
316
    """Add a new tag.
317

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

    
325
  def RemoveTag(self, tag):
326
    """Remove a tag.
327

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

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

339
    This replaces the tags set with a list.
340

341
    """
342
    bo = super(TaggableObject, self).ToDict()
343

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

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

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

    
359

    
360
class MasterNetworkParameters(ConfigObject):
361
  """Network configuration parameters for the master
362

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

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

    
378

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

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

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

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

    
403
    return mydict
404

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

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

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

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

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

    
435
  def UpgradeConfig(self):
436
    """Fill defaults for missing configuration values.
437

438
    """
439
    self.cluster.UpgradeConfig()
440
    for node in self.nodes.values():
441
      node.UpgradeConfig()
442
    for instance in self.instances.values():
443
      instance.UpgradeConfig()
444
    self._UpgradeEnabledDiskTemplates()
445
    if self.nodegroups is None:
446
      self.nodegroups = {}
447
    for nodegroup in self.nodegroups.values():
448
      nodegroup.UpgradeConfig()
449
      InstancePolicy.UpgradeDiskTemplates(
450
        nodegroup.ipolicy, self.cluster.enabled_disk_templates)
451
    if self.cluster.drbd_usermode_helper is None:
452
      if self.cluster.IsDiskTemplateEnabled(constants.DT_DRBD8):
453
        self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
454
    if self.networks is None:
455
      self.networks = {}
456
    for network in self.networks.values():
457
      network.UpgradeConfig()
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
    if not self.cluster.enabled_disk_templates:
465
      template_set = \
466
        set([inst.disk_template for inst in self.instances.values()])
467
      # Add drbd and plain, if lvm is enabled (by specifying a volume group)
468
      if self.cluster.volume_group_name:
469
        template_set.add(constants.DT_DRBD8)
470
        template_set.add(constants.DT_PLAIN)
471
      # Set enabled_disk_templates to the inferred disk templates. Order them
472
      # according to a preference list that is based on Ganeti's history of
473
      # supported disk templates.
474
      self.cluster.enabled_disk_templates = []
475
      for preferred_template in constants.DISK_TEMPLATE_PREFERENCE:
476
        if preferred_template in template_set:
477
          self.cluster.enabled_disk_templates.append(preferred_template)
478
          template_set.remove(preferred_template)
479
      self.cluster.enabled_disk_templates.extend(list(template_set))
480
    InstancePolicy.UpgradeDiskTemplates(
481
      self.cluster.ipolicy, self.cluster.enabled_disk_templates)
482

    
483

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

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

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

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

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

    
507

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

638
    This only works for VG-based disks.
639

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
746
    self.dynamic_params = dyn_disk_params
747

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
837
    # add here config upgrade for this disk
838

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

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

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

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

    
862
    assert disk_template in disk_params
863

    
864
    result = list()
865
    dt_params = disk_params[disk_template]
866

    
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
    else:
895
      defaults = constants.DISK_LD_DEFAULTS[disk_template]
896
      values = {}
897
      for field in defaults:
898
        values[field] = dt_params[field]
899
      result.append(FillDict(defaults, values))
900

    
901
    return result
902

    
903

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

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

910
  """
911
  @classmethod
912
  def UpgradeDiskTemplates(cls, ipolicy, enabled_disk_templates):
913
    """Upgrades the ipolicy configuration."""
914
    if constants.IPOLICY_DTS in ipolicy:
915
      if not set(ipolicy[constants.IPOLICY_DTS]).issubset(
916
        set(enabled_disk_templates)):
917
        ipolicy[constants.IPOLICY_DTS] = list(
918
          set(ipolicy[constants.IPOLICY_DTS]) & set(enabled_disk_templates))
919

    
920
  @classmethod
921
  def CheckParameterSyntax(cls, ipolicy, check_std):
922
    """ Check the instance policy for validity.
923

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

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

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

    
950
  @classmethod
951
  def CheckISpecSyntax(cls, ipolicy, check_std):
952
    """Check the instance policy specs for validity.
953

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

960
    """
961
    if constants.ISPECS_MINMAX not in ipolicy:
962
      # Nothing to check
963
      return
964

    
965
    if check_std and constants.ISPECS_STD not in ipolicy:
966
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
967
      raise errors.ConfigurationError(msg)
968
    stdspec = ipolicy.get(constants.ISPECS_STD)
969
    if check_std:
970
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
971

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

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

    
992
  @classmethod
993
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
994
    """Check the instance policy specs for validity on a given key.
995

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

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

1013
    """
1014
    minspec = minmaxspecs[constants.ISPECS_MIN]
1015
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1016
    min_v = minspec[name]
1017
    max_v = maxspec[name]
1018

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

    
1029
  @classmethod
1030
  def CheckDiskTemplates(cls, disk_templates):
1031
    """Checks the disk templates for validity.
1032

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

    
1042
  @classmethod
1043
  def CheckParameter(cls, key, value):
1044
    """Checks a parameter.
1045

1046
    Currently we expect all parameters to be float values.
1047

1048
    """
1049
    try:
1050
      float(value)
1051
    except (TypeError, ValueError), err:
1052
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1053
                                      " '%s', error: %s" % (key, value, err))
1054

    
1055

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

    
1075
  def _ComputeSecondaryNodes(self):
1076
    """Compute the list of secondary nodes.
1077

1078
    This is a simple wrapper over _ComputeAllNodes.
1079

1080
    """
1081
    all_nodes = set(self._ComputeAllNodes())
1082
    all_nodes.discard(self.primary_node)
1083
    return tuple(all_nodes)
1084

    
1085
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1086
                             "List of names of secondary nodes")
1087

    
1088
  def _ComputeAllNodes(self):
1089
    """Compute the list of all nodes.
1090

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

1096
    """
1097
    def _Helper(nodes, device):
1098
      """Recursively computes nodes given a top device."""
1099
      if device.dev_type in constants.DTS_DRBD:
1100
        nodea, nodeb = device.logical_id[:2]
1101
        nodes.add(nodea)
1102
        nodes.add(nodeb)
1103
      if device.children:
1104
        for child in device.children:
1105
          _Helper(nodes, child)
1106

    
1107
    all_nodes = set()
1108
    all_nodes.add(self.primary_node)
1109
    for device in self.disks:
1110
      _Helper(all_nodes, device)
1111
    return tuple(all_nodes)
1112

    
1113
  all_nodes = property(_ComputeAllNodes, None, None,
1114
                       "List of names of all the nodes of the instance")
1115

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

1119
    This function figures out what logical volumes should belong on
1120
    which nodes, recursing through a device tree.
1121

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

1136
    """
1137
    if node_uuid is None:
1138
      node_uuid = self.primary_node
1139

    
1140
    if lvmap is None:
1141
      lvmap = {
1142
        node_uuid: [],
1143
        }
1144
      ret = lvmap
1145
    else:
1146
      if not node_uuid in lvmap:
1147
        lvmap[node_uuid] = []
1148
      ret = None
1149

    
1150
    if not devs:
1151
      devs = self.disks
1152

    
1153
    for dev in devs:
1154
      if dev.dev_type == constants.DT_PLAIN:
1155
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1156

    
1157
      elif dev.dev_type in constants.DTS_DRBD:
1158
        if dev.children:
1159
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1160
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1161

    
1162
      elif dev.children:
1163
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1164

    
1165
    return ret
1166

    
1167
  def FindDisk(self, idx):
1168
    """Find a disk given having a specified index.
1169

1170
    This is just a wrapper that does validation of the index.
1171

1172
    @type idx: int
1173
    @param idx: the disk index
1174
    @rtype: L{Disk}
1175
    @return: the corresponding disk
1176
    @raise errors.OpPrereqError: when the given index is not valid
1177

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

    
1190
  def ToDict(self):
1191
    """Instance-specific conversion to standard python types.
1192

1193
    This replaces the children lists of objects with lists of standard
1194
    python types.
1195

1196
    """
1197
    bo = super(Instance, self).ToDict()
1198

    
1199
    for attr in "nics", "disks":
1200
      alist = bo.get(attr, None)
1201
      if alist:
1202
        nlist = outils.ContainerToDicts(alist)
1203
      else:
1204
        nlist = []
1205
      bo[attr] = nlist
1206
    return bo
1207

    
1208
  @classmethod
1209
  def FromDict(cls, val):
1210
    """Custom function for instances.
1211

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

    
1225
  def UpgradeConfig(self):
1226
    """Fill defaults for missing configuration values.
1227

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

    
1245

    
1246
class OS(ConfigObject):
1247
  """Config object representing an operating system.
1248

1249
  @type supported_parameters: list
1250
  @ivar supported_parameters: a list of tuples, name and description,
1251
      containing the supported parameters by this OS
1252

1253
  @type VARIANT_DELIM: string
1254
  @cvar VARIANT_DELIM: the variant delimiter
1255

1256
  """
1257
  __slots__ = [
1258
    "name",
1259
    "path",
1260
    "api_versions",
1261
    "create_script",
1262
    "export_script",
1263
    "import_script",
1264
    "rename_script",
1265
    "verify_script",
1266
    "supported_variants",
1267
    "supported_parameters",
1268
    ]
1269

    
1270
  VARIANT_DELIM = "+"
1271

    
1272
  @classmethod
1273
  def SplitNameVariant(cls, name):
1274
    """Splits the name into the proper name and variant.
1275

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

1281
    """
1282
    nv = name.split(cls.VARIANT_DELIM, 1)
1283
    if len(nv) == 1:
1284
      nv.append("")
1285
    return nv
1286

    
1287
  @classmethod
1288
  def GetName(cls, name):
1289
    """Returns the proper name of the os (without the variant).
1290

1291
    @param name: the OS (unprocessed) name
1292

1293
    """
1294
    return cls.SplitNameVariant(name)[0]
1295

    
1296
  @classmethod
1297
  def GetVariant(cls, name):
1298
    """Returns the variant the os (without the base name).
1299

1300
    @param name: the OS (unprocessed) name
1301

1302
    """
1303
    return cls.SplitNameVariant(name)[1]
1304

    
1305

    
1306
class ExtStorage(ConfigObject):
1307
  """Config object representing an External Storage Provider.
1308

1309
  """
1310
  __slots__ = [
1311
    "name",
1312
    "path",
1313
    "create_script",
1314
    "remove_script",
1315
    "grow_script",
1316
    "attach_script",
1317
    "detach_script",
1318
    "setinfo_script",
1319
    "verify_script",
1320
    "supported_parameters",
1321
    ]
1322

    
1323

    
1324
class NodeHvState(ConfigObject):
1325
  """Hypvervisor state on a node.
1326

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

1336
  """
1337
  __slots__ = [
1338
    "mem_total",
1339
    "mem_node",
1340
    "mem_hv",
1341
    "mem_inst",
1342
    "cpu_total",
1343
    "cpu_node",
1344
    ] + _TIMESTAMPS
1345

    
1346

    
1347
class NodeDiskState(ConfigObject):
1348
  """Disk state on a node.
1349

1350
  """
1351
  __slots__ = [
1352
    "total",
1353
    "reserved",
1354
    "overhead",
1355
    ] + _TIMESTAMPS
1356

    
1357

    
1358
class Node(TaggableObject):
1359
  """Config object representing a node.
1360

1361
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1362
  @ivar hv_state_static: Hypervisor state overriden by user
1363
  @ivar disk_state: Disk state (e.g. free space)
1364
  @ivar disk_state_static: Disk state overriden by user
1365

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

    
1386
  def UpgradeConfig(self):
1387
    """Fill defaults for missing configuration values.
1388

1389
    """
1390
    # pylint: disable=E0203
1391
    # because these are "defined" via slots, not manually
1392
    if self.master_capable is None:
1393
      self.master_capable = True
1394

    
1395
    if self.vm_capable is None:
1396
      self.vm_capable = True
1397

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

    
1407
    if self.powered is None:
1408
      self.powered = True
1409

    
1410
  def ToDict(self):
1411
    """Custom function for serializing.
1412

1413
    """
1414
    data = super(Node, self).ToDict()
1415

    
1416
    hv_state = data.get("hv_state", None)
1417
    if hv_state is not None:
1418
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1419

    
1420
    disk_state = data.get("disk_state", None)
1421
    if disk_state is not None:
1422
      data["disk_state"] = \
1423
        dict((key, outils.ContainerToDicts(value))
1424
             for (key, value) in disk_state.items())
1425

    
1426
    return data
1427

    
1428
  @classmethod
1429
  def FromDict(cls, val):
1430
    """Custom function for deserializing.
1431

1432
    """
1433
    obj = super(Node, cls).FromDict(val)
1434

    
1435
    if obj.hv_state is not None:
1436
      obj.hv_state = \
1437
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1438

    
1439
    if obj.disk_state is not None:
1440
      obj.disk_state = \
1441
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1442
             for (key, value) in obj.disk_state.items())
1443

    
1444
    return obj
1445

    
1446

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

    
1462
  def ToDict(self):
1463
    """Custom function for nodegroup.
1464

1465
    This discards the members object, which gets recalculated and is only kept
1466
    in memory.
1467

1468
    """
1469
    mydict = super(NodeGroup, self).ToDict()
1470
    del mydict["members"]
1471
    return mydict
1472

    
1473
  @classmethod
1474
  def FromDict(cls, val):
1475
    """Custom function for nodegroup.
1476

1477
    The members slot is initialized to an empty list, upon deserialization.
1478

1479
    """
1480
    obj = super(NodeGroup, cls).FromDict(val)
1481
    obj.members = []
1482
    return obj
1483

    
1484
  def UpgradeConfig(self):
1485
    """Fill defaults for missing configuration values.
1486

1487
    """
1488
    if self.ndparams is None:
1489
      self.ndparams = {}
1490

    
1491
    if self.serial_no is None:
1492
      self.serial_no = 1
1493

    
1494
    if self.alloc_policy is None:
1495
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1496

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

    
1502
    if self.diskparams is None:
1503
      self.diskparams = {}
1504
    if self.ipolicy is None:
1505
      self.ipolicy = MakeEmptyIPolicy()
1506

    
1507
    if self.networks is None:
1508
      self.networks = {}
1509

    
1510
  def FillND(self, node):
1511
    """Return filled out ndparams for L{objects.Node}
1512

1513
    @type node: L{objects.Node}
1514
    @param node: A Node object to fill
1515
    @return a copy of the node's ndparams with defaults filled
1516

1517
    """
1518
    return self.SimpleFillND(node.ndparams)
1519

    
1520
  def SimpleFillND(self, ndparams):
1521
    """Fill a given ndparams dict with defaults.
1522

1523
    @type ndparams: dict
1524
    @param ndparams: the dict to fill
1525
    @rtype: dict
1526
    @return: a copy of the passed in ndparams with missing keys filled
1527
        from the node group defaults
1528

1529
    """
1530
    return FillDict(self.ndparams, ndparams)
1531

    
1532

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

    
1582
  def UpgradeConfig(self):
1583
    """Fill defaults for missing configuration values.
1584

1585
    """
1586
    # pylint: disable=E0203
1587
    # because these are "defined" via slots, not manually
1588
    if self.hvparams is None:
1589
      self.hvparams = constants.HVC_DEFAULTS
1590
    else:
1591
      for hypervisor in self.hvparams:
1592
        self.hvparams[hypervisor] = FillDict(
1593
            constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1594

    
1595
    if self.os_hvp is None:
1596
      self.os_hvp = {}
1597

    
1598
    # osparams added before 2.2
1599
    if self.osparams is None:
1600
      self.osparams = {}
1601

    
1602
    self.ndparams = UpgradeNDParams(self.ndparams)
1603

    
1604
    self.beparams = UpgradeGroupedParams(self.beparams,
1605
                                         constants.BEC_DEFAULTS)
1606
    for beparams_group in self.beparams:
1607
      UpgradeBeParams(self.beparams[beparams_group])
1608

    
1609
    migrate_default_bridge = not self.nicparams
1610
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1611
                                          constants.NICC_DEFAULTS)
1612
    if migrate_default_bridge:
1613
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1614
        self.default_bridge
1615

    
1616
    if self.modify_etc_hosts is None:
1617
      self.modify_etc_hosts = True
1618

    
1619
    if self.modify_ssh_setup is None:
1620
      self.modify_ssh_setup = True
1621

    
1622
    # default_bridge is no longer used in 2.1. The slot is left there to
1623
    # support auto-upgrading. It can be removed once we decide to deprecate
1624
    # upgrading straight from 2.0.
1625
    if self.default_bridge is not None:
1626
      self.default_bridge = None
1627

    
1628
    # default_hypervisor is just the first enabled one in 2.1. This slot and
1629
    # code can be removed once upgrading straight from 2.0 is deprecated.
1630
    if self.default_hypervisor is not None:
1631
      self.enabled_hypervisors = ([self.default_hypervisor] +
1632
                                  [hvname for hvname in self.enabled_hypervisors
1633
                                   if hvname != self.default_hypervisor])
1634
      self.default_hypervisor = None
1635

    
1636
    # maintain_node_health added after 2.1.1
1637
    if self.maintain_node_health is None:
1638
      self.maintain_node_health = False
1639

    
1640
    if self.uid_pool is None:
1641
      self.uid_pool = []
1642

    
1643
    if self.default_iallocator is None:
1644
      self.default_iallocator = ""
1645

    
1646
    if self.default_iallocator_params is None:
1647
      self.default_iallocator_params = {}
1648

    
1649
    # reserved_lvs added before 2.2
1650
    if self.reserved_lvs is None:
1651
      self.reserved_lvs = []
1652

    
1653
    # hidden and blacklisted operating systems added before 2.2.1
1654
    if self.hidden_os is None:
1655
      self.hidden_os = []
1656

    
1657
    if self.blacklisted_os is None:
1658
      self.blacklisted_os = []
1659

    
1660
    # primary_ip_family added before 2.3
1661
    if self.primary_ip_family is None:
1662
      self.primary_ip_family = AF_INET
1663

    
1664
    if self.master_netmask is None:
1665
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1666
      self.master_netmask = ipcls.iplen
1667

    
1668
    if self.prealloc_wipe_disks is None:
1669
      self.prealloc_wipe_disks = False
1670

    
1671
    # shared_file_storage_dir added before 2.5
1672
    if self.shared_file_storage_dir is None:
1673
      self.shared_file_storage_dir = ""
1674

    
1675
    # gluster_storage_dir added in 2.11
1676
    if self.gluster_storage_dir is None:
1677
      self.gluster_storage_dir = ""
1678

    
1679
    if self.use_external_mip_script is None:
1680
      self.use_external_mip_script = False
1681

    
1682
    if self.diskparams:
1683
      self.diskparams = UpgradeDiskParams(self.diskparams)
1684
    else:
1685
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1686

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

    
1702
    if self.candidate_certs is None:
1703
      self.candidate_certs = {}
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 FillNDGroup(self, nodegroup):
1897
    """Return filled out ndparams for just L{objects.NodeGroup}
1898

1899
    @type nodegroup: L{objects.NodeGroup}
1900
    @param nodegroup: A Node object to fill
1901
    @return a copy of the node group's ndparams with defaults filled
1902

1903
    """
1904
    return self.SimpleFillND(nodegroup.SimpleFillND({}))
1905

    
1906
  def SimpleFillND(self, ndparams):
1907
    """Fill a given ndparams dict with defaults.
1908

1909
    @type ndparams: dict
1910
    @param ndparams: the dict to fill
1911
    @rtype: dict
1912
    @return: a copy of the passed in ndparams with missing keys filled
1913
        from the cluster defaults
1914

1915
    """
1916
    return FillDict(self.ndparams, ndparams)
1917

    
1918
  def SimpleFillIPolicy(self, ipolicy):
1919
    """ Fill instance policy dict with defaults.
1920

1921
    @type ipolicy: dict
1922
    @param ipolicy: the dict to fill
1923
    @rtype: dict
1924
    @return: a copy of passed ipolicy with missing keys filled from
1925
      the cluster defaults
1926

1927
    """
1928
    return FillIPolicy(self.ipolicy, ipolicy)
1929

    
1930
  def IsDiskTemplateEnabled(self, disk_template):
1931
    """Checks if a particular disk template is enabled.
1932

1933
    """
1934
    return utils.storage.IsDiskTemplateEnabled(
1935
        disk_template, self.enabled_disk_templates)
1936

    
1937
  def IsFileStorageEnabled(self):
1938
    """Checks if file storage is enabled.
1939

1940
    """
1941
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1942

    
1943
  def IsSharedFileStorageEnabled(self):
1944
    """Checks if shared file storage is enabled.
1945

1946
    """
1947
    return utils.storage.IsSharedFileStorageEnabled(
1948
        self.enabled_disk_templates)
1949

    
1950

    
1951
class BlockDevStatus(ConfigObject):
1952
  """Config object representing the status of a block device."""
1953
  __slots__ = [
1954
    "dev_path",
1955
    "major",
1956
    "minor",
1957
    "sync_percent",
1958
    "estimated_time",
1959
    "is_degraded",
1960
    "ldisk_status",
1961
    ]
1962

    
1963

    
1964
class ImportExportStatus(ConfigObject):
1965
  """Config object representing the status of an import or export."""
1966
  __slots__ = [
1967
    "recent_output",
1968
    "listen_port",
1969
    "connected",
1970
    "progress_mbytes",
1971
    "progress_throughput",
1972
    "progress_eta",
1973
    "progress_percent",
1974
    "exit_status",
1975
    "error_message",
1976
    ] + _TIMESTAMPS
1977

    
1978

    
1979
class ImportExportOptions(ConfigObject):
1980
  """Options for import/export daemon
1981

1982
  @ivar key_name: X509 key name (None for cluster certificate)
1983
  @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1984
  @ivar compress: Compression method (one of L{constants.IEC_ALL})
1985
  @ivar magic: Used to ensure the connection goes to the right disk
1986
  @ivar ipv6: Whether to use IPv6
1987
  @ivar connect_timeout: Number of seconds for establishing connection
1988

1989
  """
1990
  __slots__ = [
1991
    "key_name",
1992
    "ca_pem",
1993
    "compress",
1994
    "magic",
1995
    "ipv6",
1996
    "connect_timeout",
1997
    ]
1998

    
1999

    
2000
class ConfdRequest(ConfigObject):
2001
  """Object holding a confd request.
2002

2003
  @ivar protocol: confd protocol version
2004
  @ivar type: confd query type
2005
  @ivar query: query request
2006
  @ivar rsalt: requested reply salt
2007

2008
  """
2009
  __slots__ = [
2010
    "protocol",
2011
    "type",
2012
    "query",
2013
    "rsalt",
2014
    ]
2015

    
2016

    
2017
class ConfdReply(ConfigObject):
2018
  """Object holding a confd reply.
2019

2020
  @ivar protocol: confd protocol version
2021
  @ivar status: reply status code (ok, error)
2022
  @ivar answer: confd query reply
2023
  @ivar serial: configuration serial number
2024

2025
  """
2026
  __slots__ = [
2027
    "protocol",
2028
    "status",
2029
    "answer",
2030
    "serial",
2031
    ]
2032

    
2033

    
2034
class QueryFieldDefinition(ConfigObject):
2035
  """Object holding a query field definition.
2036

2037
  @ivar name: Field name
2038
  @ivar title: Human-readable title
2039
  @ivar kind: Field type
2040
  @ivar doc: Human-readable description
2041

2042
  """
2043
  __slots__ = [
2044
    "name",
2045
    "title",
2046
    "kind",
2047
    "doc",
2048
    ]
2049

    
2050

    
2051
class _QueryResponseBase(ConfigObject):
2052
  __slots__ = [
2053
    "fields",
2054
    ]
2055

    
2056
  def ToDict(self):
2057
    """Custom function for serializing.
2058

2059
    """
2060
    mydict = super(_QueryResponseBase, self).ToDict()
2061
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2062
    return mydict
2063

    
2064
  @classmethod
2065
  def FromDict(cls, val):
2066
    """Custom function for de-serializing.
2067

2068
    """
2069
    obj = super(_QueryResponseBase, cls).FromDict(val)
2070
    obj.fields = \
2071
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2072
    return obj
2073

    
2074

    
2075
class QueryResponse(_QueryResponseBase):
2076
  """Object holding the response to a query.
2077

2078
  @ivar fields: List of L{QueryFieldDefinition} objects
2079
  @ivar data: Requested data
2080

2081
  """
2082
  __slots__ = [
2083
    "data",
2084
    ]
2085

    
2086

    
2087
class QueryFieldsRequest(ConfigObject):
2088
  """Object holding a request for querying available fields.
2089

2090
  """
2091
  __slots__ = [
2092
    "what",
2093
    "fields",
2094
    ]
2095

    
2096

    
2097
class QueryFieldsResponse(_QueryResponseBase):
2098
  """Object holding the response to a query for fields.
2099

2100
  @ivar fields: List of L{QueryFieldDefinition} objects
2101

2102
  """
2103
  __slots__ = []
2104

    
2105

    
2106
class MigrationStatus(ConfigObject):
2107
  """Object holding the status of a migration.
2108

2109
  """
2110
  __slots__ = [
2111
    "status",
2112
    "transferred_ram",
2113
    "total_ram",
2114
    ]
2115

    
2116

    
2117
class InstanceConsole(ConfigObject):
2118
  """Object describing how to access the console of an instance.
2119

2120
  """
2121
  __slots__ = [
2122
    "instance",
2123
    "kind",
2124
    "message",
2125
    "host",
2126
    "port",
2127
    "user",
2128
    "command",
2129
    "display",
2130
    ]
2131

    
2132
  def Validate(self):
2133
    """Validates contents of this object.
2134

2135
    """
2136
    assert self.kind in constants.CONS_ALL, "Unknown console type"
2137
    assert self.instance, "Missing instance name"
2138
    assert self.message or self.kind in [constants.CONS_SSH,
2139
                                         constants.CONS_SPICE,
2140
                                         constants.CONS_VNC]
2141
    assert self.host or self.kind == constants.CONS_MESSAGE
2142
    assert self.port or self.kind in [constants.CONS_MESSAGE,
2143
                                      constants.CONS_SSH]
2144
    assert self.user or self.kind in [constants.CONS_MESSAGE,
2145
                                      constants.CONS_SPICE,
2146
                                      constants.CONS_VNC]
2147
    assert self.command or self.kind in [constants.CONS_MESSAGE,
2148
                                         constants.CONS_SPICE,
2149
                                         constants.CONS_VNC]
2150
    assert self.display or self.kind in [constants.CONS_MESSAGE,
2151
                                         constants.CONS_SPICE,
2152
                                         constants.CONS_SSH]
2153
    return True
2154

    
2155

    
2156
class Network(TaggableObject):
2157
  """Object representing a network definition for ganeti.
2158

2159
  """
2160
  __slots__ = [
2161
    "name",
2162
    "serial_no",
2163
    "mac_prefix",
2164
    "network",
2165
    "network6",
2166
    "gateway",
2167
    "gateway6",
2168
    "reservations",
2169
    "ext_reservations",
2170
    ] + _TIMESTAMPS + _UUID
2171

    
2172
  def HooksDict(self, prefix=""):
2173
    """Export a dictionary used by hooks with a network's information.
2174

2175
    @type prefix: String
2176
    @param prefix: Prefix to prepend to the dict entries
2177

2178
    """
2179
    result = {
2180
      "%sNETWORK_NAME" % prefix: self.name,
2181
      "%sNETWORK_UUID" % prefix: self.uuid,
2182
      "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2183
    }
2184
    if self.network:
2185
      result["%sNETWORK_SUBNET" % prefix] = self.network
2186
    if self.gateway:
2187
      result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2188
    if self.network6:
2189
      result["%sNETWORK_SUBNET6" % prefix] = self.network6
2190
    if self.gateway6:
2191
      result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2192
    if self.mac_prefix:
2193
      result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2194

    
2195
    return result
2196

    
2197
  @classmethod
2198
  def FromDict(cls, val):
2199
    """Custom function for networks.
2200

2201
    Remove deprecated network_type and family.
2202

2203
    """
2204
    if "network_type" in val:
2205
      del val["network_type"]
2206
    if "family" in val:
2207
      del val["family"]
2208
    obj = super(Network, cls).FromDict(val)
2209
    return obj
2210

    
2211

    
2212
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2213
  """Simple wrapper over ConfigParse that allows serialization.
2214

2215
  This class is basically ConfigParser.SafeConfigParser with two
2216
  additional methods that allow it to serialize/unserialize to/from a
2217
  buffer.
2218

2219
  """
2220
  def Dumps(self):
2221
    """Dump this instance and return the string representation."""
2222
    buf = StringIO()
2223
    self.write(buf)
2224
    return buf.getvalue()
2225

    
2226
  @classmethod
2227
  def Loads(cls, data):
2228
    """Load data from a string."""
2229
    buf = StringIO(data)
2230
    cfp = cls()
2231
    cfp.readfp(buf)
2232
    return cfp
2233

    
2234

    
2235
class LvmPvInfo(ConfigObject):
2236
  """Information about an LVM physical volume (PV).
2237

2238
  @type name: string
2239
  @ivar name: name of the PV
2240
  @type vg_name: string
2241
  @ivar vg_name: name of the volume group containing the PV
2242
  @type size: float
2243
  @ivar size: size of the PV in MiB
2244
  @type free: float
2245
  @ivar free: free space in the PV, in MiB
2246
  @type attributes: string
2247
  @ivar attributes: PV attributes
2248
  @type lv_list: list of strings
2249
  @ivar lv_list: names of the LVs hosted on the PV
2250
  """
2251
  __slots__ = [
2252
    "name",
2253
    "vg_name",
2254
    "size",
2255
    "free",
2256
    "attributes",
2257
    "lv_list"
2258
    ]
2259

    
2260
  def IsEmpty(self):
2261
    """Is this PV empty?
2262

2263
    """
2264
    return self.size <= (self.free + 1)
2265

    
2266
  def IsAllocatable(self):
2267
    """Is this PV allocatable?
2268

2269
    """
2270
    return ("a" in self.attributes)