4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 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 explicitely initialise its members
34 # W0201: Attribute '%s' defined outside __init__
36 # R0902: Allow instances of these objects to have more than 20 attributes
42 from cStringIO import StringIO
44 from ganeti import errors
45 from ganeti import constants
46 from ganeti import netutils
47 from ganeti import utils
49 from socket import AF_INET
52 __all__ = ["ConfigObject", "ConfigData", "NIC", "Disk", "Instance",
53 "OS", "Node", "NodeGroup", "Cluster", "FillDict"]
55 _TIMESTAMPS = ["ctime", "mtime"]
58 # constants used to create InstancePolicy dictionary
59 TISPECS_GROUP_TYPES = {
60 constants.ISPECS_MIN: constants.VTYPE_INT,
61 constants.ISPECS_MAX: constants.VTYPE_INT,
64 TISPECS_CLUSTER_TYPES = {
65 constants.ISPECS_MIN: constants.VTYPE_INT,
66 constants.ISPECS_MAX: constants.VTYPE_INT,
67 constants.ISPECS_STD: constants.VTYPE_INT,
71 def FillDict(defaults_dict, custom_dict, skip_keys=None):
72 """Basic function to apply settings on top a default dict.
74 @type defaults_dict: dict
75 @param defaults_dict: dictionary holding the default values
76 @type custom_dict: dict
77 @param custom_dict: dictionary holding customized value
79 @param skip_keys: which keys not to fill
81 @return: dict with the 'full' values
84 ret_dict = copy.deepcopy(defaults_dict)
85 ret_dict.update(custom_dict)
95 def FillIPolicy(default_ipolicy, custom_ipolicy, skip_keys=None):
96 """Fills an instance policy with defaults.
99 assert frozenset(default_ipolicy.keys()) == constants.IPOLICY_ALL_KEYS
101 for key in constants.IPOLICY_ISPECS:
102 ret_dict[key] = FillDict(default_ipolicy[key],
103 custom_ipolicy.get(key, {}),
106 for key in [constants.IPOLICY_DTS]:
107 ret_dict[key] = list(custom_ipolicy.get(key, default_ipolicy[key]))
108 # other items which we know we can directly copy (immutables)
109 for key in constants.IPOLICY_PARAMETERS:
110 ret_dict[key] = custom_ipolicy.get(key, default_ipolicy[key])
115 def FillDiskParams(default_dparams, custom_dparams, skip_keys=None):
116 """Fills the disk parameter defaults.
118 @see: L{FillDict} for parameters and return value
121 assert frozenset(default_dparams.keys()) == constants.DISK_TEMPLATES
123 return dict((dt, FillDict(default_dparams[dt], custom_dparams.get(dt, {}),
124 skip_keys=skip_keys))
125 for dt in constants.DISK_TEMPLATES)
128 def UpgradeGroupedParams(target, defaults):
129 """Update all groups for the target parameter.
131 @type target: dict of dicts
132 @param target: {group: {parameter: value}}
134 @param defaults: default parameter values
138 target = {constants.PP_DEFAULT: defaults}
141 target[group] = FillDict(defaults, target[group])
145 def UpgradeBeParams(target):
146 """Update the be parameters dict to the new format.
149 @param target: "be" parameters dict
152 if constants.BE_MEMORY in target:
153 memory = target[constants.BE_MEMORY]
154 target[constants.BE_MAXMEM] = memory
155 target[constants.BE_MINMEM] = memory
156 del target[constants.BE_MEMORY]
159 def UpgradeDiskParams(diskparams):
160 """Upgrade the disk parameters.
162 @type diskparams: dict
163 @param diskparams: disk parameters to upgrade
165 @return: the upgraded disk parameters dict
171 result = FillDiskParams(constants.DISK_DT_DEFAULTS, diskparams)
176 def UpgradeNDParams(ndparams):
177 """Upgrade ndparams structure.
180 @param ndparams: disk parameters to upgrade
182 @return: the upgraded node parameters dict
188 return FillDict(constants.NDC_DEFAULTS, ndparams)
191 def MakeEmptyIPolicy():
192 """Create empty IPolicy dictionary.
196 (constants.ISPECS_MIN, {}),
197 (constants.ISPECS_MAX, {}),
198 (constants.ISPECS_STD, {}),
202 def CreateIPolicyFromOpts(ispecs_mem_size=None,
203 ispecs_cpu_count=None,
204 ispecs_disk_count=None,
205 ispecs_disk_size=None,
206 ispecs_nic_count=None,
207 ipolicy_disk_templates=None,
208 ipolicy_vcpu_ratio=None,
212 """Creation of instance policy based on command line options.
214 @param fill_all: whether for cluster policies we should ensure that
215 all values are filled
219 # prepare ipolicy dict
220 ipolicy_transposed = {
221 constants.ISPEC_MEM_SIZE: ispecs_mem_size,
222 constants.ISPEC_CPU_COUNT: ispecs_cpu_count,
223 constants.ISPEC_DISK_COUNT: ispecs_disk_count,
224 constants.ISPEC_DISK_SIZE: ispecs_disk_size,
225 constants.ISPEC_NIC_COUNT: ispecs_nic_count,
228 # first, check that the values given are correct
230 forced_type = TISPECS_GROUP_TYPES
232 forced_type = TISPECS_CLUSTER_TYPES
234 for specs in ipolicy_transposed.values():
235 utils.ForceDictType(specs, forced_type, allowed_values=allowed_values)
238 ipolicy_out = MakeEmptyIPolicy()
239 for name, specs in ipolicy_transposed.iteritems():
240 assert name in constants.ISPECS_PARAMETERS
241 for key, val in specs.items(): # {min: .. ,max: .., std: ..}
242 ipolicy_out[key][name] = val
244 # no filldict for non-dicts
245 if not group_ipolicy and fill_all:
246 if ipolicy_disk_templates is None:
247 ipolicy_disk_templates = constants.DISK_TEMPLATES
248 if ipolicy_vcpu_ratio is None:
249 ipolicy_vcpu_ratio = \
250 constants.IPOLICY_DEFAULTS[constants.IPOLICY_VCPU_RATIO]
251 if ipolicy_disk_templates is not None:
252 ipolicy_out[constants.IPOLICY_DTS] = list(ipolicy_disk_templates)
253 if ipolicy_vcpu_ratio is not None:
254 ipolicy_out[constants.IPOLICY_VCPU_RATIO] = ipolicy_vcpu_ratio
256 assert not (frozenset(ipolicy_out.keys()) - constants.IPOLICY_ALL_KEYS)
261 class ConfigObject(object):
262 """A generic config object.
264 It has the following properties:
266 - provides somewhat safe recursive unpickling and pickling for its classes
267 - unset attributes which are defined in slots are always returned
268 as None instead of raising an error
270 Classes derived from this must always declare __slots__ (we use many
271 config objects and the memory reduction is useful)
276 def __init__(self, **kwargs):
277 for k, v in kwargs.iteritems():
280 def __getattr__(self, name):
281 if name not in self._all_slots():
282 raise AttributeError("Invalid object attribute %s.%s" %
283 (type(self).__name__, name))
286 def __setstate__(self, state):
287 slots = self._all_slots()
290 setattr(self, name, state[name])
294 """Compute the list of all declared slots for a class.
298 for parent in cls.__mro__:
299 slots.extend(getattr(parent, "__slots__", []))
302 #: Public getter for the defined slots
303 GetAllSlots = _all_slots
306 """Convert to a dict holding only standard python types.
308 The generic routine just dumps all of this object's attributes in
309 a dict. It does not work if the class has children who are
310 ConfigObjects themselves (e.g. the nics list in an Instance), in
311 which case the object should subclass the function in order to
312 make sure all objects returned are only standard python types.
316 for name in self._all_slots():
317 value = getattr(self, name, None)
318 if value is not None:
322 __getstate__ = ToDict
325 def FromDict(cls, val):
326 """Create an object from a dictionary.
328 This generic routine takes a dict, instantiates a new instance of
329 the given class, and sets attributes based on the dict content.
331 As for `ToDict`, this does not work if the class has children
332 who are ConfigObjects themselves (e.g. the nics list in an
333 Instance), in which case the object should subclass the function
334 and alter the objects.
337 if not isinstance(val, dict):
338 raise errors.ConfigurationError("Invalid object passed to FromDict:"
339 " expected dict, got %s" % type(val))
340 val_str = dict([(str(k), v) for k, v in val.iteritems()])
341 obj = cls(**val_str) # pylint: disable=W0142
345 def _ContainerToDicts(container):
346 """Convert the elements of a container to standard python types.
348 This method converts a container with elements derived from
349 ConfigData to standard python types. If the container is a dict,
350 we don't touch the keys, only the values.
353 if isinstance(container, dict):
354 ret = dict([(k, v.ToDict()) for k, v in container.iteritems()])
355 elif isinstance(container, (list, tuple, set, frozenset)):
356 ret = [elem.ToDict() for elem in container]
358 raise TypeError("Invalid type %s passed to _ContainerToDicts" %
363 def _ContainerFromDicts(source, c_type, e_type):
364 """Convert a container from standard python types.
366 This method converts a container with standard python types to
367 ConfigData objects. If the container is a dict, we don't touch the
368 keys, only the values.
371 if not isinstance(c_type, type):
372 raise TypeError("Container type %s passed to _ContainerFromDicts is"
373 " not a type" % type(c_type))
377 ret = dict([(k, e_type.FromDict(v)) for k, v in source.iteritems()])
378 elif c_type in (list, tuple, set, frozenset):
379 ret = c_type([e_type.FromDict(elem) for elem in source])
381 raise TypeError("Invalid container type %s passed to"
382 " _ContainerFromDicts" % c_type)
386 """Makes a deep copy of the current object and its children.
389 dict_form = self.ToDict()
390 clone_obj = self.__class__.FromDict(dict_form)
394 """Implement __repr__ for ConfigObjects."""
395 return repr(self.ToDict())
397 def UpgradeConfig(self):
398 """Fill defaults for missing configuration values.
400 This method will be called at configuration load time, and its
401 implementation will be object dependent.
407 class TaggableObject(ConfigObject):
408 """An generic class supporting tags.
412 VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
415 def ValidateTag(cls, tag):
416 """Check if a tag is valid.
418 If the tag is invalid, an errors.TagError will be raised. The
419 function has no return value.
422 if not isinstance(tag, basestring):
423 raise errors.TagError("Invalid tag type (not a string)")
424 if len(tag) > constants.MAX_TAG_LEN:
425 raise errors.TagError("Tag too long (>%d characters)" %
426 constants.MAX_TAG_LEN)
428 raise errors.TagError("Tags cannot be empty")
429 if not cls.VALID_TAG_RE.match(tag):
430 raise errors.TagError("Tag contains invalid characters")
433 """Return the tags list.
436 tags = getattr(self, "tags", None)
438 tags = self.tags = set()
441 def AddTag(self, tag):
445 self.ValidateTag(tag)
446 tags = self.GetTags()
447 if len(tags) >= constants.MAX_TAGS_PER_OBJ:
448 raise errors.TagError("Too many tags")
449 self.GetTags().add(tag)
451 def RemoveTag(self, tag):
455 self.ValidateTag(tag)
456 tags = self.GetTags()
460 raise errors.TagError("Tag not found")
463 """Taggable-object-specific conversion to standard python types.
465 This replaces the tags set with a list.
468 bo = super(TaggableObject, self).ToDict()
470 tags = bo.get("tags", None)
471 if isinstance(tags, set):
472 bo["tags"] = list(tags)
476 def FromDict(cls, val):
477 """Custom function for instances.
480 obj = super(TaggableObject, cls).FromDict(val)
481 if hasattr(obj, "tags") and isinstance(obj.tags, list):
482 obj.tags = set(obj.tags)
486 class MasterNetworkParameters(ConfigObject):
487 """Network configuration parameters for the master
489 @ivar name: master name
491 @ivar netmask: master netmask
492 @ivar netdev: master network device
493 @ivar ip_family: master IP family
505 class ConfigData(ConfigObject):
506 """Top-level config object."""
517 """Custom function for top-level config data.
519 This just replaces the list of instances, nodes and the cluster
520 with standard python types.
523 mydict = super(ConfigData, self).ToDict()
524 mydict["cluster"] = mydict["cluster"].ToDict()
525 for key in "nodes", "instances", "nodegroups":
526 mydict[key] = self._ContainerToDicts(mydict[key])
531 def FromDict(cls, val):
532 """Custom function for top-level config data
535 obj = super(ConfigData, cls).FromDict(val)
536 obj.cluster = Cluster.FromDict(obj.cluster)
537 obj.nodes = cls._ContainerFromDicts(obj.nodes, dict, Node)
538 obj.instances = cls._ContainerFromDicts(obj.instances, dict, Instance)
539 obj.nodegroups = cls._ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
542 def HasAnyDiskOfType(self, dev_type):
543 """Check if in there is at disk of the given type in the configuration.
545 @type dev_type: L{constants.LDS_BLOCK}
546 @param dev_type: the type to look for
548 @return: boolean indicating if a disk of the given type was found or not
551 for instance in self.instances.values():
552 for disk in instance.disks:
553 if disk.IsBasedOnDiskType(dev_type):
557 def UpgradeConfig(self):
558 """Fill defaults for missing configuration values.
561 self.cluster.UpgradeConfig()
562 for node in self.nodes.values():
564 for instance in self.instances.values():
565 instance.UpgradeConfig()
566 if self.nodegroups is None:
568 for nodegroup in self.nodegroups.values():
569 nodegroup.UpgradeConfig()
570 if self.cluster.drbd_usermode_helper is None:
571 # To decide if we set an helper let's check if at least one instance has
572 # a DRBD disk. This does not cover all the possible scenarios but it
573 # gives a good approximation.
574 if self.HasAnyDiskOfType(constants.LD_DRBD8):
575 self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
578 class NIC(ConfigObject):
579 """Config object representing a network card."""
580 __slots__ = ["mac", "ip", "nicparams"]
583 def CheckParameterSyntax(cls, nicparams):
584 """Check the given parameters for validity.
586 @type nicparams: dict
587 @param nicparams: dictionary with parameter names/value
588 @raise errors.ConfigurationError: when a parameter is not valid
591 if (nicparams[constants.NIC_MODE] not in constants.NIC_VALID_MODES and
592 nicparams[constants.NIC_MODE] != constants.VALUE_AUTO):
593 err = "Invalid nic mode: %s" % nicparams[constants.NIC_MODE]
594 raise errors.ConfigurationError(err)
596 if (nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED and
597 not nicparams[constants.NIC_LINK]):
598 err = "Missing bridged nic link"
599 raise errors.ConfigurationError(err)
602 class Disk(ConfigObject):
603 """Config object representing a block device."""
604 __slots__ = ["dev_type", "logical_id", "physical_id",
605 "children", "iv_name", "size", "mode", "params"]
607 def CreateOnSecondary(self):
608 """Test if this device needs to be created on a secondary node."""
609 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
611 def AssembleOnSecondary(self):
612 """Test if this device needs to be assembled on a secondary node."""
613 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
615 def OpenOnSecondary(self):
616 """Test if this device needs to be opened on a secondary node."""
617 return self.dev_type in (constants.LD_LV,)
619 def StaticDevPath(self):
620 """Return the device path if this device type has a static one.
622 Some devices (LVM for example) live always at the same /dev/ path,
623 irrespective of their status. For such devices, we return this
624 path, for others we return None.
626 @warning: The path returned is not a normalized pathname; callers
627 should check that it is a valid path.
630 if self.dev_type == constants.LD_LV:
631 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
632 elif self.dev_type == constants.LD_BLOCKDEV:
633 return self.logical_id[1]
634 elif self.dev_type == constants.LD_RBD:
635 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
638 def ChildrenNeeded(self):
639 """Compute the needed number of children for activation.
641 This method will return either -1 (all children) or a positive
642 number denoting the minimum number of children needed for
643 activation (only mirrored devices will usually return >=0).
645 Currently, only DRBD8 supports diskless activation (therefore we
646 return 0), for all other we keep the previous semantics and return
650 if self.dev_type == constants.LD_DRBD8:
654 def IsBasedOnDiskType(self, dev_type):
655 """Check if the disk or its children are based on the given type.
657 @type dev_type: L{constants.LDS_BLOCK}
658 @param dev_type: the type to look for
660 @return: boolean indicating if a device of the given type was found or not
664 for child in self.children:
665 if child.IsBasedOnDiskType(dev_type):
667 return self.dev_type == dev_type
669 def GetNodes(self, node):
670 """This function returns the nodes this device lives on.
672 Given the node on which the parent of the device lives on (or, in
673 case of a top-level device, the primary node of the devices'
674 instance), this function will return a list of nodes on which this
675 devices needs to (or can) be assembled.
678 if self.dev_type in [constants.LD_LV, constants.LD_FILE,
679 constants.LD_BLOCKDEV, constants.LD_RBD]:
681 elif self.dev_type in constants.LDS_DRBD:
682 result = [self.logical_id[0], self.logical_id[1]]
683 if node not in result:
684 raise errors.ConfigurationError("DRBD device passed unknown node")
686 raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
689 def ComputeNodeTree(self, parent_node):
690 """Compute the node/disk tree for this disk and its children.
692 This method, given the node on which the parent disk lives, will
693 return the list of all (node, disk) pairs which describe the disk
694 tree in the most compact way. For example, a drbd/lvm stack
695 will be returned as (primary_node, drbd) and (secondary_node, drbd)
696 which represents all the top-level devices on the nodes.
699 my_nodes = self.GetNodes(parent_node)
700 result = [(node, self) for node in my_nodes]
701 if not self.children:
704 for node in my_nodes:
705 for child in self.children:
706 child_result = child.ComputeNodeTree(node)
707 if len(child_result) == 1:
708 # child (and all its descendants) is simple, doesn't split
709 # over multiple hosts, so we don't need to describe it, our
710 # own entry for this node describes it completely
713 # check if child nodes differ from my nodes; note that
714 # subdisk can differ from the child itself, and be instead
715 # one of its descendants
716 for subnode, subdisk in child_result:
717 if subnode not in my_nodes:
718 result.append((subnode, subdisk))
719 # otherwise child is under our own node, so we ignore this
720 # entry (but probably the other results in the list will
724 def ComputeGrowth(self, amount):
725 """Compute the per-VG growth requirements.
727 This only works for VG-based disks.
729 @type amount: integer
730 @param amount: the desired increase in (user-visible) disk space
732 @return: a dictionary of volume-groups and the required size
735 if self.dev_type == constants.LD_LV:
736 return {self.logical_id[0]: amount}
737 elif self.dev_type == constants.LD_DRBD8:
739 return self.children[0].ComputeGrowth(amount)
743 # Other disk types do not require VG space
746 def RecordGrow(self, amount):
747 """Update the size of this disk after growth.
749 This method recurses over the disks's children and updates their
750 size correspondigly. The method needs to be kept in sync with the
751 actual algorithms from bdev.
754 if self.dev_type in (constants.LD_LV, constants.LD_FILE,
757 elif self.dev_type == constants.LD_DRBD8:
759 self.children[0].RecordGrow(amount)
762 raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
763 " disk type %s" % self.dev_type)
765 def Update(self, size=None, mode=None):
766 """Apply changes to size and mode.
769 if self.dev_type == constants.LD_DRBD8:
771 self.children[0].Update(size=size, mode=mode)
773 assert not self.children
781 """Sets recursively the size to zero for the disk and its children.
785 for child in self.children:
789 def SetPhysicalID(self, target_node, nodes_ip):
790 """Convert the logical ID to the physical ID.
792 This is used only for drbd, which needs ip/port configuration.
794 The routine descends down and updates its children also, because
795 this helps when the only the top device is passed to the remote
799 - target_node: the node we wish to configure for
800 - nodes_ip: a mapping of node name to ip
802 The target_node must exist in in nodes_ip, and must be one of the
803 nodes in the logical ID for each of the DRBD devices encountered
808 for child in self.children:
809 child.SetPhysicalID(target_node, nodes_ip)
811 if self.logical_id is None and self.physical_id is not None:
813 if self.dev_type in constants.LDS_DRBD:
814 pnode, snode, port, pminor, sminor, secret = self.logical_id
815 if target_node not in (pnode, snode):
816 raise errors.ConfigurationError("DRBD device not knowing node %s" %
818 pnode_ip = nodes_ip.get(pnode, None)
819 snode_ip = nodes_ip.get(snode, None)
820 if pnode_ip is None or snode_ip is None:
821 raise errors.ConfigurationError("Can't find primary or secondary node"
822 " for %s" % str(self))
823 p_data = (pnode_ip, port)
824 s_data = (snode_ip, port)
825 if pnode == target_node:
826 self.physical_id = p_data + s_data + (pminor, secret)
827 else: # it must be secondary, we tested above
828 self.physical_id = s_data + p_data + (sminor, secret)
830 self.physical_id = self.logical_id
834 """Disk-specific conversion to standard python types.
836 This replaces the children lists of objects with lists of
837 standard python types.
840 bo = super(Disk, self).ToDict()
842 for attr in ("children",):
843 alist = bo.get(attr, None)
845 bo[attr] = self._ContainerToDicts(alist)
849 def FromDict(cls, val):
850 """Custom function for Disks
853 obj = super(Disk, cls).FromDict(val)
855 obj.children = cls._ContainerFromDicts(obj.children, list, Disk)
856 if obj.logical_id and isinstance(obj.logical_id, list):
857 obj.logical_id = tuple(obj.logical_id)
858 if obj.physical_id and isinstance(obj.physical_id, list):
859 obj.physical_id = tuple(obj.physical_id)
860 if obj.dev_type in constants.LDS_DRBD:
861 # we need a tuple of length six here
862 if len(obj.logical_id) < 6:
863 obj.logical_id += (None,) * (6 - len(obj.logical_id))
867 """Custom str() formatter for disks.
870 if self.dev_type == constants.LD_LV:
871 val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
872 elif self.dev_type in constants.LDS_DRBD:
873 node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
875 if self.physical_id is None:
878 phy = ("configured as %s:%s %s:%s" %
879 (self.physical_id[0], self.physical_id[1],
880 self.physical_id[2], self.physical_id[3]))
882 val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
883 (node_a, minor_a, node_b, minor_b, port, phy))
884 if self.children and self.children.count(None) == 0:
885 val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
887 val += "no local storage"
889 val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
890 (self.dev_type, self.logical_id, self.physical_id, self.children))
891 if self.iv_name is None:
892 val += ", not visible"
894 val += ", visible as /dev/%s" % self.iv_name
895 if isinstance(self.size, int):
896 val += ", size=%dm)>" % self.size
898 val += ", size='%s')>" % (self.size,)
902 """Checks that this disk is correctly configured.
906 if self.mode not in constants.DISK_ACCESS_SET:
907 all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
910 def UpgradeConfig(self):
911 """Fill defaults for missing configuration values.
915 for child in self.children:
916 child.UpgradeConfig()
919 self.params = constants.DISK_LD_DEFAULTS[self.dev_type].copy()
921 self.params = FillDict(constants.DISK_LD_DEFAULTS[self.dev_type],
923 # add here config upgrade for this disk
926 def ComputeLDParams(disk_template, disk_params):
927 """Computes Logical Disk parameters from Disk Template parameters.
929 @type disk_template: string
930 @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
931 @type disk_params: dict
932 @param disk_params: disk template parameters;
933 dict(template_name -> parameters
935 @return: a list of dicts, one for each node of the disk hierarchy. Each dict
936 contains the LD parameters of the node. The tree is flattened in-order.
939 if disk_template not in constants.DISK_TEMPLATES:
940 raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
942 assert disk_template in disk_params
945 dt_params = disk_params[disk_template]
946 if disk_template == constants.DT_DRBD8:
948 constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
949 constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
950 constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
951 constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
952 constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
953 constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
954 constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
955 constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
956 constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
957 constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
958 constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
959 constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
963 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8],
966 result.append(drbd_params)
970 constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
973 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
975 result.append(data_params)
979 constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
982 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
984 result.append(meta_params)
986 elif (disk_template == constants.DT_FILE or
987 disk_template == constants.DT_SHARED_FILE):
988 result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
990 elif disk_template == constants.DT_PLAIN:
992 constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
995 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
997 result.append(params)
999 elif disk_template == constants.DT_BLOCK:
1000 result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
1002 elif disk_template == constants.DT_RBD:
1004 constants.LDP_POOL: dt_params[constants.RBD_POOL]
1007 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD],
1009 result.append(params)
1014 class InstancePolicy(ConfigObject):
1015 """Config object representing instance policy limits dictionary.
1018 Note that this object is not actually used in the config, it's just
1019 used as a placeholder for a few functions.
1023 def CheckParameterSyntax(cls, ipolicy):
1024 """ Check the instance policy for validity.
1027 for param in constants.ISPECS_PARAMETERS:
1028 InstancePolicy.CheckISpecSyntax(ipolicy, param)
1029 if constants.IPOLICY_DTS in ipolicy:
1030 InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
1031 for key in constants.IPOLICY_PARAMETERS:
1033 InstancePolicy.CheckParameter(key, ipolicy[key])
1034 wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1036 raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
1037 utils.CommaJoin(wrong_keys))
1040 def CheckISpecSyntax(cls, ipolicy, name):
1041 """Check the instance policy for validity on a given key.
1043 We check if the instance policy makes sense for a given key, that is
1044 if ipolicy[min][name] <= ipolicy[std][name] <= ipolicy[max][name].
1047 @param ipolicy: dictionary with min, max, std specs
1049 @param name: what are the limits for
1050 @raise errors.ConfigureError: when specs for given name are not valid
1053 min_v = ipolicy[constants.ISPECS_MIN].get(name, 0)
1054 std_v = ipolicy[constants.ISPECS_STD].get(name, min_v)
1055 max_v = ipolicy[constants.ISPECS_MAX].get(name, std_v)
1056 err = ("Invalid specification of min/max/std values for %s: %s/%s/%s" %
1058 ipolicy[constants.ISPECS_MIN].get(name, "-"),
1059 ipolicy[constants.ISPECS_MAX].get(name, "-"),
1060 ipolicy[constants.ISPECS_STD].get(name, "-")))
1061 if min_v > std_v or std_v > max_v:
1062 raise errors.ConfigurationError(err)
1065 def CheckDiskTemplates(cls, disk_templates):
1066 """Checks the disk templates for validity.
1069 wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1071 raise errors.ConfigurationError("Invalid disk template(s) %s" %
1072 utils.CommaJoin(wrong))
1075 def CheckParameter(cls, key, value):
1076 """Checks a parameter.
1078 Currently we expect all parameters to be float values.
1083 except (TypeError, ValueError), err:
1084 raise errors.ConfigurationError("Invalid value for key" " '%s':"
1085 " '%s', error: %s" % (key, value, err))
1088 class Instance(TaggableObject):
1089 """Config object representing an instance."""
1104 ] + _TIMESTAMPS + _UUID
1106 def _ComputeSecondaryNodes(self):
1107 """Compute the list of secondary nodes.
1109 This is a simple wrapper over _ComputeAllNodes.
1112 all_nodes = set(self._ComputeAllNodes())
1113 all_nodes.discard(self.primary_node)
1114 return tuple(all_nodes)
1116 secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1117 "List of secondary nodes")
1119 def _ComputeAllNodes(self):
1120 """Compute the list of all nodes.
1122 Since the data is already there (in the drbd disks), keeping it as
1123 a separate normal attribute is redundant and if not properly
1124 synchronised can cause problems. Thus it's better to compute it
1128 def _Helper(nodes, device):
1129 """Recursively computes nodes given a top device."""
1130 if device.dev_type in constants.LDS_DRBD:
1131 nodea, nodeb = device.logical_id[:2]
1135 for child in device.children:
1136 _Helper(nodes, child)
1139 all_nodes.add(self.primary_node)
1140 for device in self.disks:
1141 _Helper(all_nodes, device)
1142 return tuple(all_nodes)
1144 all_nodes = property(_ComputeAllNodes, None, None,
1145 "List of all nodes of the instance")
1147 def MapLVsByNode(self, lvmap=None, devs=None, node=None):
1148 """Provide a mapping of nodes to LVs this instance owns.
1150 This function figures out what logical volumes should belong on
1151 which nodes, recursing through a device tree.
1153 @param lvmap: optional dictionary to receive the
1154 'node' : ['lv', ...] data.
1156 @return: None if lvmap arg is given, otherwise, a dictionary of
1157 the form { 'nodename' : ['volume1', 'volume2', ...], ... };
1158 volumeN is of the form "vg_name/lv_name", compatible with
1163 node = self.primary_node
1171 if not node in lvmap:
1179 if dev.dev_type == constants.LD_LV:
1180 lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1182 elif dev.dev_type in constants.LDS_DRBD:
1184 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1185 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1188 self.MapLVsByNode(lvmap, dev.children, node)
1192 def FindDisk(self, idx):
1193 """Find a disk given having a specified index.
1195 This is just a wrapper that does validation of the index.
1198 @param idx: the disk index
1200 @return: the corresponding disk
1201 @raise errors.OpPrereqError: when the given index is not valid
1206 return self.disks[idx]
1207 except (TypeError, ValueError), err:
1208 raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1211 raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1212 " 0 to %d" % (idx, len(self.disks) - 1),
1216 """Instance-specific conversion to standard python types.
1218 This replaces the children lists of objects with lists of standard
1222 bo = super(Instance, self).ToDict()
1224 for attr in "nics", "disks":
1225 alist = bo.get(attr, None)
1227 nlist = self._ContainerToDicts(alist)
1234 def FromDict(cls, val):
1235 """Custom function for instances.
1238 if "admin_state" not in val:
1239 if val.get("admin_up", False):
1240 val["admin_state"] = constants.ADMINST_UP
1242 val["admin_state"] = constants.ADMINST_DOWN
1243 if "admin_up" in val:
1245 obj = super(Instance, cls).FromDict(val)
1246 obj.nics = cls._ContainerFromDicts(obj.nics, list, NIC)
1247 obj.disks = cls._ContainerFromDicts(obj.disks, list, Disk)
1250 def UpgradeConfig(self):
1251 """Fill defaults for missing configuration values.
1254 for nic in self.nics:
1256 for disk in self.disks:
1257 disk.UpgradeConfig()
1259 for key in constants.HVC_GLOBALS:
1261 del self.hvparams[key]
1264 if self.osparams is None:
1266 UpgradeBeParams(self.beparams)
1269 class OS(ConfigObject):
1270 """Config object representing an operating system.
1272 @type supported_parameters: list
1273 @ivar supported_parameters: a list of tuples, name and description,
1274 containing the supported parameters by this OS
1276 @type VARIANT_DELIM: string
1277 @cvar VARIANT_DELIM: the variant delimiter
1289 "supported_variants",
1290 "supported_parameters",
1296 def SplitNameVariant(cls, name):
1297 """Splits the name into the proper name and variant.
1299 @param name: the OS (unprocessed) name
1301 @return: a list of two elements; if the original name didn't
1302 contain a variant, it's returned as an empty string
1305 nv = name.split(cls.VARIANT_DELIM, 1)
1311 def GetName(cls, name):
1312 """Returns the proper name of the os (without the variant).
1314 @param name: the OS (unprocessed) name
1317 return cls.SplitNameVariant(name)[0]
1320 def GetVariant(cls, name):
1321 """Returns the variant the os (without the base name).
1323 @param name: the OS (unprocessed) name
1326 return cls.SplitNameVariant(name)[1]
1329 class NodeHvState(ConfigObject):
1330 """Hypvervisor state on a node.
1332 @ivar mem_total: Total amount of memory
1333 @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1335 @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1337 @ivar mem_inst: Memory used by instances living on node
1338 @ivar cpu_total: Total node CPU core count
1339 @ivar cpu_node: Number of CPU cores reserved for the node itself
1352 class NodeDiskState(ConfigObject):
1353 """Disk state on a node.
1363 class Node(TaggableObject):
1364 """Config object representing a node.
1366 @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1367 @ivar hv_state_static: Hypervisor state overriden by user
1368 @ivar disk_state: Disk state (e.g. free space)
1369 @ivar disk_state_static: Disk state overriden by user
1388 "disk_state_static",
1389 ] + _TIMESTAMPS + _UUID
1391 def UpgradeConfig(self):
1392 """Fill defaults for missing configuration values.
1395 # pylint: disable=E0203
1396 # because these are "defined" via slots, not manually
1397 if self.master_capable is None:
1398 self.master_capable = True
1400 if self.vm_capable is None:
1401 self.vm_capable = True
1403 if self.ndparams is None:
1406 if self.powered is None:
1410 """Custom function for serializing.
1413 data = super(Node, self).ToDict()
1415 hv_state = data.get("hv_state", None)
1416 if hv_state is not None:
1417 data["hv_state"] = self._ContainerToDicts(hv_state)
1419 disk_state = data.get("disk_state", None)
1420 if disk_state is not None:
1421 data["disk_state"] = \
1422 dict((key, self._ContainerToDicts(value))
1423 for (key, value) in disk_state.items())
1428 def FromDict(cls, val):
1429 """Custom function for deserializing.
1432 obj = super(Node, cls).FromDict(val)
1434 if obj.hv_state is not None:
1435 obj.hv_state = cls._ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1437 if obj.disk_state is not None:
1439 dict((key, cls._ContainerFromDicts(value, dict, NodeDiskState))
1440 for (key, value) in obj.disk_state.items())
1445 class NodeGroup(TaggableObject):
1446 """Config object representing a node group."""
1455 "disk_state_static",
1457 ] + _TIMESTAMPS + _UUID
1460 """Custom function for nodegroup.
1462 This discards the members object, which gets recalculated and is only kept
1466 mydict = super(NodeGroup, self).ToDict()
1467 del mydict["members"]
1471 def FromDict(cls, val):
1472 """Custom function for nodegroup.
1474 The members slot is initialized to an empty list, upon deserialization.
1477 obj = super(NodeGroup, cls).FromDict(val)
1481 def UpgradeConfig(self):
1482 """Fill defaults for missing configuration values.
1485 if self.ndparams is None:
1488 if self.serial_no is None:
1491 if self.alloc_policy is None:
1492 self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1494 # We only update mtime, and not ctime, since we would not be able
1495 # to provide a correct value for creation time.
1496 if self.mtime is None:
1497 self.mtime = time.time()
1499 if self.diskparams is None:
1500 self.diskparams = {}
1501 if self.ipolicy is None:
1502 self.ipolicy = MakeEmptyIPolicy()
1504 def FillND(self, node):
1505 """Return filled out ndparams for L{objects.Node}
1507 @type node: L{objects.Node}
1508 @param node: A Node object to fill
1509 @return a copy of the node's ndparams with defaults filled
1512 return self.SimpleFillND(node.ndparams)
1514 def SimpleFillND(self, ndparams):
1515 """Fill a given ndparams dict with defaults.
1517 @type ndparams: dict
1518 @param ndparams: the dict to fill
1520 @return: a copy of the passed in ndparams with missing keys filled
1521 from the node group defaults
1524 return FillDict(self.ndparams, ndparams)
1527 class Cluster(TaggableObject):
1528 """Config object representing the cluster."""
1532 "highest_used_port",
1535 "volume_group_name",
1537 "drbd_usermode_helper",
1539 "default_hypervisor",
1544 "use_external_mip_script",
1547 "shared_file_storage_dir",
1548 "enabled_hypervisors",
1557 "candidate_pool_size",
1560 "maintain_node_health",
1562 "default_iallocator",
1565 "primary_ip_family",
1566 "prealloc_wipe_disks",
1568 "disk_state_static",
1569 ] + _TIMESTAMPS + _UUID
1571 def UpgradeConfig(self):
1572 """Fill defaults for missing configuration values.
1575 # pylint: disable=E0203
1576 # because these are "defined" via slots, not manually
1577 if self.hvparams is None:
1578 self.hvparams = constants.HVC_DEFAULTS
1580 for hypervisor in self.hvparams:
1581 self.hvparams[hypervisor] = FillDict(
1582 constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1584 if self.os_hvp is None:
1587 # osparams added before 2.2
1588 if self.osparams is None:
1591 self.ndparams = UpgradeNDParams(self.ndparams)
1593 self.beparams = UpgradeGroupedParams(self.beparams,
1594 constants.BEC_DEFAULTS)
1595 for beparams_group in self.beparams:
1596 UpgradeBeParams(self.beparams[beparams_group])
1598 migrate_default_bridge = not self.nicparams
1599 self.nicparams = UpgradeGroupedParams(self.nicparams,
1600 constants.NICC_DEFAULTS)
1601 if migrate_default_bridge:
1602 self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1605 if self.modify_etc_hosts is None:
1606 self.modify_etc_hosts = True
1608 if self.modify_ssh_setup is None:
1609 self.modify_ssh_setup = True
1611 # default_bridge is no longer used in 2.1. The slot is left there to
1612 # support auto-upgrading. It can be removed once we decide to deprecate
1613 # upgrading straight from 2.0.
1614 if self.default_bridge is not None:
1615 self.default_bridge = None
1617 # default_hypervisor is just the first enabled one in 2.1. This slot and
1618 # code can be removed once upgrading straight from 2.0 is deprecated.
1619 if self.default_hypervisor is not None:
1620 self.enabled_hypervisors = ([self.default_hypervisor] +
1621 [hvname for hvname in self.enabled_hypervisors
1622 if hvname != self.default_hypervisor])
1623 self.default_hypervisor = None
1625 # maintain_node_health added after 2.1.1
1626 if self.maintain_node_health is None:
1627 self.maintain_node_health = False
1629 if self.uid_pool is None:
1632 if self.default_iallocator is None:
1633 self.default_iallocator = ""
1635 # reserved_lvs added before 2.2
1636 if self.reserved_lvs is None:
1637 self.reserved_lvs = []
1639 # hidden and blacklisted operating systems added before 2.2.1
1640 if self.hidden_os is None:
1643 if self.blacklisted_os is None:
1644 self.blacklisted_os = []
1646 # primary_ip_family added before 2.3
1647 if self.primary_ip_family is None:
1648 self.primary_ip_family = AF_INET
1650 if self.master_netmask is None:
1651 ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1652 self.master_netmask = ipcls.iplen
1654 if self.prealloc_wipe_disks is None:
1655 self.prealloc_wipe_disks = False
1657 # shared_file_storage_dir added before 2.5
1658 if self.shared_file_storage_dir is None:
1659 self.shared_file_storage_dir = ""
1661 if self.use_external_mip_script is None:
1662 self.use_external_mip_script = False
1665 self.diskparams = UpgradeDiskParams(self.diskparams)
1667 self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1669 # instance policy added before 2.6
1670 if self.ipolicy is None:
1671 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1673 # we can either make sure to upgrade the ipolicy always, or only
1674 # do it in some corner cases (e.g. missing keys); note that this
1675 # will break any removal of keys from the ipolicy dict
1676 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1679 def primary_hypervisor(self):
1680 """The first hypervisor is the primary.
1682 Useful, for example, for L{Node}'s hv/disk state.
1685 return self.enabled_hypervisors[0]
1688 """Custom function for cluster.
1691 mydict = super(Cluster, self).ToDict()
1692 mydict["tcpudp_port_pool"] = list(self.tcpudp_port_pool)
1696 def FromDict(cls, val):
1697 """Custom function for cluster.
1700 obj = super(Cluster, cls).FromDict(val)
1701 if not isinstance(obj.tcpudp_port_pool, set):
1702 obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1705 def SimpleFillDP(self, diskparams):
1706 """Fill a given diskparams dict with cluster defaults.
1708 @param diskparams: The diskparams
1709 @return: The defaults dict
1712 return FillDiskParams(self.diskparams, diskparams)
1714 def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1715 """Get the default hypervisor parameters for the cluster.
1717 @param hypervisor: the hypervisor name
1718 @param os_name: if specified, we'll also update the defaults for this OS
1719 @param skip_keys: if passed, list of keys not to use
1720 @return: the defaults dict
1723 if skip_keys is None:
1726 fill_stack = [self.hvparams.get(hypervisor, {})]
1727 if os_name is not None:
1728 os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1729 fill_stack.append(os_hvp)
1732 for o_dict in fill_stack:
1733 ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1737 def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1738 """Fill a given hvparams dict with cluster defaults.
1740 @type hv_name: string
1741 @param hv_name: the hypervisor to use
1742 @type os_name: string
1743 @param os_name: the OS to use for overriding the hypervisor defaults
1744 @type skip_globals: boolean
1745 @param skip_globals: if True, the global hypervisor parameters will
1748 @return: a copy of the given hvparams with missing keys filled from
1749 the cluster defaults
1753 skip_keys = constants.HVC_GLOBALS
1757 def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1758 return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1760 def FillHV(self, instance, skip_globals=False):
1761 """Fill an instance's hvparams dict with cluster defaults.
1763 @type instance: L{objects.Instance}
1764 @param instance: the instance parameter to fill
1765 @type skip_globals: boolean
1766 @param skip_globals: if True, the global hypervisor parameters will
1769 @return: a copy of the instance's hvparams with missing keys filled from
1770 the cluster defaults
1773 return self.SimpleFillHV(instance.hypervisor, instance.os,
1774 instance.hvparams, skip_globals)
1776 def SimpleFillBE(self, beparams):
1777 """Fill a given beparams dict with cluster defaults.
1779 @type beparams: dict
1780 @param beparams: the dict to fill
1782 @return: a copy of the passed in beparams with missing keys filled
1783 from the cluster defaults
1786 return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1788 def FillBE(self, instance):
1789 """Fill an instance's beparams dict with cluster defaults.
1791 @type instance: L{objects.Instance}
1792 @param instance: the instance parameter to fill
1794 @return: a copy of the instance's beparams with missing keys filled from
1795 the cluster defaults
1798 return self.SimpleFillBE(instance.beparams)
1800 def SimpleFillNIC(self, nicparams):
1801 """Fill a given nicparams dict with cluster defaults.
1803 @type nicparams: dict
1804 @param nicparams: the dict to fill
1806 @return: a copy of the passed in nicparams with missing keys filled
1807 from the cluster defaults
1810 return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1812 def SimpleFillOS(self, os_name, os_params):
1813 """Fill an instance's osparams dict with cluster defaults.
1815 @type os_name: string
1816 @param os_name: the OS name to use
1817 @type os_params: dict
1818 @param os_params: the dict to fill with default values
1820 @return: a copy of the instance's osparams with missing keys filled from
1821 the cluster defaults
1824 name_only = os_name.split("+", 1)[0]
1826 result = self.osparams.get(name_only, {})
1828 result = FillDict(result, self.osparams.get(os_name, {}))
1830 return FillDict(result, os_params)
1833 def SimpleFillHvState(hv_state):
1834 """Fill an hv_state sub dict with cluster defaults.
1837 return FillDict(constants.HVST_DEFAULTS, hv_state)
1840 def SimpleFillDiskState(disk_state):
1841 """Fill an disk_state sub dict with cluster defaults.
1844 return FillDict(constants.DS_DEFAULTS, disk_state)
1846 def FillND(self, node, nodegroup):
1847 """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1849 @type node: L{objects.Node}
1850 @param node: A Node object to fill
1851 @type nodegroup: L{objects.NodeGroup}
1852 @param nodegroup: A Node object to fill
1853 @return a copy of the node's ndparams with defaults filled
1856 return self.SimpleFillND(nodegroup.FillND(node))
1858 def SimpleFillND(self, ndparams):
1859 """Fill a given ndparams dict with defaults.
1861 @type ndparams: dict
1862 @param ndparams: the dict to fill
1864 @return: a copy of the passed in ndparams with missing keys filled
1865 from the cluster defaults
1868 return FillDict(self.ndparams, ndparams)
1870 def SimpleFillIPolicy(self, ipolicy):
1871 """ Fill instance policy dict with defaults.
1874 @param ipolicy: the dict to fill
1876 @return: a copy of passed ipolicy with missing keys filled from
1877 the cluster defaults
1880 return FillIPolicy(self.ipolicy, ipolicy)
1883 class BlockDevStatus(ConfigObject):
1884 """Config object representing the status of a block device."""
1896 class ImportExportStatus(ConfigObject):
1897 """Config object representing the status of an import or export."""
1903 "progress_throughput",
1911 class ImportExportOptions(ConfigObject):
1912 """Options for import/export daemon
1914 @ivar key_name: X509 key name (None for cluster certificate)
1915 @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1916 @ivar compress: Compression method (one of L{constants.IEC_ALL})
1917 @ivar magic: Used to ensure the connection goes to the right disk
1918 @ivar ipv6: Whether to use IPv6
1919 @ivar connect_timeout: Number of seconds for establishing connection
1932 class ConfdRequest(ConfigObject):
1933 """Object holding a confd request.
1935 @ivar protocol: confd protocol version
1936 @ivar type: confd query type
1937 @ivar query: query request
1938 @ivar rsalt: requested reply salt
1949 class ConfdReply(ConfigObject):
1950 """Object holding a confd reply.
1952 @ivar protocol: confd protocol version
1953 @ivar status: reply status code (ok, error)
1954 @ivar answer: confd query reply
1955 @ivar serial: configuration serial number
1966 class QueryFieldDefinition(ConfigObject):
1967 """Object holding a query field definition.
1969 @ivar name: Field name
1970 @ivar title: Human-readable title
1971 @ivar kind: Field type
1972 @ivar doc: Human-readable description
1983 class _QueryResponseBase(ConfigObject):
1989 """Custom function for serializing.
1992 mydict = super(_QueryResponseBase, self).ToDict()
1993 mydict["fields"] = self._ContainerToDicts(mydict["fields"])
1997 def FromDict(cls, val):
1998 """Custom function for de-serializing.
2001 obj = super(_QueryResponseBase, cls).FromDict(val)
2002 obj.fields = cls._ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2006 class QueryResponse(_QueryResponseBase):
2007 """Object holding the response to a query.
2009 @ivar fields: List of L{QueryFieldDefinition} objects
2010 @ivar data: Requested data
2018 class QueryFieldsRequest(ConfigObject):
2019 """Object holding a request for querying available fields.
2028 class QueryFieldsResponse(_QueryResponseBase):
2029 """Object holding the response to a query for fields.
2031 @ivar fields: List of L{QueryFieldDefinition} objects
2038 class MigrationStatus(ConfigObject):
2039 """Object holding the status of a migration.
2049 class InstanceConsole(ConfigObject):
2050 """Object describing how to access the console of an instance.
2065 """Validates contents of this object.
2068 assert self.kind in constants.CONS_ALL, "Unknown console type"
2069 assert self.instance, "Missing instance name"
2070 assert self.message or self.kind in [constants.CONS_SSH,
2071 constants.CONS_SPICE,
2073 assert self.host or self.kind == constants.CONS_MESSAGE
2074 assert self.port or self.kind in [constants.CONS_MESSAGE,
2076 assert self.user or self.kind in [constants.CONS_MESSAGE,
2077 constants.CONS_SPICE,
2079 assert self.command or self.kind in [constants.CONS_MESSAGE,
2080 constants.CONS_SPICE,
2082 assert self.display or self.kind in [constants.CONS_MESSAGE,
2083 constants.CONS_SPICE,
2088 class SerializableConfigParser(ConfigParser.SafeConfigParser):
2089 """Simple wrapper over ConfigParse that allows serialization.
2091 This class is basically ConfigParser.SafeConfigParser with two
2092 additional methods that allow it to serialize/unserialize to/from a
2097 """Dump this instance and return the string representation."""
2100 return buf.getvalue()
2103 def Loads(cls, data):
2104 """Load data from a string."""
2105 buf = StringIO(data)