4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
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.
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.
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
22 """Transportable objects for Ganeti.
24 This module provides small, mostly data-only objects which are safe to
25 pass to and from external parties.
29 # pylint: disable=E0203,W0201,R0902
31 # E0203: Access to member %r before its definition, since we use
32 # objects.py which doesn't explicitly initialise its members
34 # W0201: Attribute '%s' defined outside __init__
36 # R0902: Allow instances of these objects to have more than 20 attributes
43 from cStringIO import StringIO
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
51 from socket import AF_INET
54 __all__ = ["ConfigObject", "ConfigData", "NIC", "Disk", "Instance",
55 "OS", "Node", "NodeGroup", "Cluster", "FillDict", "Network"]
57 _TIMESTAMPS = ["ctime", "mtime"]
61 def FillDict(defaults_dict, custom_dict, skip_keys=None):
62 """Basic function to apply settings on top a default dict.
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
69 @param skip_keys: which keys not to fill
71 @return: dict with the 'full' values
74 ret_dict = copy.deepcopy(defaults_dict)
75 ret_dict.update(custom_dict)
85 def _FillMinMaxISpecs(default_specs, custom_specs):
86 assert frozenset(default_specs.keys()) == constants.ISPECS_MINMAX_KEYS
88 for key in constants.ISPECS_MINMAX_KEYS:
89 ret_specs[key] = FillDict(default_specs[key],
90 custom_specs.get(key, {}))
94 def FillIPolicy(default_ipolicy, custom_ipolicy):
95 """Fills an instance policy with defaults.
98 assert frozenset(default_ipolicy.keys()) == constants.IPOLICY_ALL_KEYS
101 new_mm = _FillMinMaxISpecs(default_ipolicy[constants.ISPECS_MINMAX],
102 custom_ipolicy.get(constants.ISPECS_MINMAX, {}))
103 ret_dict[constants.ISPECS_MINMAX] = new_mm
104 new_std = FillDict(default_ipolicy[constants.ISPECS_STD],
105 custom_ipolicy.get(constants.ISPECS_STD, {}))
106 ret_dict[constants.ISPECS_STD] = new_std
108 for key in [constants.IPOLICY_DTS]:
109 ret_dict[key] = list(custom_ipolicy.get(key, default_ipolicy[key]))
110 # other items which we know we can directly copy (immutables)
111 for key in constants.IPOLICY_PARAMETERS:
112 ret_dict[key] = custom_ipolicy.get(key, default_ipolicy[key])
117 def FillDiskParams(default_dparams, custom_dparams, skip_keys=None):
118 """Fills the disk parameter defaults.
120 @see: L{FillDict} for parameters and return value
123 assert frozenset(default_dparams.keys()) == constants.DISK_TEMPLATES
125 return dict((dt, FillDict(default_dparams[dt], custom_dparams.get(dt, {}),
126 skip_keys=skip_keys))
127 for dt in constants.DISK_TEMPLATES)
130 def UpgradeGroupedParams(target, defaults):
131 """Update all groups for the target parameter.
133 @type target: dict of dicts
134 @param target: {group: {parameter: value}}
136 @param defaults: default parameter values
140 target = {constants.PP_DEFAULT: defaults}
143 target[group] = FillDict(defaults, target[group])
147 def UpgradeBeParams(target):
148 """Update the be parameters dict to the new format.
151 @param target: "be" parameters dict
154 if constants.BE_MEMORY in target:
155 memory = target[constants.BE_MEMORY]
156 target[constants.BE_MAXMEM] = memory
157 target[constants.BE_MINMEM] = memory
158 del target[constants.BE_MEMORY]
161 def UpgradeDiskParams(diskparams):
162 """Upgrade the disk parameters.
164 @type diskparams: dict
165 @param diskparams: disk parameters to upgrade
167 @return: the upgraded disk parameters dict
173 result = FillDiskParams(constants.DISK_DT_DEFAULTS, diskparams)
178 def UpgradeNDParams(ndparams):
179 """Upgrade ndparams structure.
182 @param ndparams: disk parameters to upgrade
184 @return: the upgraded node parameters dict
190 if (constants.ND_OOB_PROGRAM in ndparams and
191 ndparams[constants.ND_OOB_PROGRAM] is None):
192 # will be reset by the line below
193 del ndparams[constants.ND_OOB_PROGRAM]
194 return FillDict(constants.NDC_DEFAULTS, ndparams)
197 def MakeEmptyIPolicy():
198 """Create empty IPolicy dictionary.
202 constants.ISPECS_MINMAX: {
203 constants.ISPECS_MIN: {},
204 constants.ISPECS_MAX: {},
206 constants.ISPECS_STD: {},
210 class ConfigObject(outils.ValidatedSlots):
211 """A generic config object.
213 It has the following properties:
215 - provides somewhat safe recursive unpickling and pickling for its classes
216 - unset attributes which are defined in slots are always returned
217 as None instead of raising an error
219 Classes derived from this must always declare __slots__ (we use many
220 config objects and the memory reduction is useful)
225 def __getattr__(self, name):
226 if name not in self.GetAllSlots():
227 raise AttributeError("Invalid object attribute %s.%s" %
228 (type(self).__name__, name))
231 def __setstate__(self, state):
232 slots = self.GetAllSlots()
235 setattr(self, name, state[name])
238 """Validates the slots.
243 """Convert to a dict holding only standard python types.
245 The generic routine just dumps all of this object's attributes in
246 a dict. It does not work if the class has children who are
247 ConfigObjects themselves (e.g. the nics list in an Instance), in
248 which case the object should subclass the function in order to
249 make sure all objects returned are only standard python types.
253 for name in self.GetAllSlots():
254 value = getattr(self, name, None)
255 if value is not None:
259 __getstate__ = ToDict
262 def FromDict(cls, val):
263 """Create an object from a dictionary.
265 This generic routine takes a dict, instantiates a new instance of
266 the given class, and sets attributes based on the dict content.
268 As for `ToDict`, this does not work if the class has children
269 who are ConfigObjects themselves (e.g. the nics list in an
270 Instance), in which case the object should subclass the function
271 and alter the objects.
274 if not isinstance(val, dict):
275 raise errors.ConfigurationError("Invalid object passed to FromDict:"
276 " expected dict, got %s" % type(val))
277 val_str = dict([(str(k), v) for k, v in val.iteritems()])
278 obj = cls(**val_str) # pylint: disable=W0142
282 """Makes a deep copy of the current object and its children.
285 dict_form = self.ToDict()
286 clone_obj = self.__class__.FromDict(dict_form)
290 """Implement __repr__ for ConfigObjects."""
291 return repr(self.ToDict())
293 def UpgradeConfig(self):
294 """Fill defaults for missing configuration values.
296 This method will be called at configuration load time, and its
297 implementation will be object dependent.
303 class TaggableObject(ConfigObject):
304 """An generic class supporting tags.
308 VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
311 def ValidateTag(cls, tag):
312 """Check if a tag is valid.
314 If the tag is invalid, an errors.TagError will be raised. The
315 function has no return value.
318 if not isinstance(tag, basestring):
319 raise errors.TagError("Invalid tag type (not a string)")
320 if len(tag) > constants.MAX_TAG_LEN:
321 raise errors.TagError("Tag too long (>%d characters)" %
322 constants.MAX_TAG_LEN)
324 raise errors.TagError("Tags cannot be empty")
325 if not cls.VALID_TAG_RE.match(tag):
326 raise errors.TagError("Tag contains invalid characters")
329 """Return the tags list.
332 tags = getattr(self, "tags", None)
334 tags = self.tags = set()
337 def AddTag(self, tag):
341 self.ValidateTag(tag)
342 tags = self.GetTags()
343 if len(tags) >= constants.MAX_TAGS_PER_OBJ:
344 raise errors.TagError("Too many tags")
345 self.GetTags().add(tag)
347 def RemoveTag(self, tag):
351 self.ValidateTag(tag)
352 tags = self.GetTags()
356 raise errors.TagError("Tag not found")
359 """Taggable-object-specific conversion to standard python types.
361 This replaces the tags set with a list.
364 bo = super(TaggableObject, self).ToDict()
366 tags = bo.get("tags", None)
367 if isinstance(tags, set):
368 bo["tags"] = list(tags)
372 def FromDict(cls, val):
373 """Custom function for instances.
376 obj = super(TaggableObject, cls).FromDict(val)
377 if hasattr(obj, "tags") and isinstance(obj.tags, list):
378 obj.tags = set(obj.tags)
382 class MasterNetworkParameters(ConfigObject):
383 """Network configuration parameters for the master
385 @ivar name: master name
387 @ivar netmask: master netmask
388 @ivar netdev: master network device
389 @ivar ip_family: master IP family
401 class ConfigData(ConfigObject):
402 """Top-level config object."""
414 """Custom function for top-level config data.
416 This just replaces the list of instances, nodes and the cluster
417 with standard python types.
420 mydict = super(ConfigData, self).ToDict()
421 mydict["cluster"] = mydict["cluster"].ToDict()
422 for key in "nodes", "instances", "nodegroups", "networks":
423 mydict[key] = outils.ContainerToDicts(mydict[key])
428 def FromDict(cls, val):
429 """Custom function for top-level config data
432 obj = super(ConfigData, cls).FromDict(val)
433 obj.cluster = Cluster.FromDict(obj.cluster)
434 obj.nodes = outils.ContainerFromDicts(obj.nodes, dict, Node)
436 outils.ContainerFromDicts(obj.instances, dict, Instance)
438 outils.ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
439 obj.networks = outils.ContainerFromDicts(obj.networks, dict, Network)
442 def HasAnyDiskOfType(self, dev_type):
443 """Check if in there is at disk of the given type in the configuration.
445 @type dev_type: L{constants.LDS_BLOCK}
446 @param dev_type: the type to look for
448 @return: boolean indicating if a disk of the given type was found or not
451 for instance in self.instances.values():
452 for disk in instance.disks:
453 if disk.IsBasedOnDiskType(dev_type):
457 def UpgradeConfig(self):
458 """Fill defaults for missing configuration values.
461 self.cluster.UpgradeConfig()
462 for node in self.nodes.values():
464 for instance in self.instances.values():
465 instance.UpgradeConfig()
466 if self.nodegroups is None:
468 for nodegroup in self.nodegroups.values():
469 nodegroup.UpgradeConfig()
470 if self.cluster.drbd_usermode_helper is None:
471 # To decide if we set an helper let's check if at least one instance has
472 # a DRBD disk. This does not cover all the possible scenarios but it
473 # gives a good approximation.
474 if self.HasAnyDiskOfType(constants.LD_DRBD8):
475 self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
476 if self.networks is None:
478 for network in self.networks.values():
479 network.UpgradeConfig()
480 self._UpgradeEnabledDiskTemplates()
482 def _UpgradeEnabledDiskTemplates(self):
483 """Upgrade the cluster's enabled disk templates by inspecting the currently
484 enabled and/or used disk templates.
487 # enabled_disk_templates in the cluster config were introduced in 2.8.
488 # Remove this code once upgrading from earlier versions is deprecated.
489 if not self.cluster.enabled_disk_templates:
491 set([inst.disk_template for inst in self.instances.values()])
492 # Add drbd and plain, if lvm is enabled (by specifying a volume group)
493 if self.cluster.volume_group_name:
494 template_set.add(constants.DT_DRBD8)
495 template_set.add(constants.DT_PLAIN)
496 # FIXME: Adapt this when dis/enabling at configure time is removed.
497 # Enable 'file' and 'sharedfile', if they are enabled, even though they
498 # might currently not be used.
499 if constants.ENABLE_FILE_STORAGE:
500 template_set.add(constants.DT_FILE)
501 if constants.ENABLE_SHARED_FILE_STORAGE:
502 template_set.add(constants.DT_SHARED_FILE)
503 # Set enabled_disk_templates to the inferred disk templates. Order them
504 # according to a preference list that is based on Ganeti's history of
505 # supported disk templates.
506 self.cluster.enabled_disk_templates = []
507 for preferred_template in constants.DISK_TEMPLATE_PREFERENCE:
508 if preferred_template in template_set:
509 self.cluster.enabled_disk_templates.append(preferred_template)
510 template_set.remove(preferred_template)
511 self.cluster.enabled_disk_templates.extend(list(template_set))
514 class NIC(ConfigObject):
515 """Config object representing a network card."""
516 __slots__ = ["name", "mac", "ip", "network", "nicparams", "netinfo"] + _UUID
519 def CheckParameterSyntax(cls, nicparams):
520 """Check the given parameters for validity.
522 @type nicparams: dict
523 @param nicparams: dictionary with parameter names/value
524 @raise errors.ConfigurationError: when a parameter is not valid
527 mode = nicparams[constants.NIC_MODE]
528 if (mode not in constants.NIC_VALID_MODES and
529 mode != constants.VALUE_AUTO):
530 raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
532 if (mode == constants.NIC_MODE_BRIDGED and
533 not nicparams[constants.NIC_LINK]):
534 raise errors.ConfigurationError("Missing bridged NIC link")
537 class Disk(ConfigObject):
538 """Config object representing a block device."""
539 __slots__ = ["name", "dev_type", "logical_id", "physical_id",
540 "children", "iv_name", "size", "mode", "params"] + _UUID
542 def CreateOnSecondary(self):
543 """Test if this device needs to be created on a secondary node."""
544 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
546 def AssembleOnSecondary(self):
547 """Test if this device needs to be assembled on a secondary node."""
548 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
550 def OpenOnSecondary(self):
551 """Test if this device needs to be opened on a secondary node."""
552 return self.dev_type in (constants.LD_LV,)
554 def StaticDevPath(self):
555 """Return the device path if this device type has a static one.
557 Some devices (LVM for example) live always at the same /dev/ path,
558 irrespective of their status. For such devices, we return this
559 path, for others we return None.
561 @warning: The path returned is not a normalized pathname; callers
562 should check that it is a valid path.
565 if self.dev_type == constants.LD_LV:
566 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
567 elif self.dev_type == constants.LD_BLOCKDEV:
568 return self.logical_id[1]
569 elif self.dev_type == constants.LD_RBD:
570 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
573 def ChildrenNeeded(self):
574 """Compute the needed number of children for activation.
576 This method will return either -1 (all children) or a positive
577 number denoting the minimum number of children needed for
578 activation (only mirrored devices will usually return >=0).
580 Currently, only DRBD8 supports diskless activation (therefore we
581 return 0), for all other we keep the previous semantics and return
585 if self.dev_type == constants.LD_DRBD8:
589 def IsBasedOnDiskType(self, dev_type):
590 """Check if the disk or its children are based on the given type.
592 @type dev_type: L{constants.LDS_BLOCK}
593 @param dev_type: the type to look for
595 @return: boolean indicating if a device of the given type was found or not
599 for child in self.children:
600 if child.IsBasedOnDiskType(dev_type):
602 return self.dev_type == dev_type
604 def GetNodes(self, node):
605 """This function returns the nodes this device lives on.
607 Given the node on which the parent of the device lives on (or, in
608 case of a top-level device, the primary node of the devices'
609 instance), this function will return a list of nodes on which this
610 devices needs to (or can) be assembled.
613 if self.dev_type in [constants.LD_LV, constants.LD_FILE,
614 constants.LD_BLOCKDEV, constants.LD_RBD,
617 elif self.dev_type in constants.LDS_DRBD:
618 result = [self.logical_id[0], self.logical_id[1]]
619 if node not in result:
620 raise errors.ConfigurationError("DRBD device passed unknown node")
622 raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
625 def ComputeNodeTree(self, parent_node):
626 """Compute the node/disk tree for this disk and its children.
628 This method, given the node on which the parent disk lives, will
629 return the list of all (node, disk) pairs which describe the disk
630 tree in the most compact way. For example, a drbd/lvm stack
631 will be returned as (primary_node, drbd) and (secondary_node, drbd)
632 which represents all the top-level devices on the nodes.
635 my_nodes = self.GetNodes(parent_node)
636 result = [(node, self) for node in my_nodes]
637 if not self.children:
640 for node in my_nodes:
641 for child in self.children:
642 child_result = child.ComputeNodeTree(node)
643 if len(child_result) == 1:
644 # child (and all its descendants) is simple, doesn't split
645 # over multiple hosts, so we don't need to describe it, our
646 # own entry for this node describes it completely
649 # check if child nodes differ from my nodes; note that
650 # subdisk can differ from the child itself, and be instead
651 # one of its descendants
652 for subnode, subdisk in child_result:
653 if subnode not in my_nodes:
654 result.append((subnode, subdisk))
655 # otherwise child is under our own node, so we ignore this
656 # entry (but probably the other results in the list will
660 def ComputeGrowth(self, amount):
661 """Compute the per-VG growth requirements.
663 This only works for VG-based disks.
665 @type amount: integer
666 @param amount: the desired increase in (user-visible) disk space
668 @return: a dictionary of volume-groups and the required size
671 if self.dev_type == constants.LD_LV:
672 return {self.logical_id[0]: amount}
673 elif self.dev_type == constants.LD_DRBD8:
675 return self.children[0].ComputeGrowth(amount)
679 # Other disk types do not require VG space
682 def RecordGrow(self, amount):
683 """Update the size of this disk after growth.
685 This method recurses over the disks's children and updates their
686 size correspondigly. The method needs to be kept in sync with the
687 actual algorithms from bdev.
690 if self.dev_type in (constants.LD_LV, constants.LD_FILE,
691 constants.LD_RBD, constants.LD_EXT):
693 elif self.dev_type == constants.LD_DRBD8:
695 self.children[0].RecordGrow(amount)
698 raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
699 " disk type %s" % self.dev_type)
701 def Update(self, size=None, mode=None):
702 """Apply changes to size and mode.
705 if self.dev_type == constants.LD_DRBD8:
707 self.children[0].Update(size=size, mode=mode)
709 assert not self.children
717 """Sets recursively the size to zero for the disk and its children.
721 for child in self.children:
725 def SetPhysicalID(self, target_node, nodes_ip):
726 """Convert the logical ID to the physical ID.
728 This is used only for drbd, which needs ip/port configuration.
730 The routine descends down and updates its children also, because
731 this helps when the only the top device is passed to the remote
735 - target_node: the node we wish to configure for
736 - nodes_ip: a mapping of node name to ip
738 The target_node must exist in in nodes_ip, and must be one of the
739 nodes in the logical ID for each of the DRBD devices encountered
744 for child in self.children:
745 child.SetPhysicalID(target_node, nodes_ip)
747 if self.logical_id is None and self.physical_id is not None:
749 if self.dev_type in constants.LDS_DRBD:
750 pnode, snode, port, pminor, sminor, secret = self.logical_id
751 if target_node not in (pnode, snode):
752 raise errors.ConfigurationError("DRBD device not knowing node %s" %
754 pnode_ip = nodes_ip.get(pnode, None)
755 snode_ip = nodes_ip.get(snode, None)
756 if pnode_ip is None or snode_ip is None:
757 raise errors.ConfigurationError("Can't find primary or secondary node"
758 " for %s" % str(self))
759 p_data = (pnode_ip, port)
760 s_data = (snode_ip, port)
761 if pnode == target_node:
762 self.physical_id = p_data + s_data + (pminor, secret)
763 else: # it must be secondary, we tested above
764 self.physical_id = s_data + p_data + (sminor, secret)
766 self.physical_id = self.logical_id
770 """Disk-specific conversion to standard python types.
772 This replaces the children lists of objects with lists of
773 standard python types.
776 bo = super(Disk, self).ToDict()
778 for attr in ("children",):
779 alist = bo.get(attr, None)
781 bo[attr] = outils.ContainerToDicts(alist)
785 def FromDict(cls, val):
786 """Custom function for Disks
789 obj = super(Disk, cls).FromDict(val)
791 obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
792 if obj.logical_id and isinstance(obj.logical_id, list):
793 obj.logical_id = tuple(obj.logical_id)
794 if obj.physical_id and isinstance(obj.physical_id, list):
795 obj.physical_id = tuple(obj.physical_id)
796 if obj.dev_type in constants.LDS_DRBD:
797 # we need a tuple of length six here
798 if len(obj.logical_id) < 6:
799 obj.logical_id += (None,) * (6 - len(obj.logical_id))
803 """Custom str() formatter for disks.
806 if self.dev_type == constants.LD_LV:
807 val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
808 elif self.dev_type in constants.LDS_DRBD:
809 node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
811 if self.physical_id is None:
814 phy = ("configured as %s:%s %s:%s" %
815 (self.physical_id[0], self.physical_id[1],
816 self.physical_id[2], self.physical_id[3]))
818 val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
819 (node_a, minor_a, node_b, minor_b, port, phy))
820 if self.children and self.children.count(None) == 0:
821 val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
823 val += "no local storage"
825 val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
826 (self.dev_type, self.logical_id, self.physical_id, self.children))
827 if self.iv_name is None:
828 val += ", not visible"
830 val += ", visible as /dev/%s" % self.iv_name
831 if isinstance(self.size, int):
832 val += ", size=%dm)>" % self.size
834 val += ", size='%s')>" % (self.size,)
838 """Checks that this disk is correctly configured.
842 if self.mode not in constants.DISK_ACCESS_SET:
843 all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
846 def UpgradeConfig(self):
847 """Fill defaults for missing configuration values.
851 for child in self.children:
852 child.UpgradeConfig()
854 # FIXME: Make this configurable in Ganeti 2.7
856 # add here config upgrade for this disk
859 def ComputeLDParams(disk_template, disk_params):
860 """Computes Logical Disk parameters from Disk Template parameters.
862 @type disk_template: string
863 @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
864 @type disk_params: dict
865 @param disk_params: disk template parameters;
866 dict(template_name -> parameters
868 @return: a list of dicts, one for each node of the disk hierarchy. Each dict
869 contains the LD parameters of the node. The tree is flattened in-order.
872 if disk_template not in constants.DISK_TEMPLATES:
873 raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
875 assert disk_template in disk_params
878 dt_params = disk_params[disk_template]
879 if disk_template == constants.DT_DRBD8:
880 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8], {
881 constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
882 constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
883 constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
884 constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
885 constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
886 constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
887 constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
888 constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
889 constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
890 constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
891 constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
892 constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
896 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
897 constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
901 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
902 constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
905 elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
906 result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
908 elif disk_template == constants.DT_PLAIN:
909 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
910 constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
913 elif disk_template == constants.DT_BLOCK:
914 result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
916 elif disk_template == constants.DT_RBD:
917 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD], {
918 constants.LDP_POOL: dt_params[constants.RBD_POOL],
921 elif disk_template == constants.DT_EXT:
922 result.append(constants.DISK_LD_DEFAULTS[constants.LD_EXT])
927 class InstancePolicy(ConfigObject):
928 """Config object representing instance policy limits dictionary.
930 Note that this object is not actually used in the config, it's just
931 used as a placeholder for a few functions.
935 def CheckParameterSyntax(cls, ipolicy, check_std):
936 """ Check the instance policy for validity.
939 @param ipolicy: dictionary with min/max/std specs and policies
940 @type check_std: bool
941 @param check_std: Whether to check std value or just assume compliance
942 @raise errors.ConfigurationError: when the policy is not legal
945 if constants.ISPECS_MINMAX in ipolicy:
946 if check_std and constants.ISPECS_STD not in ipolicy:
947 msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
948 raise errors.ConfigurationError(msg)
949 minmaxspecs = ipolicy[constants.ISPECS_MINMAX]
950 stdspec = ipolicy.get(constants.ISPECS_STD)
951 for param in constants.ISPECS_PARAMETERS:
952 InstancePolicy.CheckISpecSyntax(minmaxspecs, stdspec, param, check_std)
953 if constants.IPOLICY_DTS in ipolicy:
954 InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
955 for key in constants.IPOLICY_PARAMETERS:
957 InstancePolicy.CheckParameter(key, ipolicy[key])
958 wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
960 raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
961 utils.CommaJoin(wrong_keys))
964 def CheckISpecSyntax(cls, minmaxspecs, stdspec, name, check_std):
965 """Check the instance policy specs for validity on a given key.
967 We check if the instance specs makes sense for a given key, that is
968 if minmaxspecs[min][name] <= stdspec[name] <= minmaxspec[max][name].
970 @type minmaxspecs: dict
971 @param minmaxspecs: dictionary with min and max instance spec
973 @param stdspec: dictionary with standard instance spec
975 @param name: what are the limits for
976 @type check_std: bool
977 @param check_std: Whether to check std value or just assume compliance
978 @raise errors.ConfigurationError: when specs for the given name are not
982 missing = constants.ISPECS_MINMAX_KEYS - frozenset(minmaxspecs.keys())
984 msg = "Missing instance specification: %s" % utils.CommaJoin(missing)
985 raise errors.ConfigurationError(msg)
987 minspec = minmaxspecs[constants.ISPECS_MIN]
988 maxspec = minmaxspecs[constants.ISPECS_MAX]
989 min_v = minspec.get(name, 0)
992 std_v = stdspec.get(name, min_v)
998 max_v = maxspec.get(name, std_v)
999 if min_v > std_v or std_v > max_v:
1000 err = ("Invalid specification of min/max/std values for %s: %s/%s/%s" %
1002 minspec.get(name, "-"),
1003 maxspec.get(name, "-"),
1005 raise errors.ConfigurationError(err)
1008 def CheckDiskTemplates(cls, disk_templates):
1009 """Checks the disk templates for validity.
1012 if not disk_templates:
1013 raise errors.ConfigurationError("Instance policy must contain" +
1014 " at least one disk template")
1015 wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1017 raise errors.ConfigurationError("Invalid disk template(s) %s" %
1018 utils.CommaJoin(wrong))
1021 def CheckParameter(cls, key, value):
1022 """Checks a parameter.
1024 Currently we expect all parameters to be float values.
1029 except (TypeError, ValueError), err:
1030 raise errors.ConfigurationError("Invalid value for key" " '%s':"
1031 " '%s', error: %s" % (key, value, err))
1034 class Instance(TaggableObject):
1035 """Config object representing an instance."""
1050 ] + _TIMESTAMPS + _UUID
1052 def _ComputeSecondaryNodes(self):
1053 """Compute the list of secondary nodes.
1055 This is a simple wrapper over _ComputeAllNodes.
1058 all_nodes = set(self._ComputeAllNodes())
1059 all_nodes.discard(self.primary_node)
1060 return tuple(all_nodes)
1062 secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1063 "List of names of secondary nodes")
1065 def _ComputeAllNodes(self):
1066 """Compute the list of all nodes.
1068 Since the data is already there (in the drbd disks), keeping it as
1069 a separate normal attribute is redundant and if not properly
1070 synchronised can cause problems. Thus it's better to compute it
1074 def _Helper(nodes, device):
1075 """Recursively computes nodes given a top device."""
1076 if device.dev_type in constants.LDS_DRBD:
1077 nodea, nodeb = device.logical_id[:2]
1081 for child in device.children:
1082 _Helper(nodes, child)
1085 all_nodes.add(self.primary_node)
1086 for device in self.disks:
1087 _Helper(all_nodes, device)
1088 return tuple(all_nodes)
1090 all_nodes = property(_ComputeAllNodes, None, None,
1091 "List of names of all the nodes of the instance")
1093 def MapLVsByNode(self, lvmap=None, devs=None, node=None):
1094 """Provide a mapping of nodes to LVs this instance owns.
1096 This function figures out what logical volumes should belong on
1097 which nodes, recursing through a device tree.
1099 @param lvmap: optional dictionary to receive the
1100 'node' : ['lv', ...] data.
1102 @return: None if lvmap arg is given, otherwise, a dictionary of
1103 the form { 'nodename' : ['volume1', 'volume2', ...], ... };
1104 volumeN is of the form "vg_name/lv_name", compatible with
1109 node = self.primary_node
1117 if not node in lvmap:
1125 if dev.dev_type == constants.LD_LV:
1126 lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1128 elif dev.dev_type in constants.LDS_DRBD:
1130 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1131 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1134 self.MapLVsByNode(lvmap, dev.children, node)
1138 def FindDisk(self, idx):
1139 """Find a disk given having a specified index.
1141 This is just a wrapper that does validation of the index.
1144 @param idx: the disk index
1146 @return: the corresponding disk
1147 @raise errors.OpPrereqError: when the given index is not valid
1152 return self.disks[idx]
1153 except (TypeError, ValueError), err:
1154 raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1157 raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1158 " 0 to %d" % (idx, len(self.disks) - 1),
1162 """Instance-specific conversion to standard python types.
1164 This replaces the children lists of objects with lists of standard
1168 bo = super(Instance, self).ToDict()
1170 for attr in "nics", "disks":
1171 alist = bo.get(attr, None)
1173 nlist = outils.ContainerToDicts(alist)
1180 def FromDict(cls, val):
1181 """Custom function for instances.
1184 if "admin_state" not in val:
1185 if val.get("admin_up", False):
1186 val["admin_state"] = constants.ADMINST_UP
1188 val["admin_state"] = constants.ADMINST_DOWN
1189 if "admin_up" in val:
1191 obj = super(Instance, cls).FromDict(val)
1192 obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1193 obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1196 def UpgradeConfig(self):
1197 """Fill defaults for missing configuration values.
1200 for nic in self.nics:
1202 for disk in self.disks:
1203 disk.UpgradeConfig()
1205 for key in constants.HVC_GLOBALS:
1207 del self.hvparams[key]
1210 if self.osparams is None:
1212 UpgradeBeParams(self.beparams)
1215 class OS(ConfigObject):
1216 """Config object representing an operating system.
1218 @type supported_parameters: list
1219 @ivar supported_parameters: a list of tuples, name and description,
1220 containing the supported parameters by this OS
1222 @type VARIANT_DELIM: string
1223 @cvar VARIANT_DELIM: the variant delimiter
1235 "supported_variants",
1236 "supported_parameters",
1242 def SplitNameVariant(cls, name):
1243 """Splits the name into the proper name and variant.
1245 @param name: the OS (unprocessed) name
1247 @return: a list of two elements; if the original name didn't
1248 contain a variant, it's returned as an empty string
1251 nv = name.split(cls.VARIANT_DELIM, 1)
1257 def GetName(cls, name):
1258 """Returns the proper name of the os (without the variant).
1260 @param name: the OS (unprocessed) name
1263 return cls.SplitNameVariant(name)[0]
1266 def GetVariant(cls, name):
1267 """Returns the variant the os (without the base name).
1269 @param name: the OS (unprocessed) name
1272 return cls.SplitNameVariant(name)[1]
1275 class ExtStorage(ConfigObject):
1276 """Config object representing an External Storage Provider.
1289 "supported_parameters",
1293 class NodeHvState(ConfigObject):
1294 """Hypvervisor state on a node.
1296 @ivar mem_total: Total amount of memory
1297 @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1299 @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1301 @ivar mem_inst: Memory used by instances living on node
1302 @ivar cpu_total: Total node CPU core count
1303 @ivar cpu_node: Number of CPU cores reserved for the node itself
1316 class NodeDiskState(ConfigObject):
1317 """Disk state on a node.
1327 class Node(TaggableObject):
1328 """Config object representing a node.
1330 @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1331 @ivar hv_state_static: Hypervisor state overriden by user
1332 @ivar disk_state: Disk state (e.g. free space)
1333 @ivar disk_state_static: Disk state overriden by user
1352 "disk_state_static",
1353 ] + _TIMESTAMPS + _UUID
1355 def UpgradeConfig(self):
1356 """Fill defaults for missing configuration values.
1359 # pylint: disable=E0203
1360 # because these are "defined" via slots, not manually
1361 if self.master_capable is None:
1362 self.master_capable = True
1364 if self.vm_capable is None:
1365 self.vm_capable = True
1367 if self.ndparams is None:
1369 # And remove any global parameter
1370 for key in constants.NDC_GLOBALS:
1371 if key in self.ndparams:
1372 logging.warning("Ignoring %s node parameter for node %s",
1374 del self.ndparams[key]
1376 if self.powered is None:
1380 """Custom function for serializing.
1383 data = super(Node, self).ToDict()
1385 hv_state = data.get("hv_state", None)
1386 if hv_state is not None:
1387 data["hv_state"] = outils.ContainerToDicts(hv_state)
1389 disk_state = data.get("disk_state", None)
1390 if disk_state is not None:
1391 data["disk_state"] = \
1392 dict((key, outils.ContainerToDicts(value))
1393 for (key, value) in disk_state.items())
1398 def FromDict(cls, val):
1399 """Custom function for deserializing.
1402 obj = super(Node, cls).FromDict(val)
1404 if obj.hv_state is not None:
1406 outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1408 if obj.disk_state is not None:
1410 dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1411 for (key, value) in obj.disk_state.items())
1416 class NodeGroup(TaggableObject):
1417 """Config object representing a node group."""
1426 "disk_state_static",
1429 ] + _TIMESTAMPS + _UUID
1432 """Custom function for nodegroup.
1434 This discards the members object, which gets recalculated and is only kept
1438 mydict = super(NodeGroup, self).ToDict()
1439 del mydict["members"]
1443 def FromDict(cls, val):
1444 """Custom function for nodegroup.
1446 The members slot is initialized to an empty list, upon deserialization.
1449 obj = super(NodeGroup, cls).FromDict(val)
1453 def UpgradeConfig(self):
1454 """Fill defaults for missing configuration values.
1457 if self.ndparams is None:
1460 if self.serial_no is None:
1463 if self.alloc_policy is None:
1464 self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1466 # We only update mtime, and not ctime, since we would not be able
1467 # to provide a correct value for creation time.
1468 if self.mtime is None:
1469 self.mtime = time.time()
1471 if self.diskparams is None:
1472 self.diskparams = {}
1473 if self.ipolicy is None:
1474 self.ipolicy = MakeEmptyIPolicy()
1476 if self.networks is None:
1479 def FillND(self, node):
1480 """Return filled out ndparams for L{objects.Node}
1482 @type node: L{objects.Node}
1483 @param node: A Node object to fill
1484 @return a copy of the node's ndparams with defaults filled
1487 return self.SimpleFillND(node.ndparams)
1489 def SimpleFillND(self, ndparams):
1490 """Fill a given ndparams dict with defaults.
1492 @type ndparams: dict
1493 @param ndparams: the dict to fill
1495 @return: a copy of the passed in ndparams with missing keys filled
1496 from the node group defaults
1499 return FillDict(self.ndparams, ndparams)
1502 class Cluster(TaggableObject):
1503 """Config object representing the cluster."""
1507 "highest_used_port",
1510 "volume_group_name",
1512 "drbd_usermode_helper",
1514 "default_hypervisor",
1519 "use_external_mip_script",
1522 "shared_file_storage_dir",
1523 "enabled_hypervisors",
1532 "candidate_pool_size",
1535 "maintain_node_health",
1537 "default_iallocator",
1540 "primary_ip_family",
1541 "prealloc_wipe_disks",
1543 "disk_state_static",
1544 "enabled_disk_templates",
1545 ] + _TIMESTAMPS + _UUID
1547 def UpgradeConfig(self):
1548 """Fill defaults for missing configuration values.
1551 # pylint: disable=E0203
1552 # because these are "defined" via slots, not manually
1553 if self.hvparams is None:
1554 self.hvparams = constants.HVC_DEFAULTS
1556 for hypervisor in self.hvparams:
1557 self.hvparams[hypervisor] = FillDict(
1558 constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1560 if self.os_hvp is None:
1563 # osparams added before 2.2
1564 if self.osparams is None:
1567 self.ndparams = UpgradeNDParams(self.ndparams)
1569 self.beparams = UpgradeGroupedParams(self.beparams,
1570 constants.BEC_DEFAULTS)
1571 for beparams_group in self.beparams:
1572 UpgradeBeParams(self.beparams[beparams_group])
1574 migrate_default_bridge = not self.nicparams
1575 self.nicparams = UpgradeGroupedParams(self.nicparams,
1576 constants.NICC_DEFAULTS)
1577 if migrate_default_bridge:
1578 self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1581 if self.modify_etc_hosts is None:
1582 self.modify_etc_hosts = True
1584 if self.modify_ssh_setup is None:
1585 self.modify_ssh_setup = True
1587 # default_bridge is no longer used in 2.1. The slot is left there to
1588 # support auto-upgrading. It can be removed once we decide to deprecate
1589 # upgrading straight from 2.0.
1590 if self.default_bridge is not None:
1591 self.default_bridge = None
1593 # default_hypervisor is just the first enabled one in 2.1. This slot and
1594 # code can be removed once upgrading straight from 2.0 is deprecated.
1595 if self.default_hypervisor is not None:
1596 self.enabled_hypervisors = ([self.default_hypervisor] +
1597 [hvname for hvname in self.enabled_hypervisors
1598 if hvname != self.default_hypervisor])
1599 self.default_hypervisor = None
1601 # maintain_node_health added after 2.1.1
1602 if self.maintain_node_health is None:
1603 self.maintain_node_health = False
1605 if self.uid_pool is None:
1608 if self.default_iallocator is None:
1609 self.default_iallocator = ""
1611 # reserved_lvs added before 2.2
1612 if self.reserved_lvs is None:
1613 self.reserved_lvs = []
1615 # hidden and blacklisted operating systems added before 2.2.1
1616 if self.hidden_os is None:
1619 if self.blacklisted_os is None:
1620 self.blacklisted_os = []
1622 # primary_ip_family added before 2.3
1623 if self.primary_ip_family is None:
1624 self.primary_ip_family = AF_INET
1626 if self.master_netmask is None:
1627 ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1628 self.master_netmask = ipcls.iplen
1630 if self.prealloc_wipe_disks is None:
1631 self.prealloc_wipe_disks = False
1633 # shared_file_storage_dir added before 2.5
1634 if self.shared_file_storage_dir is None:
1635 self.shared_file_storage_dir = ""
1637 if self.use_external_mip_script is None:
1638 self.use_external_mip_script = False
1641 self.diskparams = UpgradeDiskParams(self.diskparams)
1643 self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1645 # instance policy added before 2.6
1646 if self.ipolicy is None:
1647 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1649 # we can either make sure to upgrade the ipolicy always, or only
1650 # do it in some corner cases (e.g. missing keys); note that this
1651 # will break any removal of keys from the ipolicy dict
1652 wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1654 # These keys would be silently removed by FillIPolicy()
1655 msg = ("Cluster instance policy contains spurious keys: %s" %
1656 utils.CommaJoin(wrongkeys))
1657 raise errors.ConfigurationError(msg)
1658 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1661 def primary_hypervisor(self):
1662 """The first hypervisor is the primary.
1664 Useful, for example, for L{Node}'s hv/disk state.
1667 return self.enabled_hypervisors[0]
1670 """Custom function for cluster.
1673 mydict = super(Cluster, self).ToDict()
1675 if self.tcpudp_port_pool is None:
1676 tcpudp_port_pool = []
1678 tcpudp_port_pool = list(self.tcpudp_port_pool)
1680 mydict["tcpudp_port_pool"] = tcpudp_port_pool
1685 def FromDict(cls, val):
1686 """Custom function for cluster.
1689 obj = super(Cluster, cls).FromDict(val)
1691 if obj.tcpudp_port_pool is None:
1692 obj.tcpudp_port_pool = set()
1693 elif not isinstance(obj.tcpudp_port_pool, set):
1694 obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1698 def SimpleFillDP(self, diskparams):
1699 """Fill a given diskparams dict with cluster defaults.
1701 @param diskparams: The diskparams
1702 @return: The defaults dict
1705 return FillDiskParams(self.diskparams, diskparams)
1707 def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1708 """Get the default hypervisor parameters for the cluster.
1710 @param hypervisor: the hypervisor name
1711 @param os_name: if specified, we'll also update the defaults for this OS
1712 @param skip_keys: if passed, list of keys not to use
1713 @return: the defaults dict
1716 if skip_keys is None:
1719 fill_stack = [self.hvparams.get(hypervisor, {})]
1720 if os_name is not None:
1721 os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1722 fill_stack.append(os_hvp)
1725 for o_dict in fill_stack:
1726 ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1730 def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1731 """Fill a given hvparams dict with cluster defaults.
1733 @type hv_name: string
1734 @param hv_name: the hypervisor to use
1735 @type os_name: string
1736 @param os_name: the OS to use for overriding the hypervisor defaults
1737 @type skip_globals: boolean
1738 @param skip_globals: if True, the global hypervisor parameters will
1741 @return: a copy of the given hvparams with missing keys filled from
1742 the cluster defaults
1746 skip_keys = constants.HVC_GLOBALS
1750 def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1751 return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1753 def FillHV(self, instance, skip_globals=False):
1754 """Fill an instance's hvparams dict with cluster defaults.
1756 @type instance: L{objects.Instance}
1757 @param instance: the instance parameter to fill
1758 @type skip_globals: boolean
1759 @param skip_globals: if True, the global hypervisor parameters will
1762 @return: a copy of the instance's hvparams with missing keys filled from
1763 the cluster defaults
1766 return self.SimpleFillHV(instance.hypervisor, instance.os,
1767 instance.hvparams, skip_globals)
1769 def SimpleFillBE(self, beparams):
1770 """Fill a given beparams dict with cluster defaults.
1772 @type beparams: dict
1773 @param beparams: the dict to fill
1775 @return: a copy of the passed in beparams with missing keys filled
1776 from the cluster defaults
1779 return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1781 def FillBE(self, instance):
1782 """Fill an instance's beparams dict with cluster defaults.
1784 @type instance: L{objects.Instance}
1785 @param instance: the instance parameter to fill
1787 @return: a copy of the instance's beparams with missing keys filled from
1788 the cluster defaults
1791 return self.SimpleFillBE(instance.beparams)
1793 def SimpleFillNIC(self, nicparams):
1794 """Fill a given nicparams dict with cluster defaults.
1796 @type nicparams: dict
1797 @param nicparams: the dict to fill
1799 @return: a copy of the passed in nicparams with missing keys filled
1800 from the cluster defaults
1803 return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1805 def SimpleFillOS(self, os_name, os_params):
1806 """Fill an instance's osparams dict with cluster defaults.
1808 @type os_name: string
1809 @param os_name: the OS name to use
1810 @type os_params: dict
1811 @param os_params: the dict to fill with default values
1813 @return: a copy of the instance's osparams with missing keys filled from
1814 the cluster defaults
1817 name_only = os_name.split("+", 1)[0]
1819 result = self.osparams.get(name_only, {})
1821 result = FillDict(result, self.osparams.get(os_name, {}))
1823 return FillDict(result, os_params)
1826 def SimpleFillHvState(hv_state):
1827 """Fill an hv_state sub dict with cluster defaults.
1830 return FillDict(constants.HVST_DEFAULTS, hv_state)
1833 def SimpleFillDiskState(disk_state):
1834 """Fill an disk_state sub dict with cluster defaults.
1837 return FillDict(constants.DS_DEFAULTS, disk_state)
1839 def FillND(self, node, nodegroup):
1840 """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1842 @type node: L{objects.Node}
1843 @param node: A Node object to fill
1844 @type nodegroup: L{objects.NodeGroup}
1845 @param nodegroup: A Node object to fill
1846 @return a copy of the node's ndparams with defaults filled
1849 return self.SimpleFillND(nodegroup.FillND(node))
1851 def SimpleFillND(self, ndparams):
1852 """Fill a given ndparams dict with defaults.
1854 @type ndparams: dict
1855 @param ndparams: the dict to fill
1857 @return: a copy of the passed in ndparams with missing keys filled
1858 from the cluster defaults
1861 return FillDict(self.ndparams, ndparams)
1863 def SimpleFillIPolicy(self, ipolicy):
1864 """ Fill instance policy dict with defaults.
1867 @param ipolicy: the dict to fill
1869 @return: a copy of passed ipolicy with missing keys filled from
1870 the cluster defaults
1873 return FillIPolicy(self.ipolicy, ipolicy)
1876 class BlockDevStatus(ConfigObject):
1877 """Config object representing the status of a block device."""
1889 class ImportExportStatus(ConfigObject):
1890 """Config object representing the status of an import or export."""
1896 "progress_throughput",
1904 class ImportExportOptions(ConfigObject):
1905 """Options for import/export daemon
1907 @ivar key_name: X509 key name (None for cluster certificate)
1908 @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1909 @ivar compress: Compression method (one of L{constants.IEC_ALL})
1910 @ivar magic: Used to ensure the connection goes to the right disk
1911 @ivar ipv6: Whether to use IPv6
1912 @ivar connect_timeout: Number of seconds for establishing connection
1925 class ConfdRequest(ConfigObject):
1926 """Object holding a confd request.
1928 @ivar protocol: confd protocol version
1929 @ivar type: confd query type
1930 @ivar query: query request
1931 @ivar rsalt: requested reply salt
1942 class ConfdReply(ConfigObject):
1943 """Object holding a confd reply.
1945 @ivar protocol: confd protocol version
1946 @ivar status: reply status code (ok, error)
1947 @ivar answer: confd query reply
1948 @ivar serial: configuration serial number
1959 class QueryFieldDefinition(ConfigObject):
1960 """Object holding a query field definition.
1962 @ivar name: Field name
1963 @ivar title: Human-readable title
1964 @ivar kind: Field type
1965 @ivar doc: Human-readable description
1976 class _QueryResponseBase(ConfigObject):
1982 """Custom function for serializing.
1985 mydict = super(_QueryResponseBase, self).ToDict()
1986 mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
1990 def FromDict(cls, val):
1991 """Custom function for de-serializing.
1994 obj = super(_QueryResponseBase, cls).FromDict(val)
1996 outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2000 class QueryResponse(_QueryResponseBase):
2001 """Object holding the response to a query.
2003 @ivar fields: List of L{QueryFieldDefinition} objects
2004 @ivar data: Requested data
2012 class QueryFieldsRequest(ConfigObject):
2013 """Object holding a request for querying available fields.
2022 class QueryFieldsResponse(_QueryResponseBase):
2023 """Object holding the response to a query for fields.
2025 @ivar fields: List of L{QueryFieldDefinition} objects
2031 class MigrationStatus(ConfigObject):
2032 """Object holding the status of a migration.
2042 class InstanceConsole(ConfigObject):
2043 """Object describing how to access the console of an instance.
2058 """Validates contents of this object.
2061 assert self.kind in constants.CONS_ALL, "Unknown console type"
2062 assert self.instance, "Missing instance name"
2063 assert self.message or self.kind in [constants.CONS_SSH,
2064 constants.CONS_SPICE,
2066 assert self.host or self.kind == constants.CONS_MESSAGE
2067 assert self.port or self.kind in [constants.CONS_MESSAGE,
2069 assert self.user or self.kind in [constants.CONS_MESSAGE,
2070 constants.CONS_SPICE,
2072 assert self.command or self.kind in [constants.CONS_MESSAGE,
2073 constants.CONS_SPICE,
2075 assert self.display or self.kind in [constants.CONS_MESSAGE,
2076 constants.CONS_SPICE,
2081 class Network(TaggableObject):
2082 """Object representing a network definition for ganeti.
2095 ] + _TIMESTAMPS + _UUID
2097 def HooksDict(self, prefix=""):
2098 """Export a dictionary used by hooks with a network's information.
2100 @type prefix: String
2101 @param prefix: Prefix to prepend to the dict entries
2105 "%sNETWORK_NAME" % prefix: self.name,
2106 "%sNETWORK_UUID" % prefix: self.uuid,
2107 "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2110 result["%sNETWORK_SUBNET" % prefix] = self.network
2112 result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2114 result["%sNETWORK_SUBNET6" % prefix] = self.network6
2116 result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2118 result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2123 def FromDict(cls, val):
2124 """Custom function for networks.
2126 Remove deprecated network_type and family.
2129 if "network_type" in val:
2130 del val["network_type"]
2133 obj = super(Network, cls).FromDict(val)
2137 class SerializableConfigParser(ConfigParser.SafeConfigParser):
2138 """Simple wrapper over ConfigParse that allows serialization.
2140 This class is basically ConfigParser.SafeConfigParser with two
2141 additional methods that allow it to serialize/unserialize to/from a
2146 """Dump this instance and return the string representation."""
2149 return buf.getvalue()
2152 def Loads(cls, data):
2153 """Load data from a string."""
2154 buf = StringIO(data)
2160 class LvmPvInfo(ConfigObject):
2161 """Information about an LVM physical volume (PV).
2164 @ivar name: name of the PV
2165 @type vg_name: string
2166 @ivar vg_name: name of the volume group containing the PV
2168 @ivar size: size of the PV in MiB
2170 @ivar free: free space in the PV, in MiB
2171 @type attributes: string
2172 @ivar attributes: PV attributes
2173 @type lv_list: list of strings
2174 @ivar lv_list: names of the LVs hosted on the PV
2186 """Is this PV empty?
2189 return self.size <= (self.free + 1)
2191 def IsAllocatable(self):
2192 """Is this PV allocatable?
2195 return ("a" in self.attributes)