Statistics
| Branch: | Tag: | Revision:

root / lib / objects.py @ f2a3c4f0

History | View | Annotate | Download (65.8 kB)

1
#
2
#
3

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

    
21

    
22
"""Transportable objects for Ganeti.
23

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

27
"""
28

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

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

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

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

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

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

    
51
from socket import AF_INET
52

    
53

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

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

    
60

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

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

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

    
84

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

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

    
98

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

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

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

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

    
111

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

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

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

    
128

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

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

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

    
142

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

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

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

    
157
  return result
158

    
159

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

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

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

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

    
178

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

182
  """
183
  return {}
184

    
185

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

189
  It has the following properties:
190

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

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

198
  """
199
  __slots__ = []
200

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

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

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

216
    """
217

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

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

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

    
235
  __getstate__ = ToDict
236

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

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

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

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

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

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

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

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

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

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

279
    """
280
    pass
281

    
282

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

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

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

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

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

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

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

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

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

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

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

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

341
    This replaces the tags set with a list.
342

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

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

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

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

    
361

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

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

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

    
380

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

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

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

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

    
405
    return mydict
406

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

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

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

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

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

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

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

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

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

    
485

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

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

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

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

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

    
509

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

639
    This only works for VG-based disks.
640

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
747
    self.dynamic_params = dyn_disk_params
748

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
838
    # add here config upgrade for this disk
839

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

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

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

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

    
863
    assert disk_template in disk_params
864

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

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

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

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

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

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

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

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

    
914
    return result
915

    
916

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1068

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

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

1091
    This is a simple wrapper over _ComputeAllNodes.
1092

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

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

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

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

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

    
1120
    all_nodes = set()
1121
    for device in self.disks:
1122
      _Helper(all_nodes, device)
1123
    # ensure that the primary node is always the first
1124
    all_nodes.discard(self.primary_node)
1125
    return (self.primary_node, ) + tuple(all_nodes)
1126

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

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

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

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

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

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

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

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

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

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

    
1179
    return ret
1180

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

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

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

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

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

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

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

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

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

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

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

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

    
1259

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

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

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

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

    
1284
  VARIANT_DELIM = "+"
1285

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

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

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

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

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

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

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

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

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

    
1319

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

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

    
1337

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

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

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

    
1360

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

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

    
1371

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

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

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

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

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

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

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

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

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

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

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

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

    
1440
    return data
1441

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

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

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

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

    
1458
    return obj
1459

    
1460

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1546

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

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

1596
    """
1597
    # pylint: disable=E0203
1598
    # because these are "defined" via slots, not manually
1599
    if self.hvparams is None:
1600
      self.hvparams = constants.HVC_DEFAULTS
1601
    else:
1602
      for hypervisor in constants.HYPER_TYPES:
1603
        try:
1604
          existing_params = self.hvparams[hypervisor]
1605
        except KeyError:
1606
          existing_params = {}
1607
        self.hvparams[hypervisor] = FillDict(
1608
            constants.HVC_DEFAULTS[hypervisor], existing_params)
1609

    
1610
    if self.os_hvp is None:
1611
      self.os_hvp = {}
1612

    
1613
    # osparams added before 2.2
1614
    if self.osparams is None:
1615
      self.osparams = {}
1616

    
1617
    self.ndparams = UpgradeNDParams(self.ndparams)
1618

    
1619
    self.beparams = UpgradeGroupedParams(self.beparams,
1620
                                         constants.BEC_DEFAULTS)
1621
    for beparams_group in self.beparams:
1622
      UpgradeBeParams(self.beparams[beparams_group])
1623

    
1624
    migrate_default_bridge = not self.nicparams
1625
    self.nicparams = UpgradeGroupedParams(self.nicparams,
1626
                                          constants.NICC_DEFAULTS)
1627
    if migrate_default_bridge:
1628
      self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1629
        self.default_bridge
1630

    
1631
    if self.modify_etc_hosts is None:
1632
      self.modify_etc_hosts = True
1633

    
1634
    if self.modify_ssh_setup is None:
1635
      self.modify_ssh_setup = True
1636

    
1637
    # default_bridge is no longer used in 2.1. The slot is left there to
1638
    # support auto-upgrading. It can be removed once we decide to deprecate
1639
    # upgrading straight from 2.0.
1640
    if self.default_bridge is not None:
1641
      self.default_bridge = None
1642

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

    
1651
    # maintain_node_health added after 2.1.1
1652
    if self.maintain_node_health is None:
1653
      self.maintain_node_health = False
1654

    
1655
    if self.uid_pool is None:
1656
      self.uid_pool = []
1657

    
1658
    if self.default_iallocator is None:
1659
      self.default_iallocator = ""
1660

    
1661
    # reserved_lvs added before 2.2
1662
    if self.reserved_lvs is None:
1663
      self.reserved_lvs = []
1664

    
1665
    # hidden and blacklisted operating systems added before 2.2.1
1666
    if self.hidden_os is None:
1667
      self.hidden_os = []
1668

    
1669
    if self.blacklisted_os is None:
1670
      self.blacklisted_os = []
1671

    
1672
    # primary_ip_family added before 2.3
1673
    if self.primary_ip_family is None:
1674
      self.primary_ip_family = AF_INET
1675

    
1676
    if self.master_netmask is None:
1677
      ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1678
      self.master_netmask = ipcls.iplen
1679

    
1680
    if self.prealloc_wipe_disks is None:
1681
      self.prealloc_wipe_disks = False
1682

    
1683
    # shared_file_storage_dir added before 2.5
1684
    if self.shared_file_storage_dir is None:
1685
      self.shared_file_storage_dir = ""
1686

    
1687
    if self.use_external_mip_script is None:
1688
      self.use_external_mip_script = False
1689

    
1690
    if self.diskparams:
1691
      self.diskparams = UpgradeDiskParams(self.diskparams)
1692
    else:
1693
      self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1694

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

    
1710
  @property
1711
  def primary_hypervisor(self):
1712
    """The first hypervisor is the primary.
1713

1714
    Useful, for example, for L{Node}'s hv/disk state.
1715

1716
    """
1717
    return self.enabled_hypervisors[0]
1718

    
1719
  def ToDict(self):
1720
    """Custom function for cluster.
1721

1722
    """
1723
    mydict = super(Cluster, self).ToDict()
1724

    
1725
    if self.tcpudp_port_pool is None:
1726
      tcpudp_port_pool = []
1727
    else:
1728
      tcpudp_port_pool = list(self.tcpudp_port_pool)
1729

    
1730
    mydict["tcpudp_port_pool"] = tcpudp_port_pool
1731

    
1732
    return mydict
1733

    
1734
  @classmethod
1735
  def FromDict(cls, val):
1736
    """Custom function for cluster.
1737

1738
    """
1739
    obj = super(Cluster, cls).FromDict(val)
1740

    
1741
    if obj.tcpudp_port_pool is None:
1742
      obj.tcpudp_port_pool = set()
1743
    elif not isinstance(obj.tcpudp_port_pool, set):
1744
      obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1745

    
1746
    return obj
1747

    
1748
  def SimpleFillDP(self, diskparams):
1749
    """Fill a given diskparams dict with cluster defaults.
1750

1751
    @param diskparams: The diskparams
1752
    @return: The defaults dict
1753

1754
    """
1755
    return FillDiskParams(self.diskparams, diskparams)
1756

    
1757
  def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1758
    """Get the default hypervisor parameters for the cluster.
1759

1760
    @param hypervisor: the hypervisor name
1761
    @param os_name: if specified, we'll also update the defaults for this OS
1762
    @param skip_keys: if passed, list of keys not to use
1763
    @return: the defaults dict
1764

1765
    """
1766
    if skip_keys is None:
1767
      skip_keys = []
1768

    
1769
    fill_stack = [self.hvparams.get(hypervisor, {})]
1770
    if os_name is not None:
1771
      os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1772
      fill_stack.append(os_hvp)
1773

    
1774
    ret_dict = {}
1775
    for o_dict in fill_stack:
1776
      ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1777

    
1778
    return ret_dict
1779

    
1780
  def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1781
    """Fill a given hvparams dict with cluster defaults.
1782

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

1794
    """
1795
    if skip_globals:
1796
      skip_keys = constants.HVC_GLOBALS
1797
    else:
1798
      skip_keys = []
1799

    
1800
    def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1801
    return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1802

    
1803
  def FillHV(self, instance, skip_globals=False):
1804
    """Fill an instance's hvparams dict with cluster defaults.
1805

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

1815
    """
1816
    return self.SimpleFillHV(instance.hypervisor, instance.os,
1817
                             instance.hvparams, skip_globals)
1818

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

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

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

    
1831
  def FillBE(self, instance):
1832
    """Fill an instance's beparams dict with cluster defaults.
1833

1834
    @type instance: L{objects.Instance}
1835
    @param instance: the instance parameter to fill
1836
    @rtype: dict
1837
    @return: a copy of the instance's beparams with missing keys filled from
1838
        the cluster defaults
1839

1840
    """
1841
    return self.SimpleFillBE(instance.beparams)
1842

    
1843
  def SimpleFillNIC(self, nicparams):
1844
    """Fill a given nicparams dict with cluster defaults.
1845

1846
    @type nicparams: dict
1847
    @param nicparams: the dict to fill
1848
    @rtype: dict
1849
    @return: a copy of the passed in nicparams with missing keys filled
1850
        from the cluster defaults
1851

1852
    """
1853
    return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1854

    
1855
  def SimpleFillOS(self, os_name, os_params):
1856
    """Fill an instance's osparams dict with cluster defaults.
1857

1858
    @type os_name: string
1859
    @param os_name: the OS name to use
1860
    @type os_params: dict
1861
    @param os_params: the dict to fill with default values
1862
    @rtype: dict
1863
    @return: a copy of the instance's osparams with missing keys filled from
1864
        the cluster defaults
1865

1866
    """
1867
    name_only = os_name.split("+", 1)[0]
1868
    # base OS
1869
    result = self.osparams.get(name_only, {})
1870
    # OS with variant
1871
    result = FillDict(result, self.osparams.get(os_name, {}))
1872
    # specified params
1873
    return FillDict(result, os_params)
1874

    
1875
  @staticmethod
1876
  def SimpleFillHvState(hv_state):
1877
    """Fill an hv_state sub dict with cluster defaults.
1878

1879
    """
1880
    return FillDict(constants.HVST_DEFAULTS, hv_state)
1881

    
1882
  @staticmethod
1883
  def SimpleFillDiskState(disk_state):
1884
    """Fill an disk_state sub dict with cluster defaults.
1885

1886
    """
1887
    return FillDict(constants.DS_DEFAULTS, disk_state)
1888

    
1889
  def FillND(self, node, nodegroup):
1890
    """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1891

1892
    @type node: L{objects.Node}
1893
    @param node: A Node object to fill
1894
    @type nodegroup: L{objects.NodeGroup}
1895
    @param nodegroup: A Node object to fill
1896
    @return a copy of the node's ndparams with defaults filled
1897

1898
    """
1899
    return self.SimpleFillND(nodegroup.FillND(node))
1900

    
1901
  def SimpleFillND(self, ndparams):
1902
    """Fill a given ndparams dict with defaults.
1903

1904
    @type ndparams: dict
1905
    @param ndparams: the dict to fill
1906
    @rtype: dict
1907
    @return: a copy of the passed in ndparams with missing keys filled
1908
        from the cluster defaults
1909

1910
    """
1911
    return FillDict(self.ndparams, ndparams)
1912

    
1913
  def SimpleFillIPolicy(self, ipolicy):
1914
    """ Fill instance policy dict with defaults.
1915

1916
    @type ipolicy: dict
1917
    @param ipolicy: the dict to fill
1918
    @rtype: dict
1919
    @return: a copy of passed ipolicy with missing keys filled from
1920
      the cluster defaults
1921

1922
    """
1923
    return FillIPolicy(self.ipolicy, ipolicy)
1924

    
1925
  def IsDiskTemplateEnabled(self, disk_template):
1926
    """Checks if a particular disk template is enabled.
1927

1928
    """
1929
    return utils.storage.IsDiskTemplateEnabled(
1930
        disk_template, self.enabled_disk_templates)
1931

    
1932
  def IsFileStorageEnabled(self):
1933
    """Checks if file storage is enabled.
1934

1935
    """
1936
    return utils.storage.IsFileStorageEnabled(self.enabled_disk_templates)
1937

    
1938
  def IsSharedFileStorageEnabled(self):
1939
    """Checks if shared file storage is enabled.
1940

1941
    """
1942
    return utils.storage.IsSharedFileStorageEnabled(
1943
        self.enabled_disk_templates)
1944

    
1945

    
1946
class BlockDevStatus(ConfigObject):
1947
  """Config object representing the status of a block device."""
1948
  __slots__ = [
1949
    "dev_path",
1950
    "major",
1951
    "minor",
1952
    "sync_percent",
1953
    "estimated_time",
1954
    "is_degraded",
1955
    "ldisk_status",
1956
    ]
1957

    
1958

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

    
1973

    
1974
class ImportExportOptions(ConfigObject):
1975
  """Options for import/export daemon
1976

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

1984
  """
1985
  __slots__ = [
1986
    "key_name",
1987
    "ca_pem",
1988
    "compress",
1989
    "magic",
1990
    "ipv6",
1991
    "connect_timeout",
1992
    ]
1993

    
1994

    
1995
class ConfdRequest(ConfigObject):
1996
  """Object holding a confd request.
1997

1998
  @ivar protocol: confd protocol version
1999
  @ivar type: confd query type
2000
  @ivar query: query request
2001
  @ivar rsalt: requested reply salt
2002

2003
  """
2004
  __slots__ = [
2005
    "protocol",
2006
    "type",
2007
    "query",
2008
    "rsalt",
2009
    ]
2010

    
2011

    
2012
class ConfdReply(ConfigObject):
2013
  """Object holding a confd reply.
2014

2015
  @ivar protocol: confd protocol version
2016
  @ivar status: reply status code (ok, error)
2017
  @ivar answer: confd query reply
2018
  @ivar serial: configuration serial number
2019

2020
  """
2021
  __slots__ = [
2022
    "protocol",
2023
    "status",
2024
    "answer",
2025
    "serial",
2026
    ]
2027

    
2028

    
2029
class QueryFieldDefinition(ConfigObject):
2030
  """Object holding a query field definition.
2031

2032
  @ivar name: Field name
2033
  @ivar title: Human-readable title
2034
  @ivar kind: Field type
2035
  @ivar doc: Human-readable description
2036

2037
  """
2038
  __slots__ = [
2039
    "name",
2040
    "title",
2041
    "kind",
2042
    "doc",
2043
    ]
2044

    
2045

    
2046
class _QueryResponseBase(ConfigObject):
2047
  __slots__ = [
2048
    "fields",
2049
    ]
2050

    
2051
  def ToDict(self):
2052
    """Custom function for serializing.
2053

2054
    """
2055
    mydict = super(_QueryResponseBase, self).ToDict()
2056
    mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2057
    return mydict
2058

    
2059
  @classmethod
2060
  def FromDict(cls, val):
2061
    """Custom function for de-serializing.
2062

2063
    """
2064
    obj = super(_QueryResponseBase, cls).FromDict(val)
2065
    obj.fields = \
2066
      outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2067
    return obj
2068

    
2069

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

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

2076
  """
2077
  __slots__ = [
2078
    "data",
2079
    ]
2080

    
2081

    
2082
class QueryFieldsRequest(ConfigObject):
2083
  """Object holding a request for querying available fields.
2084

2085
  """
2086
  __slots__ = [
2087
    "what",
2088
    "fields",
2089
    ]
2090

    
2091

    
2092
class QueryFieldsResponse(_QueryResponseBase):
2093
  """Object holding the response to a query for fields.
2094

2095
  @ivar fields: List of L{QueryFieldDefinition} objects
2096

2097
  """
2098
  __slots__ = []
2099

    
2100

    
2101
class MigrationStatus(ConfigObject):
2102
  """Object holding the status of a migration.
2103

2104
  """
2105
  __slots__ = [
2106
    "status",
2107
    "transferred_ram",
2108
    "total_ram",
2109
    ]
2110

    
2111

    
2112
class InstanceConsole(ConfigObject):
2113
  """Object describing how to access the console of an instance.
2114

2115
  """
2116
  __slots__ = [
2117
    "instance",
2118
    "kind",
2119
    "message",
2120
    "host",
2121
    "port",
2122
    "user",
2123
    "command",
2124
    "display",
2125
    ]
2126

    
2127
  def Validate(self):
2128
    """Validates contents of this object.
2129

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

    
2150

    
2151
class Network(TaggableObject):
2152
  """Object representing a network definition for ganeti.
2153

2154
  """
2155
  __slots__ = [
2156
    "name",
2157
    "serial_no",
2158
    "mac_prefix",
2159
    "network",
2160
    "network6",
2161
    "gateway",
2162
    "gateway6",
2163
    "reservations",
2164
    "ext_reservations",
2165
    ] + _TIMESTAMPS + _UUID
2166

    
2167
  def HooksDict(self, prefix=""):
2168
    """Export a dictionary used by hooks with a network's information.
2169

2170
    @type prefix: String
2171
    @param prefix: Prefix to prepend to the dict entries
2172

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

    
2190
    return result
2191

    
2192
  @classmethod
2193
  def FromDict(cls, val):
2194
    """Custom function for networks.
2195

2196
    Remove deprecated network_type and family.
2197

2198
    """
2199
    if "network_type" in val:
2200
      del val["network_type"]
2201
    if "family" in val:
2202
      del val["family"]
2203
    obj = super(Network, cls).FromDict(val)
2204
    return obj
2205

    
2206

    
2207
class SerializableConfigParser(ConfigParser.SafeConfigParser):
2208
  """Simple wrapper over ConfigParse that allows serialization.
2209

2210
  This class is basically ConfigParser.SafeConfigParser with two
2211
  additional methods that allow it to serialize/unserialize to/from a
2212
  buffer.
2213

2214
  """
2215
  def Dumps(self):
2216
    """Dump this instance and return the string representation."""
2217
    buf = StringIO()
2218
    self.write(buf)
2219
    return buf.getvalue()
2220

    
2221
  @classmethod
2222
  def Loads(cls, data):
2223
    """Load data from a string."""
2224
    buf = StringIO(data)
2225
    cfp = cls()
2226
    cfp.readfp(buf)
2227
    return cfp
2228

    
2229

    
2230
class LvmPvInfo(ConfigObject):
2231
  """Information about an LVM physical volume (PV).
2232

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

    
2255
  def IsEmpty(self):
2256
    """Is this PV empty?
2257

2258
    """
2259
    return self.size <= (self.free + 1)
2260

    
2261
  def IsAllocatable(self):
2262
    """Is this PV allocatable?
2263

2264
    """
2265
    return ("a" in self.attributes)