Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ df58ca1c

History | View | Annotate | Download (65.3 kB)

1
#
2
#
3

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

    
21

    
22
"""Transportable objects for Ganeti.
23

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

27
"""
28

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

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

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

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

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

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

    
51
from socket import AF_INET
52

    
53

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

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

    
60

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

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

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

    
84

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

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

    
98

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

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

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

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

    
111

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

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

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

    
128

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

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

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

    
142

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

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

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

    
157
  return result
158

    
159

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

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

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

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

    
178

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

182
  """
183
  return {}
184

    
185

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

189
  It has the following properties:
190

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

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

198
  """
199
  __slots__ = []
200

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

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

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

216
    """
217

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

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

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

    
235
  __getstate__ = ToDict
236

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

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

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

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

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

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

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

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

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

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

279
    """
280
    pass
281

    
282

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

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

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

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

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

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

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

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

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

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

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

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

341
    This replaces the tags set with a list.
342

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

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

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

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

    
361

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

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

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

    
380

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

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

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

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

    
405
    return mydict
406

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

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

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

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

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

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

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

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

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

    
485

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

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

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

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

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

    
509

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

639
    This only works for VG-based disks.
640

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
747
    self.dynamic_params = dyn_disk_params
748

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
841
  @staticmethod
842
  def ComputeLDParams(disk_template, disk_params):
843
    """Computes Logical Disk parameters from Disk Template parameters.
844

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

854
    """
855
    if disk_template not in constants.DISK_TEMPLATES:
856
      raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
857

    
858
    assert disk_template in disk_params
859

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

    
879
      # data LV
880
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
881
        constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
882
        }))
883

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

    
889
    elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
890
      result.append(constants.DISK_LD_DEFAULTS[disk_template])
891

    
892
    elif disk_template == constants.DT_PLAIN:
893
      result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.DT_PLAIN], {
894
        constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
895
        }))
896

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

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

    
906
    elif disk_template == constants.DT_EXT:
907
      result.append(constants.DISK_LD_DEFAULTS[constants.DT_EXT])
908

    
909
    return result
910

    
911

    
912
class InstancePolicy(ConfigObject):
913
  """Config object representing instance policy limits dictionary.
914

915
  Note that this object is not actually used in the config, it's just
916
  used as a placeholder for a few functions.
917

918
  """
919
  @classmethod
920
  def UpgradeDiskTemplates(cls, ipolicy, enabled_disk_templates):
921
    """Upgrades the ipolicy configuration."""
922
    if constants.IPOLICY_DTS in ipolicy:
923
      if not set(ipolicy[constants.IPOLICY_DTS]).issubset(
924
        set(enabled_disk_templates)):
925
        ipolicy[constants.IPOLICY_DTS] = list(
926
          set(ipolicy[constants.IPOLICY_DTS]) & set(enabled_disk_templates))
927

    
928
  @classmethod
929
  def CheckParameterSyntax(cls, ipolicy, check_std):
930
    """ Check the instance policy for validity.
931

932
    @type ipolicy: dict
933
    @param ipolicy: dictionary with min/max/std specs and policies
934
    @type check_std: bool
935
    @param check_std: Whether to check std value or just assume compliance
936
    @raise errors.ConfigurationError: when the policy is not legal
937

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

    
950
  @classmethod
951
  def _CheckIncompleteSpec(cls, spec, keyname):
952
    missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
953
    if missing_params:
954
      msg = ("Missing instance specs parameters for %s: %s" %
955
             (keyname, utils.CommaJoin(missing_params)))
956
      raise errors.ConfigurationError(msg)
957

    
958
  @classmethod
959
  def CheckISpecSyntax(cls, ipolicy, check_std):
960
    """Check the instance policy specs for validity.
961

962
    @type ipolicy: dict
963
    @param ipolicy: dictionary with min/max/std specs
964
    @type check_std: bool
965
    @param check_std: Whether to check std value or just assume compliance
966
    @raise errors.ConfigurationError: when specs are not valid
967

968
    """
969
    if constants.ISPECS_MINMAX not in ipolicy:
970
      # Nothing to check
971
      return
972

    
973
    if check_std and constants.ISPECS_STD not in ipolicy:
974
      msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
975
      raise errors.ConfigurationError(msg)
976
    stdspec = ipolicy.get(constants.ISPECS_STD)
977
    if check_std:
978
      InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
979

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

    
991
      spec_std_ok = True
992
      for param in constants.ISPECS_PARAMETERS:
993
        par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
994
                                                           param, check_std)
995
        spec_std_ok = spec_std_ok and par_std_ok
996
      std_is_good = std_is_good or spec_std_ok
997
    if not std_is_good:
998
      raise errors.ConfigurationError("Invalid std specifications")
999

    
1000
  @classmethod
1001
  def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
1002
    """Check the instance policy specs for validity on a given key.
1003

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

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

1021
    """
1022
    minspec = minmaxspecs[constants.ISPECS_MIN]
1023
    maxspec = minmaxspecs[constants.ISPECS_MAX]
1024
    min_v = minspec[name]
1025
    max_v = maxspec[name]
1026

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

    
1037
  @classmethod
1038
  def CheckDiskTemplates(cls, disk_templates):
1039
    """Checks the disk templates for validity.
1040

1041
    """
1042
    if not disk_templates:
1043
      raise errors.ConfigurationError("Instance policy must contain" +
1044
                                      " at least one disk template")
1045
    wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1046
    if wrong:
1047
      raise errors.ConfigurationError("Invalid disk template(s) %s" %
1048
                                      utils.CommaJoin(wrong))
1049

    
1050
  @classmethod
1051
  def CheckParameter(cls, key, value):
1052
    """Checks a parameter.
1053

1054
    Currently we expect all parameters to be float values.
1055

1056
    """
1057
    try:
1058
      float(value)
1059
    except (TypeError, ValueError), err:
1060
      raise errors.ConfigurationError("Invalid value for key" " '%s':"
1061
                                      " '%s', error: %s" % (key, value, err))
1062

    
1063

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

    
1083
  def _ComputeSecondaryNodes(self):
1084
    """Compute the list of secondary nodes.
1085

1086
    This is a simple wrapper over _ComputeAllNodes.
1087

1088
    """
1089
    all_nodes = set(self._ComputeAllNodes())
1090
    all_nodes.discard(self.primary_node)
1091
    return tuple(all_nodes)
1092

    
1093
  secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1094
                             "List of names of secondary nodes")
1095

    
1096
  def _ComputeAllNodes(self):
1097
    """Compute the list of all nodes.
1098

1099
    Since the data is already there (in the drbd disks), keeping it as
1100
    a separate normal attribute is redundant and if not properly
1101
    synchronised can cause problems. Thus it's better to compute it
1102
    dynamically.
1103

1104
    """
1105
    def _Helper(nodes, device):
1106
      """Recursively computes nodes given a top device."""
1107
      if device.dev_type in constants.DTS_DRBD:
1108
        nodea, nodeb = device.logical_id[:2]
1109
        nodes.add(nodea)
1110
        nodes.add(nodeb)
1111
      if device.children:
1112
        for child in device.children:
1113
          _Helper(nodes, child)
1114

    
1115
    all_nodes = set()
1116
    all_nodes.add(self.primary_node)
1117
    for device in self.disks:
1118
      _Helper(all_nodes, device)
1119
    return tuple(all_nodes)
1120

    
1121
  all_nodes = property(_ComputeAllNodes, None, None,
1122
                       "List of names of all the nodes of the instance")
1123

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

1127
    This function figures out what logical volumes should belong on
1128
    which nodes, recursing through a device tree.
1129

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

1144
    """
1145
    if node_uuid is None:
1146
      node_uuid = self.primary_node
1147

    
1148
    if lvmap is None:
1149
      lvmap = {
1150
        node_uuid: [],
1151
        }
1152
      ret = lvmap
1153
    else:
1154
      if not node_uuid in lvmap:
1155
        lvmap[node_uuid] = []
1156
      ret = None
1157

    
1158
    if not devs:
1159
      devs = self.disks
1160

    
1161
    for dev in devs:
1162
      if dev.dev_type == constants.DT_PLAIN:
1163
        lvmap[node_uuid].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1164

    
1165
      elif dev.dev_type in constants.DTS_DRBD:
1166
        if dev.children:
1167
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1168
          self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1169

    
1170
      elif dev.children:
1171
        self.MapLVsByNode(lvmap, dev.children, node_uuid)
1172

    
1173
    return ret
1174

    
1175
  def FindDisk(self, idx):
1176
    """Find a disk given having a specified index.
1177

1178
    This is just a wrapper that does validation of the index.
1179

1180
    @type idx: int
1181
    @param idx: the disk index
1182
    @rtype: L{Disk}
1183
    @return: the corresponding disk
1184
    @raise errors.OpPrereqError: when the given index is not valid
1185

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

    
1198
  def ToDict(self):
1199
    """Instance-specific conversion to standard python types.
1200

1201
    This replaces the children lists of objects with lists of standard
1202
    python types.
1203

1204
    """
1205
    bo = super(Instance, self).ToDict()
1206

    
1207
    for attr in "nics", "disks":
1208
      alist = bo.get(attr, None)
1209
      if alist:
1210
        nlist = outils.ContainerToDicts(alist)
1211
      else:
1212
        nlist = []
1213
      bo[attr] = nlist
1214
    return bo
1215

    
1216
  @classmethod
1217
  def FromDict(cls, val):
1218
    """Custom function for instances.
1219

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

    
1233
  def UpgradeConfig(self):
1234
    """Fill defaults for missing configuration values.
1235

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

    
1253

    
1254
class OS(ConfigObject):
1255
  """Config object representing an operating system.
1256

1257
  @type supported_parameters: list
1258
  @ivar supported_parameters: a list of tuples, name and description,
1259
      containing the supported parameters by this OS
1260

1261
  @type VARIANT_DELIM: string
1262
  @cvar VARIANT_DELIM: the variant delimiter
1263

1264
  """
1265
  __slots__ = [
1266
    "name",
1267
    "path",
1268
    "api_versions",
1269
    "create_script",
1270
    "export_script",
1271
    "import_script",
1272
    "rename_script",
1273
    "verify_script",
1274
    "supported_variants",
1275
    "supported_parameters",
1276
    ]
1277

    
1278
  VARIANT_DELIM = "+"
1279

    
1280
  @classmethod
1281
  def SplitNameVariant(cls, name):
1282
    """Splits the name into the proper name and variant.
1283

1284
    @param name: the OS (unprocessed) name
1285
    @rtype: list
1286
    @return: a list of two elements; if the original name didn't
1287
        contain a variant, it's returned as an empty string
1288

1289
    """
1290
    nv = name.split(cls.VARIANT_DELIM, 1)
1291
    if len(nv) == 1:
1292
      nv.append("")
1293
    return nv
1294

    
1295
  @classmethod
1296
  def GetName(cls, name):
1297
    """Returns the proper name of the os (without the variant).
1298

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

1301
    """
1302
    return cls.SplitNameVariant(name)[0]
1303

    
1304
  @classmethod
1305
  def GetVariant(cls, name):
1306
    """Returns the variant the os (without the base name).
1307

1308
    @param name: the OS (unprocessed) name
1309

1310
    """
1311
    return cls.SplitNameVariant(name)[1]
1312

    
1313

    
1314
class ExtStorage(ConfigObject):
1315
  """Config object representing an External Storage Provider.
1316

1317
  """
1318
  __slots__ = [
1319
    "name",
1320
    "path",
1321
    "create_script",
1322
    "remove_script",
1323
    "grow_script",
1324
    "attach_script",
1325
    "detach_script",
1326
    "setinfo_script",
1327
    "verify_script",
1328
    "supported_parameters",
1329
    ]
1330

    
1331

    
1332
class NodeHvState(ConfigObject):
1333
  """Hypvervisor state on a node.
1334

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

1344
  """
1345
  __slots__ = [
1346
    "mem_total",
1347
    "mem_node",
1348
    "mem_hv",
1349
    "mem_inst",
1350
    "cpu_total",
1351
    "cpu_node",
1352
    ] + _TIMESTAMPS
1353

    
1354

    
1355
class NodeDiskState(ConfigObject):
1356
  """Disk state on a node.
1357

1358
  """
1359
  __slots__ = [
1360
    "total",
1361
    "reserved",
1362
    "overhead",
1363
    ] + _TIMESTAMPS
1364

    
1365

    
1366
class Node(TaggableObject):
1367
  """Config object representing a node.
1368

1369
  @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1370
  @ivar hv_state_static: Hypervisor state overriden by user
1371
  @ivar disk_state: Disk state (e.g. free space)
1372
  @ivar disk_state_static: Disk state overriden by user
1373

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

    
1394
  def UpgradeConfig(self):
1395
    """Fill defaults for missing configuration values.
1396

1397
    """
1398
    # pylint: disable=E0203
1399
    # because these are "defined" via slots, not manually
1400
    if self.master_capable is None:
1401
      self.master_capable = True
1402

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

    
1406
    if self.ndparams is None:
1407
      self.ndparams = {}
1408
    # And remove any global parameter
1409
    for key in constants.NDC_GLOBALS:
1410
      if key in self.ndparams:
1411
        logging.warning("Ignoring %s node parameter for node %s",
1412
                        key, self.name)
1413
        del self.ndparams[key]
1414

    
1415
    if self.powered is None:
1416
      self.powered = True
1417

    
1418
  def ToDict(self):
1419
    """Custom function for serializing.
1420

1421
    """
1422
    data = super(Node, self).ToDict()
1423

    
1424
    hv_state = data.get("hv_state", None)
1425
    if hv_state is not None:
1426
      data["hv_state"] = outils.ContainerToDicts(hv_state)
1427

    
1428
    disk_state = data.get("disk_state", None)
1429
    if disk_state is not None:
1430
      data["disk_state"] = \
1431
        dict((key, outils.ContainerToDicts(value))
1432
             for (key, value) in disk_state.items())
1433

    
1434
    return data
1435

    
1436
  @classmethod
1437
  def FromDict(cls, val):
1438
    """Custom function for deserializing.
1439

1440
    """
1441
    obj = super(Node, cls).FromDict(val)
1442

    
1443
    if obj.hv_state is not None:
1444
      obj.hv_state = \
1445
        outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1446

    
1447
    if obj.disk_state is not None:
1448
      obj.disk_state = \
1449
        dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1450
             for (key, value) in obj.disk_state.items())
1451

    
1452
    return obj
1453

    
1454

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

    
1470
  def ToDict(self):
1471
    """Custom function for nodegroup.
1472

1473
    This discards the members object, which gets recalculated and is only kept
1474
    in memory.
1475

1476
    """
1477
    mydict = super(NodeGroup, self).ToDict()
1478
    del mydict["members"]
1479
    return mydict
1480

    
1481
  @classmethod
1482
  def FromDict(cls, val):
1483
    """Custom function for nodegroup.
1484

1485
    The members slot is initialized to an empty list, upon deserialization.
1486

1487
    """
1488
    obj = super(NodeGroup, cls).FromDict(val)
1489
    obj.members = []
1490
    return obj
1491

    
1492
  def UpgradeConfig(self):
1493
    """Fill defaults for missing configuration values.
1494

1495
    """
1496
    if self.ndparams is None:
1497
      self.ndparams = {}
1498

    
1499
    if self.serial_no is None:
1500
      self.serial_no = 1
1501

    
1502
    if self.alloc_policy is None:
1503
      self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1504

    
1505
    # We only update mtime, and not ctime, since we would not be able
1506
    # to provide a correct value for creation time.
1507
    if self.mtime is None:
1508
      self.mtime = time.time()
1509

    
1510
    if self.diskparams is None:
1511
      self.diskparams = {}
1512
    if self.ipolicy is None:
1513
      self.ipolicy = MakeEmptyIPolicy()
1514

    
1515
    if self.networks is None:
1516
      self.networks = {}
1517

    
1518
  def FillND(self, node):
1519
    """Return filled out ndparams for L{objects.Node}
1520

1521
    @type node: L{objects.Node}
1522
    @param node: A Node object to fill
1523
    @return a copy of the node's ndparams with defaults filled
1524

1525
    """
1526
    return self.SimpleFillND(node.ndparams)
1527

    
1528
  def SimpleFillND(self, ndparams):
1529
    """Fill a given ndparams dict with defaults.
1530

1531
    @type ndparams: dict
1532
    @param ndparams: the dict to fill
1533
    @rtype: dict
1534
    @return: a copy of the passed in ndparams with missing keys filled
1535
        from the node group defaults
1536

1537
    """
1538
    return FillDict(self.ndparams, ndparams)
1539

    
1540

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

    
1587
  def UpgradeConfig(self):
1588
    """Fill defaults for missing configuration values.
1589

1590
    """
1591
    # pylint: disable=E0203
1592
    # because these are "defined" via slots, not manually
1593
    if self.hvparams is None:
1594
      self.hvparams = constants.HVC_DEFAULTS
1595
    else:
1596
      for hypervisor in self.hvparams:
1597
        self.hvparams[hypervisor] = FillDict(
1598
            constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1599

    
1600
    if self.os_hvp is None:
1601
      self.os_hvp = {}
1602

    
1603
    # osparams added before 2.2
1604
    if self.osparams is None:
1605
      self.osparams = {}
1606

    
1607
    self.ndparams = UpgradeNDParams(self.ndparams)
1608

    
1609
    self.beparams = UpgradeGroupedParams(self.beparams,
1610
                                         constants.BEC_DEFAULTS)
1611
    for beparams_group in self.beparams:
1612
      UpgradeBeParams(self.beparams[beparams_group])
1613

    
1614
    migrate_default_bridge = not self.nicparams
1615
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1616
                                          constants.NICC_DEFAULTS)
1617
    if migrate_default_bridge:
1618
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1619
        self.default_bridge
1620

    
1621
    if self.modify_etc_hosts is None:
1622
      self.modify_etc_hosts = True
1623

    
1624
    if self.modify_ssh_setup is None:
1625
      self.modify_ssh_setup = True
1626

    
1627
    # default_bridge is no longer used in 2.1. The slot is left there to
1628
    # support auto-upgrading. It can be removed once we decide to deprecate
1629
    # upgrading straight from 2.0.
1630
    if self.default_bridge is not None:
1631
      self.default_bridge = None
1632

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

    
1641
    # maintain_node_health added after 2.1.1
1642
    if self.maintain_node_health is None:
1643
      self.maintain_node_health = False
1644

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

    
1648
    if self.default_iallocator is None:
1649
      self.default_iallocator = ""
1650

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

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

    
1659
    if self.blacklisted_os is None:
1660
      self.blacklisted_os = []
1661

    
1662
    # primary_ip_family added before 2.3
1663
    if self.primary_ip_family is None:
1664
      self.primary_ip_family = AF_INET
1665

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

    
1670
    if self.prealloc_wipe_disks is None:
1671
      self.prealloc_wipe_disks = False
1672

    
1673
    # shared_file_storage_dir added before 2.5
1674
    if self.shared_file_storage_dir is None:
1675
      self.shared_file_storage_dir = ""
1676

    
1677
    if self.use_external_mip_script is None:
1678
      self.use_external_mip_script = False
1679

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

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

    
1700
  @property
1701
  def primary_hypervisor(self):
1702
    """The first hypervisor is the primary.
1703

1704
    Useful, for example, for L{Node}'s hv/disk state.
1705

1706
    """
1707
    return self.enabled_hypervisors[0]
1708

    
1709
  def ToDict(self):
1710
    """Custom function for cluster.
1711

1712
    """
1713
    mydict = super(Cluster, self).ToDict()
1714

    
1715
    if self.tcpudp_port_pool is None:
1716
      tcpudp_port_pool = []
1717
    else:
1718
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1719

    
1720
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1721

    
1722
    return mydict
1723

    
1724
  @classmethod
1725
  def FromDict(cls, val):
1726
    """Custom function for cluster.
1727

1728
    """
1729
    obj = super(Cluster, cls).FromDict(val)
1730

    
1731
    if obj.tcpudp_port_pool is None:
1732
      obj.tcpudp_port_pool = set()
1733
    elif not isinstance(obj.tcpudp_port_pool, set):
1734
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1735

    
1736
    return obj
1737

    
1738
  def SimpleFillDP(self, diskparams):
1739
    """Fill a given diskparams dict with cluster defaults.
1740

1741
    @param diskparams: The diskparams
1742
    @return: The defaults dict
1743

1744
    """
1745
    return FillDiskParams(self.diskparams, diskparams)
1746

    
1747
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1748
    """Get the default hypervisor parameters for the cluster.
1749

1750
    @param hypervisor: the hypervisor name
1751
    @param os_name: if specified, we'll also update the defaults for this OS
1752
    @param skip_keys: if passed, list of keys not to use
1753
    @return: the defaults dict
1754

1755
    """
1756
    if skip_keys is None:
1757
      skip_keys = []
1758

    
1759
    fill_stack = [self.hvparams.get(hypervisor, {})]
1760
    if os_name is not None:
1761
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1762
      fill_stack.append(os_hvp)
1763

    
1764
    ret_dict = {}
1765
    for o_dict in fill_stack:
1766
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1767

    
1768
    return ret_dict
1769

    
1770
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1771
    """Fill a given hvparams dict with cluster defaults.
1772

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

1784
    """
1785
    if skip_globals:
1786
      skip_keys = constants.HVC_GLOBALS
1787
    else:
1788
      skip_keys = []
1789

    
1790
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1791
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1792

    
1793
  def FillHV(self, instance, skip_globals=False):
1794
    """Fill an instance's hvparams dict with cluster defaults.
1795

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

1805
    """
1806
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1807
                             instance.hvparams, skip_globals)
1808

    
1809
  def SimpleFillBE(self, beparams):
1810
    """Fill a given beparams dict with cluster defaults.
1811

1812
    @type beparams: dict
1813
    @param beparams: the dict to fill
1814
    @rtype: dict
1815
    @return: a copy of the passed in beparams with missing keys filled
1816
        from the cluster defaults
1817

1818
    """
1819
    return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1820

    
1821
  def FillBE(self, instance):
1822
    """Fill an instance's beparams dict with cluster defaults.
1823

1824
    @type instance: L{objects.Instance}
1825
    @param instance: the instance parameter to fill
1826
    @rtype: dict
1827
    @return: a copy of the instance's beparams with missing keys filled from
1828
        the cluster defaults
1829

1830
    """
1831
    return self.SimpleFillBE(instance.beparams)
1832

    
1833
  def SimpleFillNIC(self, nicparams):
1834
    """Fill a given nicparams dict with cluster defaults.
1835

1836
    @type nicparams: dict
1837
    @param nicparams: the dict to fill
1838
    @rtype: dict
1839
    @return: a copy of the passed in nicparams with missing keys filled
1840
        from the cluster defaults
1841

1842
    """
1843
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1844

    
1845
  def SimpleFillOS(self, os_name, os_params):
1846
    """Fill an instance's osparams dict with cluster defaults.
1847

1848
    @type os_name: string
1849
    @param os_name: the OS name to use
1850
    @type os_params: dict
1851
    @param os_params: the dict to fill with default values
1852
    @rtype: dict
1853
    @return: a copy of the instance's osparams with missing keys filled from
1854
        the cluster defaults
1855

1856
    """
1857
    name_only = os_name.split("+", 1)[0]
1858
    # base OS
1859
    result = self.osparams.get(name_only, {})
1860
    # OS with variant
1861
    result = FillDict(result, self.osparams.get(os_name, {}))
1862
    # specified params
1863
    return FillDict(result, os_params)
1864

    
1865
  @staticmethod
1866
  def SimpleFillHvState(hv_state):
1867
    """Fill an hv_state sub dict with cluster defaults.
1868

1869
    """
1870
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1871

    
1872
  @staticmethod
1873
  def SimpleFillDiskState(disk_state):
1874
    """Fill an disk_state sub dict with cluster defaults.
1875

1876
    """
1877
    return FillDict(constants.DS_DEFAULTS, disk_state)
1878

    
1879
  def FillND(self, node, nodegroup):
1880
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1881

1882
    @type node: L{objects.Node}
1883
    @param node: A Node object to fill
1884
    @type nodegroup: L{objects.NodeGroup}
1885
    @param nodegroup: A Node object to fill
1886
    @return a copy of the node's ndparams with defaults filled
1887

1888
    """
1889
    return self.SimpleFillND(nodegroup.FillND(node))
1890

    
1891
  def SimpleFillND(self, ndparams):
1892
    """Fill a given ndparams dict with defaults.
1893

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

1900
    """
1901
    return FillDict(self.ndparams, ndparams)
1902

    
1903
  def SimpleFillIPolicy(self, ipolicy):
1904
    """ Fill instance policy dict with defaults.
1905

1906
    @type ipolicy: dict
1907
    @param ipolicy: the dict to fill
1908
    @rtype: dict
1909
    @return: a copy of passed ipolicy with missing keys filled from
1910
      the cluster defaults
1911

1912
    """
1913
    return FillIPolicy(self.ipolicy, ipolicy)
1914

    
1915
  def IsDiskTemplateEnabled(self, disk_template):
1916
    """Checks if a particular disk template is enabled.
1917

1918
    """
1919
    return utils.storage.IsDiskTemplateEnabled(
1920
        disk_template, self.enabled_disk_templates)
1921

    
1922
  def IsFileStorageEnabled(self):
1923
    """Checks if file storage is enabled.
1924

1925
    """
1926
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1927

    
1928
  def IsSharedFileStorageEnabled(self):
1929
    """Checks if shared file storage is enabled.
1930

1931
    """
1932
    return utils.storage.IsSharedFileStorageEnabled(
1933
        self.enabled_disk_templates)
1934

    
1935

    
1936
class BlockDevStatus(ConfigObject):
1937
  """Config object representing the status of a block device."""
1938
  __slots__ = [
1939
    "dev_path",
1940
    "major",
1941
    "minor",
1942
    "sync_percent",
1943
    "estimated_time",
1944
    "is_degraded",
1945
    "ldisk_status",
1946
    ]
1947

    
1948

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

    
1963

    
1964
class ImportExportOptions(ConfigObject):
1965
  """Options for import/export daemon
1966

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

1974
  """
1975
  __slots__ = [
1976
    "key_name",
1977
    "ca_pem",
1978
    "compress",
1979
    "magic",
1980
    "ipv6",
1981
    "connect_timeout",
1982
    ]
1983

    
1984

    
1985
class ConfdRequest(ConfigObject):
1986
  """Object holding a confd request.
1987

1988
  @ivar protocol: confd protocol version
1989
  @ivar type: confd query type
1990
  @ivar query: query request
1991
  @ivar rsalt: requested reply salt
1992

1993
  """
1994
  __slots__ = [
1995
    "protocol",
1996
    "type",
1997
    "query",
1998
    "rsalt",
1999
    ]
2000

    
2001

    
2002
class ConfdReply(ConfigObject):
2003
  """Object holding a confd reply.
2004

2005
  @ivar protocol: confd protocol version
2006
  @ivar status: reply status code (ok, error)
2007
  @ivar answer: confd query reply
2008
  @ivar serial: configuration serial number
2009

2010
  """
2011
  __slots__ = [
2012
    "protocol",
2013
    "status",
2014
    "answer",
2015
    "serial",
2016
    ]
2017

    
2018

    
2019
class QueryFieldDefinition(ConfigObject):
2020
  """Object holding a query field definition.
2021

2022
  @ivar name: Field name
2023
  @ivar title: Human-readable title
2024
  @ivar kind: Field type
2025
  @ivar doc: Human-readable description
2026

2027
  """
2028
  __slots__ = [
2029
    "name",
2030
    "title",
2031
    "kind",
2032
    "doc",
2033
    ]
2034

    
2035

    
2036
class _QueryResponseBase(ConfigObject):
2037
  __slots__ = [
2038
    "fields",
2039
    ]
2040

    
2041
  def ToDict(self):
2042
    """Custom function for serializing.
2043

2044
    """
2045
    mydict = super(_QueryResponseBase, self).ToDict()
2046
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2047
    return mydict
2048

    
2049
  @classmethod
2050
  def FromDict(cls, val):
2051
    """Custom function for de-serializing.
2052

2053
    """
2054
    obj = super(_QueryResponseBase, cls).FromDict(val)
2055
    obj.fields = \
2056
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2057
    return obj
2058

    
2059

    
2060
class QueryResponse(_QueryResponseBase):
2061
  """Object holding the response to a query.
2062

2063
  @ivar fields: List of L{QueryFieldDefinition} objects
2064
  @ivar data: Requested data
2065

2066
  """
2067
  __slots__ = [
2068
    "data",
2069
    ]
2070

    
2071

    
2072
class QueryFieldsRequest(ConfigObject):
2073
  """Object holding a request for querying available fields.
2074

2075
  """
2076
  __slots__ = [
2077
    "what",
2078
    "fields",
2079
    ]
2080

    
2081

    
2082
class QueryFieldsResponse(_QueryResponseBase):
2083
  """Object holding the response to a query for fields.
2084

2085
  @ivar fields: List of L{QueryFieldDefinition} objects
2086

2087
  """
2088
  __slots__ = []
2089

    
2090

    
2091
class MigrationStatus(ConfigObject):
2092
  """Object holding the status of a migration.
2093

2094
  """
2095
  __slots__ = [
2096
    "status",
2097
    "transferred_ram",
2098
    "total_ram",
2099
    ]
2100

    
2101

    
2102
class InstanceConsole(ConfigObject):
2103
  """Object describing how to access the console of an instance.
2104

2105
  """
2106
  __slots__ = [
2107
    "instance",
2108
    "kind",
2109
    "message",
2110
    "host",
2111
    "port",
2112
    "user",
2113
    "command",
2114
    "display",
2115
    ]
2116

    
2117
  def Validate(self):
2118
    """Validates contents of this object.
2119

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

    
2140

    
2141
class Network(TaggableObject):
2142
  """Object representing a network definition for ganeti.
2143

2144
  """
2145
  __slots__ = [
2146
    "name",
2147
    "serial_no",
2148
    "mac_prefix",
2149
    "network",
2150
    "network6",
2151
    "gateway",
2152
    "gateway6",
2153
    "reservations",
2154
    "ext_reservations",
2155
    ] + _TIMESTAMPS + _UUID
2156

    
2157
  def HooksDict(self, prefix=""):
2158
    """Export a dictionary used by hooks with a network's information.
2159

2160
    @type prefix: String
2161
    @param prefix: Prefix to prepend to the dict entries
2162

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

    
2180
    return result
2181

    
2182
  @classmethod
2183
  def FromDict(cls, val):
2184
    """Custom function for networks.
2185

2186
    Remove deprecated network_type and family.
2187

2188
    """
2189
    if "network_type" in val:
2190
      del val["network_type"]
2191
    if "family" in val:
2192
      del val["family"]
2193
    obj = super(Network, cls).FromDict(val)
2194
    return obj
2195

    
2196

    
2197
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2198
  """Simple wrapper over ConfigParse that allows serialization.
2199

2200
  This class is basically ConfigParser.SafeConfigParser with two
2201
  additional methods that allow it to serialize/unserialize to/from a
2202
  buffer.
2203

2204
  """
2205
  def Dumps(self):
2206
    """Dump this instance and return the string representation."""
2207
    buf = StringIO()
2208
    self.write(buf)
2209
    return buf.getvalue()
2210

    
2211
  @classmethod
2212
  def Loads(cls, data):
2213
    """Load data from a string."""
2214
    buf = StringIO(data)
2215
    cfp = cls()
2216
    cfp.readfp(buf)
2217
    return cfp
2218

    
2219

    
2220
class LvmPvInfo(ConfigObject):
2221
  """Information about an LVM physical volume (PV).
2222

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

    
2245
  def IsEmpty(self):
2246
    """Is this PV empty?
2247

2248
    """
2249
    return self.size <= (self.free + 1)
2250

    
2251
  def IsAllocatable(self):
2252
    """Is this PV allocatable?
2253

2254
    """
2255
    return ("a" in self.attributes)