4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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-msg=E0203,W0201
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__
40 from cStringIO import StringIO
42 from ganeti import errors
43 from ganeti import constants
45 from socket import AF_INET
48 __all__ = ["ConfigObject", "ConfigData", "NIC", "Disk", "Instance",
49 "OS", "Node", "NodeGroup", "Cluster", "FillDict"]
51 _TIMESTAMPS = ["ctime", "mtime"]
55 def FillDict(defaults_dict, custom_dict, skip_keys=None):
56 """Basic function to apply settings on top a default dict.
58 @type defaults_dict: dict
59 @param defaults_dict: dictionary holding the default values
60 @type custom_dict: dict
61 @param custom_dict: dictionary holding customized value
63 @param skip_keys: which keys not to fill
65 @return: dict with the 'full' values
68 ret_dict = copy.deepcopy(defaults_dict)
69 ret_dict.update(custom_dict)
79 def UpgradeGroupedParams(target, defaults):
80 """Update all groups for the target parameter.
82 @type target: dict of dicts
83 @param target: {group: {parameter: value}}
85 @param defaults: default parameter values
89 target = {constants.PP_DEFAULT: defaults}
92 target[group] = FillDict(defaults, target[group])
96 class ConfigObject(object):
97 """A generic config object.
99 It has the following properties:
101 - provides somewhat safe recursive unpickling and pickling for its classes
102 - unset attributes which are defined in slots are always returned
103 as None instead of raising an error
105 Classes derived from this must always declare __slots__ (we use many
106 config objects and the memory reduction is useful)
111 def __init__(self, **kwargs):
112 for k, v in kwargs.iteritems():
115 def __getattr__(self, name):
116 if name not in self._all_slots():
117 raise AttributeError("Invalid object attribute %s.%s" %
118 (type(self).__name__, name))
121 def __setstate__(self, state):
122 slots = self._all_slots()
125 setattr(self, name, state[name])
129 """Compute the list of all declared slots for a class.
133 for parent in cls.__mro__:
134 slots.extend(getattr(parent, "__slots__", []))
138 """Convert to a dict holding only standard python types.
140 The generic routine just dumps all of this object's attributes in
141 a dict. It does not work if the class has children who are
142 ConfigObjects themselves (e.g. the nics list in an Instance), in
143 which case the object should subclass the function in order to
144 make sure all objects returned are only standard python types.
148 for name in self._all_slots():
149 value = getattr(self, name, None)
150 if value is not None:
154 __getstate__ = ToDict
157 def FromDict(cls, val):
158 """Create an object from a dictionary.
160 This generic routine takes a dict, instantiates a new instance of
161 the given class, and sets attributes based on the dict content.
163 As for `ToDict`, this does not work if the class has children
164 who are ConfigObjects themselves (e.g. the nics list in an
165 Instance), in which case the object should subclass the function
166 and alter the objects.
169 if not isinstance(val, dict):
170 raise errors.ConfigurationError("Invalid object passed to FromDict:"
171 " expected dict, got %s" % type(val))
172 val_str = dict([(str(k), v) for k, v in val.iteritems()])
173 obj = cls(**val_str) # pylint: disable-msg=W0142
177 def _ContainerToDicts(container):
178 """Convert the elements of a container to standard python types.
180 This method converts a container with elements derived from
181 ConfigData to standard python types. If the container is a dict,
182 we don't touch the keys, only the values.
185 if isinstance(container, dict):
186 ret = dict([(k, v.ToDict()) for k, v in container.iteritems()])
187 elif isinstance(container, (list, tuple, set, frozenset)):
188 ret = [elem.ToDict() for elem in container]
190 raise TypeError("Invalid type %s passed to _ContainerToDicts" %
195 def _ContainerFromDicts(source, c_type, e_type):
196 """Convert a container from standard python types.
198 This method converts a container with standard python types to
199 ConfigData objects. If the container is a dict, we don't touch the
200 keys, only the values.
203 if not isinstance(c_type, type):
204 raise TypeError("Container type %s passed to _ContainerFromDicts is"
205 " not a type" % type(c_type))
209 ret = dict([(k, e_type.FromDict(v)) for k, v in source.iteritems()])
210 elif c_type in (list, tuple, set, frozenset):
211 ret = c_type([e_type.FromDict(elem) for elem in source])
213 raise TypeError("Invalid container type %s passed to"
214 " _ContainerFromDicts" % c_type)
218 """Makes a deep copy of the current object and its children.
221 dict_form = self.ToDict()
222 clone_obj = self.__class__.FromDict(dict_form)
226 """Implement __repr__ for ConfigObjects."""
227 return repr(self.ToDict())
229 def UpgradeConfig(self):
230 """Fill defaults for missing configuration values.
232 This method will be called at configuration load time, and its
233 implementation will be object dependent.
239 class TaggableObject(ConfigObject):
240 """An generic class supporting tags.
244 VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
247 def ValidateTag(cls, tag):
248 """Check if a tag is valid.
250 If the tag is invalid, an errors.TagError will be raised. The
251 function has no return value.
254 if not isinstance(tag, basestring):
255 raise errors.TagError("Invalid tag type (not a string)")
256 if len(tag) > constants.MAX_TAG_LEN:
257 raise errors.TagError("Tag too long (>%d characters)" %
258 constants.MAX_TAG_LEN)
260 raise errors.TagError("Tags cannot be empty")
261 if not cls.VALID_TAG_RE.match(tag):
262 raise errors.TagError("Tag contains invalid characters")
265 """Return the tags list.
268 tags = getattr(self, "tags", None)
270 tags = self.tags = set()
273 def AddTag(self, tag):
277 self.ValidateTag(tag)
278 tags = self.GetTags()
279 if len(tags) >= constants.MAX_TAGS_PER_OBJ:
280 raise errors.TagError("Too many tags")
281 self.GetTags().add(tag)
283 def RemoveTag(self, tag):
287 self.ValidateTag(tag)
288 tags = self.GetTags()
292 raise errors.TagError("Tag not found")
295 """Taggable-object-specific conversion to standard python types.
297 This replaces the tags set with a list.
300 bo = super(TaggableObject, self).ToDict()
302 tags = bo.get("tags", None)
303 if isinstance(tags, set):
304 bo["tags"] = list(tags)
308 def FromDict(cls, val):
309 """Custom function for instances.
312 obj = super(TaggableObject, cls).FromDict(val)
313 if hasattr(obj, "tags") and isinstance(obj.tags, list):
314 obj.tags = set(obj.tags)
318 class ConfigData(ConfigObject):
319 """Top-level config object."""
330 """Custom function for top-level config data.
332 This just replaces the list of instances, nodes and the cluster
333 with standard python types.
336 mydict = super(ConfigData, self).ToDict()
337 mydict["cluster"] = mydict["cluster"].ToDict()
338 for key in "nodes", "instances", "nodegroups":
339 mydict[key] = self._ContainerToDicts(mydict[key])
344 def FromDict(cls, val):
345 """Custom function for top-level config data
348 obj = super(ConfigData, cls).FromDict(val)
349 obj.cluster = Cluster.FromDict(obj.cluster)
350 obj.nodes = cls._ContainerFromDicts(obj.nodes, dict, Node)
351 obj.instances = cls._ContainerFromDicts(obj.instances, dict, Instance)
352 obj.nodegroups = cls._ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
355 def HasAnyDiskOfType(self, dev_type):
356 """Check if in there is at disk of the given type in the configuration.
358 @type dev_type: L{constants.LDS_BLOCK}
359 @param dev_type: the type to look for
361 @return: boolean indicating if a disk of the given type was found or not
364 for instance in self.instances.values():
365 for disk in instance.disks:
366 if disk.IsBasedOnDiskType(dev_type):
370 def UpgradeConfig(self):
371 """Fill defaults for missing configuration values.
374 self.cluster.UpgradeConfig()
375 for node in self.nodes.values():
377 for instance in self.instances.values():
378 instance.UpgradeConfig()
379 if self.nodegroups is None:
381 for nodegroup in self.nodegroups.values():
382 nodegroup.UpgradeConfig()
383 if self.cluster.drbd_usermode_helper is None:
384 # To decide if we set an helper let's check if at least one instance has
385 # a DRBD disk. This does not cover all the possible scenarios but it
386 # gives a good approximation.
387 if self.HasAnyDiskOfType(constants.LD_DRBD8):
388 self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
391 class NIC(ConfigObject):
392 """Config object representing a network card."""
393 __slots__ = ["mac", "ip", "nicparams"]
396 def CheckParameterSyntax(cls, nicparams):
397 """Check the given parameters for validity.
399 @type nicparams: dict
400 @param nicparams: dictionary with parameter names/value
401 @raise errors.ConfigurationError: when a parameter is not valid
404 if nicparams[constants.NIC_MODE] not in constants.NIC_VALID_MODES:
405 err = "Invalid nic mode: %s" % nicparams[constants.NIC_MODE]
406 raise errors.ConfigurationError(err)
408 if (nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED and
409 not nicparams[constants.NIC_LINK]):
410 err = "Missing bridged nic link"
411 raise errors.ConfigurationError(err)
414 class Disk(ConfigObject):
415 """Config object representing a block device."""
416 __slots__ = ["dev_type", "logical_id", "physical_id",
417 "children", "iv_name", "size", "mode"]
419 def CreateOnSecondary(self):
420 """Test if this device needs to be created on a secondary node."""
421 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
423 def AssembleOnSecondary(self):
424 """Test if this device needs to be assembled on a secondary node."""
425 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
427 def OpenOnSecondary(self):
428 """Test if this device needs to be opened on a secondary node."""
429 return self.dev_type in (constants.LD_LV,)
431 def StaticDevPath(self):
432 """Return the device path if this device type has a static one.
434 Some devices (LVM for example) live always at the same /dev/ path,
435 irrespective of their status. For such devices, we return this
436 path, for others we return None.
438 @warning: The path returned is not a normalized pathname; callers
439 should check that it is a valid path.
442 if self.dev_type == constants.LD_LV:
443 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
444 elif self.dev_type == constants.LD_BLOCKDEV:
445 return self.logical_id[1]
448 def ChildrenNeeded(self):
449 """Compute the needed number of children for activation.
451 This method will return either -1 (all children) or a positive
452 number denoting the minimum number of children needed for
453 activation (only mirrored devices will usually return >=0).
455 Currently, only DRBD8 supports diskless activation (therefore we
456 return 0), for all other we keep the previous semantics and return
460 if self.dev_type == constants.LD_DRBD8:
464 def IsBasedOnDiskType(self, dev_type):
465 """Check if the disk or its children are based on the given type.
467 @type dev_type: L{constants.LDS_BLOCK}
468 @param dev_type: the type to look for
470 @return: boolean indicating if a device of the given type was found or not
474 for child in self.children:
475 if child.IsBasedOnDiskType(dev_type):
477 return self.dev_type == dev_type
479 def GetNodes(self, node):
480 """This function returns the nodes this device lives on.
482 Given the node on which the parent of the device lives on (or, in
483 case of a top-level device, the primary node of the devices'
484 instance), this function will return a list of nodes on which this
485 devices needs to (or can) be assembled.
488 if self.dev_type in [constants.LD_LV, constants.LD_FILE,
489 constants.LD_BLOCKDEV]:
491 elif self.dev_type in constants.LDS_DRBD:
492 result = [self.logical_id[0], self.logical_id[1]]
493 if node not in result:
494 raise errors.ConfigurationError("DRBD device passed unknown node")
496 raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
499 def ComputeNodeTree(self, parent_node):
500 """Compute the node/disk tree for this disk and its children.
502 This method, given the node on which the parent disk lives, will
503 return the list of all (node, disk) pairs which describe the disk
504 tree in the most compact way. For example, a drbd/lvm stack
505 will be returned as (primary_node, drbd) and (secondary_node, drbd)
506 which represents all the top-level devices on the nodes.
509 my_nodes = self.GetNodes(parent_node)
510 result = [(node, self) for node in my_nodes]
511 if not self.children:
514 for node in my_nodes:
515 for child in self.children:
516 child_result = child.ComputeNodeTree(node)
517 if len(child_result) == 1:
518 # child (and all its descendants) is simple, doesn't split
519 # over multiple hosts, so we don't need to describe it, our
520 # own entry for this node describes it completely
523 # check if child nodes differ from my nodes; note that
524 # subdisk can differ from the child itself, and be instead
525 # one of its descendants
526 for subnode, subdisk in child_result:
527 if subnode not in my_nodes:
528 result.append((subnode, subdisk))
529 # otherwise child is under our own node, so we ignore this
530 # entry (but probably the other results in the list will
534 def ComputeGrowth(self, amount):
535 """Compute the per-VG growth requirements.
537 This only works for VG-based disks.
539 @type amount: integer
540 @param amount: the desired increase in (user-visible) disk space
542 @return: a dictionary of volume-groups and the required size
545 if self.dev_type == constants.LD_LV:
546 return {self.logical_id[0]: amount}
547 elif self.dev_type == constants.LD_DRBD8:
549 return self.children[0].ComputeGrowth(amount)
553 # Other disk types do not require VG space
556 def RecordGrow(self, amount):
557 """Update the size of this disk after growth.
559 This method recurses over the disks's children and updates their
560 size correspondigly. The method needs to be kept in sync with the
561 actual algorithms from bdev.
564 if self.dev_type in (constants.LD_LV, constants.LD_FILE):
566 elif self.dev_type == constants.LD_DRBD8:
568 self.children[0].RecordGrow(amount)
571 raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
572 " disk type %s" % self.dev_type)
575 """Sets recursively the size to zero for the disk and its children.
579 for child in self.children:
583 def SetPhysicalID(self, target_node, nodes_ip):
584 """Convert the logical ID to the physical ID.
586 This is used only for drbd, which needs ip/port configuration.
588 The routine descends down and updates its children also, because
589 this helps when the only the top device is passed to the remote
593 - target_node: the node we wish to configure for
594 - nodes_ip: a mapping of node name to ip
596 The target_node must exist in in nodes_ip, and must be one of the
597 nodes in the logical ID for each of the DRBD devices encountered
602 for child in self.children:
603 child.SetPhysicalID(target_node, nodes_ip)
605 if self.logical_id is None and self.physical_id is not None:
607 if self.dev_type in constants.LDS_DRBD:
608 pnode, snode, port, pminor, sminor, secret = self.logical_id
609 if target_node not in (pnode, snode):
610 raise errors.ConfigurationError("DRBD device not knowing node %s" %
612 pnode_ip = nodes_ip.get(pnode, None)
613 snode_ip = nodes_ip.get(snode, None)
614 if pnode_ip is None or snode_ip is None:
615 raise errors.ConfigurationError("Can't find primary or secondary node"
616 " for %s" % str(self))
617 p_data = (pnode_ip, port)
618 s_data = (snode_ip, port)
619 if pnode == target_node:
620 self.physical_id = p_data + s_data + (pminor, secret)
621 else: # it must be secondary, we tested above
622 self.physical_id = s_data + p_data + (sminor, secret)
624 self.physical_id = self.logical_id
628 """Disk-specific conversion to standard python types.
630 This replaces the children lists of objects with lists of
631 standard python types.
634 bo = super(Disk, self).ToDict()
636 for attr in ("children",):
637 alist = bo.get(attr, None)
639 bo[attr] = self._ContainerToDicts(alist)
643 def FromDict(cls, val):
644 """Custom function for Disks
647 obj = super(Disk, cls).FromDict(val)
649 obj.children = cls._ContainerFromDicts(obj.children, list, Disk)
650 if obj.logical_id and isinstance(obj.logical_id, list):
651 obj.logical_id = tuple(obj.logical_id)
652 if obj.physical_id and isinstance(obj.physical_id, list):
653 obj.physical_id = tuple(obj.physical_id)
654 if obj.dev_type in constants.LDS_DRBD:
655 # we need a tuple of length six here
656 if len(obj.logical_id) < 6:
657 obj.logical_id += (None,) * (6 - len(obj.logical_id))
661 """Custom str() formatter for disks.
664 if self.dev_type == constants.LD_LV:
665 val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
666 elif self.dev_type in constants.LDS_DRBD:
667 node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
669 if self.physical_id is None:
672 phy = ("configured as %s:%s %s:%s" %
673 (self.physical_id[0], self.physical_id[1],
674 self.physical_id[2], self.physical_id[3]))
676 val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
677 (node_a, minor_a, node_b, minor_b, port, phy))
678 if self.children and self.children.count(None) == 0:
679 val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
681 val += "no local storage"
683 val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
684 (self.dev_type, self.logical_id, self.physical_id, self.children))
685 if self.iv_name is None:
686 val += ", not visible"
688 val += ", visible as /dev/%s" % self.iv_name
689 if isinstance(self.size, int):
690 val += ", size=%dm)>" % self.size
692 val += ", size='%s')>" % (self.size,)
696 """Checks that this disk is correctly configured.
700 if self.mode not in constants.DISK_ACCESS_SET:
701 all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
704 def UpgradeConfig(self):
705 """Fill defaults for missing configuration values.
709 for child in self.children:
710 child.UpgradeConfig()
711 # add here config upgrade for this disk
714 class Instance(TaggableObject):
715 """Config object representing an instance."""
730 ] + _TIMESTAMPS + _UUID
732 def _ComputeSecondaryNodes(self):
733 """Compute the list of secondary nodes.
735 This is a simple wrapper over _ComputeAllNodes.
738 all_nodes = set(self._ComputeAllNodes())
739 all_nodes.discard(self.primary_node)
740 return tuple(all_nodes)
742 secondary_nodes = property(_ComputeSecondaryNodes, None, None,
743 "List of secondary nodes")
745 def _ComputeAllNodes(self):
746 """Compute the list of all nodes.
748 Since the data is already there (in the drbd disks), keeping it as
749 a separate normal attribute is redundant and if not properly
750 synchronised can cause problems. Thus it's better to compute it
754 def _Helper(nodes, device):
755 """Recursively computes nodes given a top device."""
756 if device.dev_type in constants.LDS_DRBD:
757 nodea, nodeb = device.logical_id[:2]
761 for child in device.children:
762 _Helper(nodes, child)
765 all_nodes.add(self.primary_node)
766 for device in self.disks:
767 _Helper(all_nodes, device)
768 return tuple(all_nodes)
770 all_nodes = property(_ComputeAllNodes, None, None,
771 "List of all nodes of the instance")
773 def MapLVsByNode(self, lvmap=None, devs=None, node=None):
774 """Provide a mapping of nodes to LVs this instance owns.
776 This function figures out what logical volumes should belong on
777 which nodes, recursing through a device tree.
779 @param lvmap: optional dictionary to receive the
780 'node' : ['lv', ...] data.
782 @return: None if lvmap arg is given, otherwise, a dictionary of
783 the form { 'nodename' : ['volume1', 'volume2', ...], ... };
784 volumeN is of the form "vg_name/lv_name", compatible with
789 node = self.primary_node
797 if not node in lvmap:
805 if dev.dev_type == constants.LD_LV:
806 lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
808 elif dev.dev_type in constants.LDS_DRBD:
810 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
811 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
814 self.MapLVsByNode(lvmap, dev.children, node)
818 def FindDisk(self, idx):
819 """Find a disk given having a specified index.
821 This is just a wrapper that does validation of the index.
824 @param idx: the disk index
826 @return: the corresponding disk
827 @raise errors.OpPrereqError: when the given index is not valid
832 return self.disks[idx]
833 except (TypeError, ValueError), err:
834 raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
837 raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
838 " 0 to %d" % (idx, len(self.disks) - 1),
842 """Instance-specific conversion to standard python types.
844 This replaces the children lists of objects with lists of standard
848 bo = super(Instance, self).ToDict()
850 for attr in "nics", "disks":
851 alist = bo.get(attr, None)
853 nlist = self._ContainerToDicts(alist)
860 def FromDict(cls, val):
861 """Custom function for instances.
864 obj = super(Instance, cls).FromDict(val)
865 obj.nics = cls._ContainerFromDicts(obj.nics, list, NIC)
866 obj.disks = cls._ContainerFromDicts(obj.disks, list, Disk)
869 def UpgradeConfig(self):
870 """Fill defaults for missing configuration values.
873 for nic in self.nics:
875 for disk in self.disks:
878 for key in constants.HVC_GLOBALS:
880 del self.hvparams[key]
883 if self.osparams is None:
887 class OS(ConfigObject):
888 """Config object representing an operating system.
890 @type supported_parameters: list
891 @ivar supported_parameters: a list of tuples, name and description,
892 containing the supported parameters by this OS
894 @type VARIANT_DELIM: string
895 @cvar VARIANT_DELIM: the variant delimiter
907 "supported_variants",
908 "supported_parameters",
914 def SplitNameVariant(cls, name):
915 """Splits the name into the proper name and variant.
917 @param name: the OS (unprocessed) name
919 @return: a list of two elements; if the original name didn't
920 contain a variant, it's returned as an empty string
923 nv = name.split(cls.VARIANT_DELIM, 1)
929 def GetName(cls, name):
930 """Returns the proper name of the os (without the variant).
932 @param name: the OS (unprocessed) name
935 return cls.SplitNameVariant(name)[0]
938 def GetVariant(cls, name):
939 """Returns the variant the os (without the base name).
941 @param name: the OS (unprocessed) name
944 return cls.SplitNameVariant(name)[1]
947 class Node(TaggableObject):
948 """Config object representing a node."""
962 ] + _TIMESTAMPS + _UUID
964 def UpgradeConfig(self):
965 """Fill defaults for missing configuration values.
968 # pylint: disable-msg=E0203
969 # because these are "defined" via slots, not manually
970 if self.master_capable is None:
971 self.master_capable = True
973 if self.vm_capable is None:
974 self.vm_capable = True
976 if self.ndparams is None:
979 if self.powered is None:
983 class NodeGroup(TaggableObject):
984 """Config object representing a node group."""
991 ] + _TIMESTAMPS + _UUID
994 """Custom function for nodegroup.
996 This discards the members object, which gets recalculated and is only kept
1000 mydict = super(NodeGroup, self).ToDict()
1001 del mydict["members"]
1005 def FromDict(cls, val):
1006 """Custom function for nodegroup.
1008 The members slot is initialized to an empty list, upon deserialization.
1011 obj = super(NodeGroup, cls).FromDict(val)
1015 def UpgradeConfig(self):
1016 """Fill defaults for missing configuration values.
1019 if self.ndparams is None:
1022 if self.serial_no is None:
1025 if self.alloc_policy is None:
1026 self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1028 # We only update mtime, and not ctime, since we would not be able to provide
1029 # a correct value for creation time.
1030 if self.mtime is None:
1031 self.mtime = time.time()
1033 def FillND(self, node):
1034 """Return filled out ndparams for L{objects.Node}
1036 @type node: L{objects.Node}
1037 @param node: A Node object to fill
1038 @return a copy of the node's ndparams with defaults filled
1041 return self.SimpleFillND(node.ndparams)
1043 def SimpleFillND(self, ndparams):
1044 """Fill a given ndparams dict with defaults.
1046 @type ndparams: dict
1047 @param ndparams: the dict to fill
1049 @return: a copy of the passed in ndparams with missing keys filled
1050 from the node group defaults
1053 return FillDict(self.ndparams, ndparams)
1056 class Cluster(TaggableObject):
1057 """Config object representing the cluster."""
1061 "highest_used_port",
1064 "volume_group_name",
1066 "drbd_usermode_helper",
1068 "default_hypervisor",
1074 "shared_file_storage_dir",
1075 "enabled_hypervisors",
1082 "candidate_pool_size",
1085 "maintain_node_health",
1087 "default_iallocator",
1090 "primary_ip_family",
1091 "prealloc_wipe_disks",
1092 ] + _TIMESTAMPS + _UUID
1094 def UpgradeConfig(self):
1095 """Fill defaults for missing configuration values.
1098 # pylint: disable-msg=E0203
1099 # because these are "defined" via slots, not manually
1100 if self.hvparams is None:
1101 self.hvparams = constants.HVC_DEFAULTS
1103 for hypervisor in self.hvparams:
1104 self.hvparams[hypervisor] = FillDict(
1105 constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1107 if self.os_hvp is None:
1110 # osparams added before 2.2
1111 if self.osparams is None:
1114 if self.ndparams is None:
1115 self.ndparams = constants.NDC_DEFAULTS
1117 self.beparams = UpgradeGroupedParams(self.beparams,
1118 constants.BEC_DEFAULTS)
1119 migrate_default_bridge = not self.nicparams
1120 self.nicparams = UpgradeGroupedParams(self.nicparams,
1121 constants.NICC_DEFAULTS)
1122 if migrate_default_bridge:
1123 self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1126 if self.modify_etc_hosts is None:
1127 self.modify_etc_hosts = True
1129 if self.modify_ssh_setup is None:
1130 self.modify_ssh_setup = True
1132 # default_bridge is no longer used in 2.1. The slot is left there to
1133 # support auto-upgrading. It can be removed once we decide to deprecate
1134 # upgrading straight from 2.0.
1135 if self.default_bridge is not None:
1136 self.default_bridge = None
1138 # default_hypervisor is just the first enabled one in 2.1. This slot and
1139 # code can be removed once upgrading straight from 2.0 is deprecated.
1140 if self.default_hypervisor is not None:
1141 self.enabled_hypervisors = ([self.default_hypervisor] +
1142 [hvname for hvname in self.enabled_hypervisors
1143 if hvname != self.default_hypervisor])
1144 self.default_hypervisor = None
1146 # maintain_node_health added after 2.1.1
1147 if self.maintain_node_health is None:
1148 self.maintain_node_health = False
1150 if self.uid_pool is None:
1153 if self.default_iallocator is None:
1154 self.default_iallocator = ""
1156 # reserved_lvs added before 2.2
1157 if self.reserved_lvs is None:
1158 self.reserved_lvs = []
1160 # hidden and blacklisted operating systems added before 2.2.1
1161 if self.hidden_os is None:
1164 if self.blacklisted_os is None:
1165 self.blacklisted_os = []
1167 # primary_ip_family added before 2.3
1168 if self.primary_ip_family is None:
1169 self.primary_ip_family = AF_INET
1171 if self.prealloc_wipe_disks is None:
1172 self.prealloc_wipe_disks = False
1174 # shared_file_storage_dir added before 2.5
1175 if self.shared_file_storage_dir is None:
1176 self.shared_file_storage_dir = ""
1179 """Custom function for cluster.
1182 mydict = super(Cluster, self).ToDict()
1183 mydict["tcpudp_port_pool"] = list(self.tcpudp_port_pool)
1187 def FromDict(cls, val):
1188 """Custom function for cluster.
1191 obj = super(Cluster, cls).FromDict(val)
1192 if not isinstance(obj.tcpudp_port_pool, set):
1193 obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1196 def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1197 """Get the default hypervisor parameters for the cluster.
1199 @param hypervisor: the hypervisor name
1200 @param os_name: if specified, we'll also update the defaults for this OS
1201 @param skip_keys: if passed, list of keys not to use
1202 @return: the defaults dict
1205 if skip_keys is None:
1208 fill_stack = [self.hvparams.get(hypervisor, {})]
1209 if os_name is not None:
1210 os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1211 fill_stack.append(os_hvp)
1214 for o_dict in fill_stack:
1215 ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1219 def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1220 """Fill a given hvparams dict with cluster defaults.
1222 @type hv_name: string
1223 @param hv_name: the hypervisor to use
1224 @type os_name: string
1225 @param os_name: the OS to use for overriding the hypervisor defaults
1226 @type skip_globals: boolean
1227 @param skip_globals: if True, the global hypervisor parameters will
1230 @return: a copy of the given hvparams with missing keys filled from
1231 the cluster defaults
1235 skip_keys = constants.HVC_GLOBALS
1239 def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1240 return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1242 def FillHV(self, instance, skip_globals=False):
1243 """Fill an instance's hvparams dict with cluster defaults.
1245 @type instance: L{objects.Instance}
1246 @param instance: the instance parameter to fill
1247 @type skip_globals: boolean
1248 @param skip_globals: if True, the global hypervisor parameters will
1251 @return: a copy of the instance's hvparams with missing keys filled from
1252 the cluster defaults
1255 return self.SimpleFillHV(instance.hypervisor, instance.os,
1256 instance.hvparams, skip_globals)
1258 def SimpleFillBE(self, beparams):
1259 """Fill a given beparams dict with cluster defaults.
1261 @type beparams: dict
1262 @param beparams: the dict to fill
1264 @return: a copy of the passed in beparams with missing keys filled
1265 from the cluster defaults
1268 return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1270 def FillBE(self, instance):
1271 """Fill an instance's beparams dict with cluster defaults.
1273 @type instance: L{objects.Instance}
1274 @param instance: the instance parameter to fill
1276 @return: a copy of the instance's beparams with missing keys filled from
1277 the cluster defaults
1280 return self.SimpleFillBE(instance.beparams)
1282 def SimpleFillNIC(self, nicparams):
1283 """Fill a given nicparams dict with cluster defaults.
1285 @type nicparams: dict
1286 @param nicparams: the dict to fill
1288 @return: a copy of the passed in nicparams with missing keys filled
1289 from the cluster defaults
1292 return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1294 def SimpleFillOS(self, os_name, os_params):
1295 """Fill an instance's osparams dict with cluster defaults.
1297 @type os_name: string
1298 @param os_name: the OS name to use
1299 @type os_params: dict
1300 @param os_params: the dict to fill with default values
1302 @return: a copy of the instance's osparams with missing keys filled from
1303 the cluster defaults
1306 name_only = os_name.split("+", 1)[0]
1308 result = self.osparams.get(name_only, {})
1310 result = FillDict(result, self.osparams.get(os_name, {}))
1312 return FillDict(result, os_params)
1314 def FillND(self, node, nodegroup):
1315 """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1317 @type node: L{objects.Node}
1318 @param node: A Node object to fill
1319 @type nodegroup: L{objects.NodeGroup}
1320 @param nodegroup: A Node object to fill
1321 @return a copy of the node's ndparams with defaults filled
1324 return self.SimpleFillND(nodegroup.FillND(node))
1326 def SimpleFillND(self, ndparams):
1327 """Fill a given ndparams dict with defaults.
1329 @type ndparams: dict
1330 @param ndparams: the dict to fill
1332 @return: a copy of the passed in ndparams with missing keys filled
1333 from the cluster defaults
1336 return FillDict(self.ndparams, ndparams)
1339 class BlockDevStatus(ConfigObject):
1340 """Config object representing the status of a block device."""
1352 class ImportExportStatus(ConfigObject):
1353 """Config object representing the status of an import or export."""
1359 "progress_throughput",
1367 class ImportExportOptions(ConfigObject):
1368 """Options for import/export daemon
1370 @ivar key_name: X509 key name (None for cluster certificate)
1371 @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1372 @ivar compress: Compression method (one of L{constants.IEC_ALL})
1373 @ivar magic: Used to ensure the connection goes to the right disk
1374 @ivar ipv6: Whether to use IPv6
1375 @ivar connect_timeout: Number of seconds for establishing connection
1388 class ConfdRequest(ConfigObject):
1389 """Object holding a confd request.
1391 @ivar protocol: confd protocol version
1392 @ivar type: confd query type
1393 @ivar query: query request
1394 @ivar rsalt: requested reply salt
1405 class ConfdReply(ConfigObject):
1406 """Object holding a confd reply.
1408 @ivar protocol: confd protocol version
1409 @ivar status: reply status code (ok, error)
1410 @ivar answer: confd query reply
1411 @ivar serial: configuration serial number
1422 class QueryFieldDefinition(ConfigObject):
1423 """Object holding a query field definition.
1425 @ivar name: Field name
1426 @ivar title: Human-readable title
1427 @ivar kind: Field type
1428 @ivar doc: Human-readable description
1439 class _QueryResponseBase(ConfigObject):
1445 """Custom function for serializing.
1448 mydict = super(_QueryResponseBase, self).ToDict()
1449 mydict["fields"] = self._ContainerToDicts(mydict["fields"])
1453 def FromDict(cls, val):
1454 """Custom function for de-serializing.
1457 obj = super(_QueryResponseBase, cls).FromDict(val)
1458 obj.fields = cls._ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
1462 class QueryRequest(ConfigObject):
1463 """Object holding a query request.
1473 class QueryResponse(_QueryResponseBase):
1474 """Object holding the response to a query.
1476 @ivar fields: List of L{QueryFieldDefinition} objects
1477 @ivar data: Requested data
1485 class QueryFieldsRequest(ConfigObject):
1486 """Object holding a request for querying available fields.
1495 class QueryFieldsResponse(_QueryResponseBase):
1496 """Object holding the response to a query for fields.
1498 @ivar fields: List of L{QueryFieldDefinition} objects
1505 class InstanceConsole(ConfigObject):
1506 """Object describing how to access the console of an instance.
1521 """Validates contents of this object.
1524 assert self.kind in constants.CONS_ALL, "Unknown console type"
1525 assert self.instance, "Missing instance name"
1526 assert self.message or self.kind in [constants.CONS_SSH, constants.CONS_VNC]
1527 assert self.host or self.kind == constants.CONS_MESSAGE
1528 assert self.port or self.kind in [constants.CONS_MESSAGE,
1530 assert self.user or self.kind in [constants.CONS_MESSAGE,
1532 assert self.command or self.kind in [constants.CONS_MESSAGE,
1534 assert self.display or self.kind in [constants.CONS_MESSAGE,
1539 class SerializableConfigParser(ConfigParser.SafeConfigParser):
1540 """Simple wrapper over ConfigParse that allows serialization.
1542 This class is basically ConfigParser.SafeConfigParser with two
1543 additional methods that allow it to serialize/unserialize to/from a
1548 """Dump this instance and return the string representation."""
1551 return buf.getvalue()
1554 def Loads(cls, data):
1555 """Load data from a string."""
1556 buf = StringIO(data)