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"]
59 def FillDict(defaults_dict, custom_dict, skip_keys=None):
60 """Basic function to apply settings on top a default dict.
62 @type defaults_dict: dict
63 @param defaults_dict: dictionary holding the default values
64 @type custom_dict: dict
65 @param custom_dict: dictionary holding customized value
67 @param skip_keys: which keys not to fill
69 @return: dict with the 'full' values
72 ret_dict = copy.deepcopy(defaults_dict)
73 ret_dict.update(custom_dict)
83 def FillIPolicy(default_ipolicy, custom_ipolicy, skip_keys=None):
84 """Fills an instance policy with defaults.
87 assert frozenset(default_ipolicy.keys()) == constants.IPOLICY_ALL_KEYS
89 for key in constants.IPOLICY_ISPECS:
90 ret_dict[key] = FillDict(default_ipolicy[key],
91 custom_ipolicy.get(key, {}),
94 for key in [constants.IPOLICY_DTS]:
95 ret_dict[key] = list(custom_ipolicy.get(key, default_ipolicy[key]))
96 # other items which we know we can directly copy (immutables)
97 for key in constants.IPOLICY_PARAMETERS:
98 ret_dict[key] = custom_ipolicy.get(key, default_ipolicy[key])
103 def FillDiskParams(default_dparams, custom_dparams, skip_keys=None):
104 """Fills the disk parameter defaults.
106 @see: L{FillDict} for parameters and return value
109 assert frozenset(default_dparams.keys()) == constants.DISK_TEMPLATES
111 return dict((dt, FillDict(default_dparams[dt], custom_dparams.get(dt, {}),
112 skip_keys=skip_keys))
113 for dt in constants.DISK_TEMPLATES)
116 def UpgradeGroupedParams(target, defaults):
117 """Update all groups for the target parameter.
119 @type target: dict of dicts
120 @param target: {group: {parameter: value}}
122 @param defaults: default parameter values
126 target = {constants.PP_DEFAULT: defaults}
129 target[group] = FillDict(defaults, target[group])
133 def UpgradeBeParams(target):
134 """Update the be parameters dict to the new format.
137 @param target: "be" parameters dict
140 if constants.BE_MEMORY in target:
141 memory = target[constants.BE_MEMORY]
142 target[constants.BE_MAXMEM] = memory
143 target[constants.BE_MINMEM] = memory
144 del target[constants.BE_MEMORY]
147 def UpgradeDiskParams(diskparams):
148 """Upgrade the disk parameters.
150 @type diskparams: dict
151 @param diskparams: disk parameters to upgrade
153 @return: the upgraded disk parameters dict
159 result = FillDiskParams(constants.DISK_DT_DEFAULTS, diskparams)
164 def UpgradeNDParams(ndparams):
165 """Upgrade ndparams structure.
168 @param ndparams: disk parameters to upgrade
170 @return: the upgraded node parameters dict
176 return FillDict(constants.NDC_DEFAULTS, ndparams)
179 def MakeEmptyIPolicy():
180 """Create empty IPolicy dictionary.
184 (constants.ISPECS_MIN, {}),
185 (constants.ISPECS_MAX, {}),
186 (constants.ISPECS_STD, {}),
190 class ConfigObject(object):
191 """A generic config object.
193 It has the following properties:
195 - provides somewhat safe recursive unpickling and pickling for its classes
196 - unset attributes which are defined in slots are always returned
197 as None instead of raising an error
199 Classes derived from this must always declare __slots__ (we use many
200 config objects and the memory reduction is useful)
205 def __init__(self, **kwargs):
206 for k, v in kwargs.iteritems():
209 def __getattr__(self, name):
210 if name not in self._all_slots():
211 raise AttributeError("Invalid object attribute %s.%s" %
212 (type(self).__name__, name))
215 def __setstate__(self, state):
216 slots = self._all_slots()
219 setattr(self, name, state[name])
223 """Compute the list of all declared slots for a class.
227 for parent in cls.__mro__:
228 slots.extend(getattr(parent, "__slots__", []))
231 #: Public getter for the defined slots
232 GetAllSlots = _all_slots
235 """Convert to a dict holding only standard python types.
237 The generic routine just dumps all of this object's attributes in
238 a dict. It does not work if the class has children who are
239 ConfigObjects themselves (e.g. the nics list in an Instance), in
240 which case the object should subclass the function in order to
241 make sure all objects returned are only standard python types.
245 for name in self._all_slots():
246 value = getattr(self, name, None)
247 if value is not None:
251 __getstate__ = ToDict
254 def FromDict(cls, val):
255 """Create an object from a dictionary.
257 This generic routine takes a dict, instantiates a new instance of
258 the given class, and sets attributes based on the dict content.
260 As for `ToDict`, this does not work if the class has children
261 who are ConfigObjects themselves (e.g. the nics list in an
262 Instance), in which case the object should subclass the function
263 and alter the objects.
266 if not isinstance(val, dict):
267 raise errors.ConfigurationError("Invalid object passed to FromDict:"
268 " expected dict, got %s" % type(val))
269 val_str = dict([(str(k), v) for k, v in val.iteritems()])
270 obj = cls(**val_str) # pylint: disable=W0142
274 def _ContainerToDicts(container):
275 """Convert the elements of a container to standard python types.
277 This method converts a container with elements derived from
278 ConfigData to standard python types. If the container is a dict,
279 we don't touch the keys, only the values.
282 if isinstance(container, dict):
283 ret = dict([(k, v.ToDict()) for k, v in container.iteritems()])
284 elif isinstance(container, (list, tuple, set, frozenset)):
285 ret = [elem.ToDict() for elem in container]
287 raise TypeError("Invalid type %s passed to _ContainerToDicts" %
292 def _ContainerFromDicts(source, c_type, e_type):
293 """Convert a container from standard python types.
295 This method converts a container with standard python types to
296 ConfigData objects. If the container is a dict, we don't touch the
297 keys, only the values.
300 if not isinstance(c_type, type):
301 raise TypeError("Container type %s passed to _ContainerFromDicts is"
302 " not a type" % type(c_type))
306 ret = dict([(k, e_type.FromDict(v)) for k, v in source.iteritems()])
307 elif c_type in (list, tuple, set, frozenset):
308 ret = c_type([e_type.FromDict(elem) for elem in source])
310 raise TypeError("Invalid container type %s passed to"
311 " _ContainerFromDicts" % c_type)
315 """Makes a deep copy of the current object and its children.
318 dict_form = self.ToDict()
319 clone_obj = self.__class__.FromDict(dict_form)
323 """Implement __repr__ for ConfigObjects."""
324 return repr(self.ToDict())
326 def UpgradeConfig(self):
327 """Fill defaults for missing configuration values.
329 This method will be called at configuration load time, and its
330 implementation will be object dependent.
336 class TaggableObject(ConfigObject):
337 """An generic class supporting tags.
341 VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
344 def ValidateTag(cls, tag):
345 """Check if a tag is valid.
347 If the tag is invalid, an errors.TagError will be raised. The
348 function has no return value.
351 if not isinstance(tag, basestring):
352 raise errors.TagError("Invalid tag type (not a string)")
353 if len(tag) > constants.MAX_TAG_LEN:
354 raise errors.TagError("Tag too long (>%d characters)" %
355 constants.MAX_TAG_LEN)
357 raise errors.TagError("Tags cannot be empty")
358 if not cls.VALID_TAG_RE.match(tag):
359 raise errors.TagError("Tag contains invalid characters")
362 """Return the tags list.
365 tags = getattr(self, "tags", None)
367 tags = self.tags = set()
370 def AddTag(self, tag):
374 self.ValidateTag(tag)
375 tags = self.GetTags()
376 if len(tags) >= constants.MAX_TAGS_PER_OBJ:
377 raise errors.TagError("Too many tags")
378 self.GetTags().add(tag)
380 def RemoveTag(self, tag):
384 self.ValidateTag(tag)
385 tags = self.GetTags()
389 raise errors.TagError("Tag not found")
392 """Taggable-object-specific conversion to standard python types.
394 This replaces the tags set with a list.
397 bo = super(TaggableObject, self).ToDict()
399 tags = bo.get("tags", None)
400 if isinstance(tags, set):
401 bo["tags"] = list(tags)
405 def FromDict(cls, val):
406 """Custom function for instances.
409 obj = super(TaggableObject, cls).FromDict(val)
410 if hasattr(obj, "tags") and isinstance(obj.tags, list):
411 obj.tags = set(obj.tags)
415 class MasterNetworkParameters(ConfigObject):
416 """Network configuration parameters for the master
418 @ivar name: master name
420 @ivar netmask: master netmask
421 @ivar netdev: master network device
422 @ivar ip_family: master IP family
434 class ConfigData(ConfigObject):
435 """Top-level config object."""
446 """Custom function for top-level config data.
448 This just replaces the list of instances, nodes and the cluster
449 with standard python types.
452 mydict = super(ConfigData, self).ToDict()
453 mydict["cluster"] = mydict["cluster"].ToDict()
454 for key in "nodes", "instances", "nodegroups":
455 mydict[key] = self._ContainerToDicts(mydict[key])
460 def FromDict(cls, val):
461 """Custom function for top-level config data
464 obj = super(ConfigData, cls).FromDict(val)
465 obj.cluster = Cluster.FromDict(obj.cluster)
466 obj.nodes = cls._ContainerFromDicts(obj.nodes, dict, Node)
467 obj.instances = cls._ContainerFromDicts(obj.instances, dict, Instance)
468 obj.nodegroups = cls._ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
471 def HasAnyDiskOfType(self, dev_type):
472 """Check if in there is at disk of the given type in the configuration.
474 @type dev_type: L{constants.LDS_BLOCK}
475 @param dev_type: the type to look for
477 @return: boolean indicating if a disk of the given type was found or not
480 for instance in self.instances.values():
481 for disk in instance.disks:
482 if disk.IsBasedOnDiskType(dev_type):
486 def UpgradeConfig(self):
487 """Fill defaults for missing configuration values.
490 self.cluster.UpgradeConfig()
491 for node in self.nodes.values():
493 for instance in self.instances.values():
494 instance.UpgradeConfig()
495 if self.nodegroups is None:
497 for nodegroup in self.nodegroups.values():
498 nodegroup.UpgradeConfig()
499 if self.cluster.drbd_usermode_helper is None:
500 # To decide if we set an helper let's check if at least one instance has
501 # a DRBD disk. This does not cover all the possible scenarios but it
502 # gives a good approximation.
503 if self.HasAnyDiskOfType(constants.LD_DRBD8):
504 self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
507 class NIC(ConfigObject):
508 """Config object representing a network card."""
509 __slots__ = ["mac", "ip", "nicparams"]
512 def CheckParameterSyntax(cls, nicparams):
513 """Check the given parameters for validity.
515 @type nicparams: dict
516 @param nicparams: dictionary with parameter names/value
517 @raise errors.ConfigurationError: when a parameter is not valid
520 if (nicparams[constants.NIC_MODE] not in constants.NIC_VALID_MODES and
521 nicparams[constants.NIC_MODE] != constants.VALUE_AUTO):
522 err = "Invalid nic mode: %s" % nicparams[constants.NIC_MODE]
523 raise errors.ConfigurationError(err)
525 if (nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED and
526 not nicparams[constants.NIC_LINK]):
527 err = "Missing bridged nic link"
528 raise errors.ConfigurationError(err)
531 class Disk(ConfigObject):
532 """Config object representing a block device."""
533 __slots__ = ["dev_type", "logical_id", "physical_id",
534 "children", "iv_name", "size", "mode", "params"]
536 def CreateOnSecondary(self):
537 """Test if this device needs to be created on a secondary node."""
538 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
540 def AssembleOnSecondary(self):
541 """Test if this device needs to be assembled on a secondary node."""
542 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
544 def OpenOnSecondary(self):
545 """Test if this device needs to be opened on a secondary node."""
546 return self.dev_type in (constants.LD_LV,)
548 def StaticDevPath(self):
549 """Return the device path if this device type has a static one.
551 Some devices (LVM for example) live always at the same /dev/ path,
552 irrespective of their status. For such devices, we return this
553 path, for others we return None.
555 @warning: The path returned is not a normalized pathname; callers
556 should check that it is a valid path.
559 if self.dev_type == constants.LD_LV:
560 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
561 elif self.dev_type == constants.LD_BLOCKDEV:
562 return self.logical_id[1]
563 elif self.dev_type == constants.LD_RBD:
564 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
567 def ChildrenNeeded(self):
568 """Compute the needed number of children for activation.
570 This method will return either -1 (all children) or a positive
571 number denoting the minimum number of children needed for
572 activation (only mirrored devices will usually return >=0).
574 Currently, only DRBD8 supports diskless activation (therefore we
575 return 0), for all other we keep the previous semantics and return
579 if self.dev_type == constants.LD_DRBD8:
583 def IsBasedOnDiskType(self, dev_type):
584 """Check if the disk or its children are based on the given type.
586 @type dev_type: L{constants.LDS_BLOCK}
587 @param dev_type: the type to look for
589 @return: boolean indicating if a device of the given type was found or not
593 for child in self.children:
594 if child.IsBasedOnDiskType(dev_type):
596 return self.dev_type == dev_type
598 def GetNodes(self, node):
599 """This function returns the nodes this device lives on.
601 Given the node on which the parent of the device lives on (or, in
602 case of a top-level device, the primary node of the devices'
603 instance), this function will return a list of nodes on which this
604 devices needs to (or can) be assembled.
607 if self.dev_type in [constants.LD_LV, constants.LD_FILE,
608 constants.LD_BLOCKDEV, constants.LD_RBD]:
610 elif self.dev_type in constants.LDS_DRBD:
611 result = [self.logical_id[0], self.logical_id[1]]
612 if node not in result:
613 raise errors.ConfigurationError("DRBD device passed unknown node")
615 raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
618 def ComputeNodeTree(self, parent_node):
619 """Compute the node/disk tree for this disk and its children.
621 This method, given the node on which the parent disk lives, will
622 return the list of all (node, disk) pairs which describe the disk
623 tree in the most compact way. For example, a drbd/lvm stack
624 will be returned as (primary_node, drbd) and (secondary_node, drbd)
625 which represents all the top-level devices on the nodes.
628 my_nodes = self.GetNodes(parent_node)
629 result = [(node, self) for node in my_nodes]
630 if not self.children:
633 for node in my_nodes:
634 for child in self.children:
635 child_result = child.ComputeNodeTree(node)
636 if len(child_result) == 1:
637 # child (and all its descendants) is simple, doesn't split
638 # over multiple hosts, so we don't need to describe it, our
639 # own entry for this node describes it completely
642 # check if child nodes differ from my nodes; note that
643 # subdisk can differ from the child itself, and be instead
644 # one of its descendants
645 for subnode, subdisk in child_result:
646 if subnode not in my_nodes:
647 result.append((subnode, subdisk))
648 # otherwise child is under our own node, so we ignore this
649 # entry (but probably the other results in the list will
653 def ComputeGrowth(self, amount):
654 """Compute the per-VG growth requirements.
656 This only works for VG-based disks.
658 @type amount: integer
659 @param amount: the desired increase in (user-visible) disk space
661 @return: a dictionary of volume-groups and the required size
664 if self.dev_type == constants.LD_LV:
665 return {self.logical_id[0]: amount}
666 elif self.dev_type == constants.LD_DRBD8:
668 return self.children[0].ComputeGrowth(amount)
672 # Other disk types do not require VG space
675 def RecordGrow(self, amount):
676 """Update the size of this disk after growth.
678 This method recurses over the disks's children and updates their
679 size correspondigly. The method needs to be kept in sync with the
680 actual algorithms from bdev.
683 if self.dev_type in (constants.LD_LV, constants.LD_FILE,
686 elif self.dev_type == constants.LD_DRBD8:
688 self.children[0].RecordGrow(amount)
691 raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
692 " disk type %s" % self.dev_type)
694 def Update(self, size=None, mode=None):
695 """Apply changes to size and mode.
698 if self.dev_type == constants.LD_DRBD8:
700 self.children[0].Update(size=size, mode=mode)
702 assert not self.children
710 """Sets recursively the size to zero for the disk and its children.
714 for child in self.children:
718 def SetPhysicalID(self, target_node, nodes_ip):
719 """Convert the logical ID to the physical ID.
721 This is used only for drbd, which needs ip/port configuration.
723 The routine descends down and updates its children also, because
724 this helps when the only the top device is passed to the remote
728 - target_node: the node we wish to configure for
729 - nodes_ip: a mapping of node name to ip
731 The target_node must exist in in nodes_ip, and must be one of the
732 nodes in the logical ID for each of the DRBD devices encountered
737 for child in self.children:
738 child.SetPhysicalID(target_node, nodes_ip)
740 if self.logical_id is None and self.physical_id is not None:
742 if self.dev_type in constants.LDS_DRBD:
743 pnode, snode, port, pminor, sminor, secret = self.logical_id
744 if target_node not in (pnode, snode):
745 raise errors.ConfigurationError("DRBD device not knowing node %s" %
747 pnode_ip = nodes_ip.get(pnode, None)
748 snode_ip = nodes_ip.get(snode, None)
749 if pnode_ip is None or snode_ip is None:
750 raise errors.ConfigurationError("Can't find primary or secondary node"
751 " for %s" % str(self))
752 p_data = (pnode_ip, port)
753 s_data = (snode_ip, port)
754 if pnode == target_node:
755 self.physical_id = p_data + s_data + (pminor, secret)
756 else: # it must be secondary, we tested above
757 self.physical_id = s_data + p_data + (sminor, secret)
759 self.physical_id = self.logical_id
763 """Disk-specific conversion to standard python types.
765 This replaces the children lists of objects with lists of
766 standard python types.
769 bo = super(Disk, self).ToDict()
771 for attr in ("children",):
772 alist = bo.get(attr, None)
774 bo[attr] = self._ContainerToDicts(alist)
778 def FromDict(cls, val):
779 """Custom function for Disks
782 obj = super(Disk, cls).FromDict(val)
784 obj.children = cls._ContainerFromDicts(obj.children, list, Disk)
785 if obj.logical_id and isinstance(obj.logical_id, list):
786 obj.logical_id = tuple(obj.logical_id)
787 if obj.physical_id and isinstance(obj.physical_id, list):
788 obj.physical_id = tuple(obj.physical_id)
789 if obj.dev_type in constants.LDS_DRBD:
790 # we need a tuple of length six here
791 if len(obj.logical_id) < 6:
792 obj.logical_id += (None,) * (6 - len(obj.logical_id))
796 """Custom str() formatter for disks.
799 if self.dev_type == constants.LD_LV:
800 val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
801 elif self.dev_type in constants.LDS_DRBD:
802 node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
804 if self.physical_id is None:
807 phy = ("configured as %s:%s %s:%s" %
808 (self.physical_id[0], self.physical_id[1],
809 self.physical_id[2], self.physical_id[3]))
811 val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
812 (node_a, minor_a, node_b, minor_b, port, phy))
813 if self.children and self.children.count(None) == 0:
814 val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
816 val += "no local storage"
818 val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
819 (self.dev_type, self.logical_id, self.physical_id, self.children))
820 if self.iv_name is None:
821 val += ", not visible"
823 val += ", visible as /dev/%s" % self.iv_name
824 if isinstance(self.size, int):
825 val += ", size=%dm)>" % self.size
827 val += ", size='%s')>" % (self.size,)
831 """Checks that this disk is correctly configured.
835 if self.mode not in constants.DISK_ACCESS_SET:
836 all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
839 def UpgradeConfig(self):
840 """Fill defaults for missing configuration values.
844 for child in self.children:
845 child.UpgradeConfig()
847 # FIXME: Make this configurable in Ganeti 2.7
849 # add here config upgrade for this disk
852 def ComputeLDParams(disk_template, disk_params):
853 """Computes Logical Disk parameters from Disk Template parameters.
855 @type disk_template: string
856 @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
857 @type disk_params: dict
858 @param disk_params: disk template parameters;
859 dict(template_name -> parameters
861 @return: a list of dicts, one for each node of the disk hierarchy. Each dict
862 contains the LD parameters of the node. The tree is flattened in-order.
865 if disk_template not in constants.DISK_TEMPLATES:
866 raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
868 assert disk_template in disk_params
871 dt_params = disk_params[disk_template]
872 if disk_template == constants.DT_DRBD8:
874 constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
875 constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
876 constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
877 constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
878 constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
879 constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
880 constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
881 constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
882 constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
883 constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
884 constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
885 constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
889 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8],
892 result.append(drbd_params)
896 constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
899 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
901 result.append(data_params)
905 constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
908 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
910 result.append(meta_params)
912 elif (disk_template == constants.DT_FILE or
913 disk_template == constants.DT_SHARED_FILE):
914 result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
916 elif disk_template == constants.DT_PLAIN:
918 constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
921 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
923 result.append(params)
925 elif disk_template == constants.DT_BLOCK:
926 result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
928 elif disk_template == constants.DT_RBD:
930 constants.LDP_POOL: dt_params[constants.RBD_POOL]
933 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD],
935 result.append(params)
940 class InstancePolicy(ConfigObject):
941 """Config object representing instance policy limits dictionary.
944 Note that this object is not actually used in the config, it's just
945 used as a placeholder for a few functions.
949 def CheckParameterSyntax(cls, ipolicy, check_std):
950 """ Check the instance policy for validity.
953 for param in constants.ISPECS_PARAMETERS:
954 InstancePolicy.CheckISpecSyntax(ipolicy, param, check_std)
955 if constants.IPOLICY_DTS in ipolicy:
956 InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
957 for key in constants.IPOLICY_PARAMETERS:
959 InstancePolicy.CheckParameter(key, ipolicy[key])
960 wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
962 raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
963 utils.CommaJoin(wrong_keys))
966 def CheckISpecSyntax(cls, ipolicy, name, check_std):
967 """Check the instance policy for validity on a given key.
969 We check if the instance policy makes sense for a given key, that is
970 if ipolicy[min][name] <= ipolicy[std][name] <= ipolicy[max][name].
973 @param ipolicy: dictionary with min, max, std specs
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.ConfigureError: when specs for given name are not valid
981 min_v = ipolicy[constants.ISPECS_MIN].get(name, 0)
984 std_v = ipolicy[constants.ISPECS_STD].get(name, min_v)
990 max_v = ipolicy[constants.ISPECS_MAX].get(name, std_v)
991 err = ("Invalid specification of min/max/std values for %s: %s/%s/%s" %
993 ipolicy[constants.ISPECS_MIN].get(name, "-"),
994 ipolicy[constants.ISPECS_MAX].get(name, "-"),
996 if min_v > std_v or std_v > max_v:
997 raise errors.ConfigurationError(err)
1000 def CheckDiskTemplates(cls, disk_templates):
1001 """Checks the disk templates for validity.
1004 wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1006 raise errors.ConfigurationError("Invalid disk template(s) %s" %
1007 utils.CommaJoin(wrong))
1010 def CheckParameter(cls, key, value):
1011 """Checks a parameter.
1013 Currently we expect all parameters to be float values.
1018 except (TypeError, ValueError), err:
1019 raise errors.ConfigurationError("Invalid value for key" " '%s':"
1020 " '%s', error: %s" % (key, value, err))
1023 class Instance(TaggableObject):
1024 """Config object representing an instance."""
1039 ] + _TIMESTAMPS + _UUID
1041 def _ComputeSecondaryNodes(self):
1042 """Compute the list of secondary nodes.
1044 This is a simple wrapper over _ComputeAllNodes.
1047 all_nodes = set(self._ComputeAllNodes())
1048 all_nodes.discard(self.primary_node)
1049 return tuple(all_nodes)
1051 secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1052 "List of secondary nodes")
1054 def _ComputeAllNodes(self):
1055 """Compute the list of all nodes.
1057 Since the data is already there (in the drbd disks), keeping it as
1058 a separate normal attribute is redundant and if not properly
1059 synchronised can cause problems. Thus it's better to compute it
1063 def _Helper(nodes, device):
1064 """Recursively computes nodes given a top device."""
1065 if device.dev_type in constants.LDS_DRBD:
1066 nodea, nodeb = device.logical_id[:2]
1070 for child in device.children:
1071 _Helper(nodes, child)
1074 all_nodes.add(self.primary_node)
1075 for device in self.disks:
1076 _Helper(all_nodes, device)
1077 return tuple(all_nodes)
1079 all_nodes = property(_ComputeAllNodes, None, None,
1080 "List of all nodes of the instance")
1082 def MapLVsByNode(self, lvmap=None, devs=None, node=None):
1083 """Provide a mapping of nodes to LVs this instance owns.
1085 This function figures out what logical volumes should belong on
1086 which nodes, recursing through a device tree.
1088 @param lvmap: optional dictionary to receive the
1089 'node' : ['lv', ...] data.
1091 @return: None if lvmap arg is given, otherwise, a dictionary of
1092 the form { 'nodename' : ['volume1', 'volume2', ...], ... };
1093 volumeN is of the form "vg_name/lv_name", compatible with
1098 node = self.primary_node
1106 if not node in lvmap:
1114 if dev.dev_type == constants.LD_LV:
1115 lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1117 elif dev.dev_type in constants.LDS_DRBD:
1119 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1120 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1123 self.MapLVsByNode(lvmap, dev.children, node)
1127 def FindDisk(self, idx):
1128 """Find a disk given having a specified index.
1130 This is just a wrapper that does validation of the index.
1133 @param idx: the disk index
1135 @return: the corresponding disk
1136 @raise errors.OpPrereqError: when the given index is not valid
1141 return self.disks[idx]
1142 except (TypeError, ValueError), err:
1143 raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1146 raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1147 " 0 to %d" % (idx, len(self.disks) - 1),
1151 """Instance-specific conversion to standard python types.
1153 This replaces the children lists of objects with lists of standard
1157 bo = super(Instance, self).ToDict()
1159 for attr in "nics", "disks":
1160 alist = bo.get(attr, None)
1162 nlist = self._ContainerToDicts(alist)
1169 def FromDict(cls, val):
1170 """Custom function for instances.
1173 if "admin_state" not in val:
1174 if val.get("admin_up", False):
1175 val["admin_state"] = constants.ADMINST_UP
1177 val["admin_state"] = constants.ADMINST_DOWN
1178 if "admin_up" in val:
1180 obj = super(Instance, cls).FromDict(val)
1181 obj.nics = cls._ContainerFromDicts(obj.nics, list, NIC)
1182 obj.disks = cls._ContainerFromDicts(obj.disks, list, Disk)
1185 def UpgradeConfig(self):
1186 """Fill defaults for missing configuration values.
1189 for nic in self.nics:
1191 for disk in self.disks:
1192 disk.UpgradeConfig()
1194 for key in constants.HVC_GLOBALS:
1196 del self.hvparams[key]
1199 if self.osparams is None:
1201 UpgradeBeParams(self.beparams)
1204 class OS(ConfigObject):
1205 """Config object representing an operating system.
1207 @type supported_parameters: list
1208 @ivar supported_parameters: a list of tuples, name and description,
1209 containing the supported parameters by this OS
1211 @type VARIANT_DELIM: string
1212 @cvar VARIANT_DELIM: the variant delimiter
1224 "supported_variants",
1225 "supported_parameters",
1231 def SplitNameVariant(cls, name):
1232 """Splits the name into the proper name and variant.
1234 @param name: the OS (unprocessed) name
1236 @return: a list of two elements; if the original name didn't
1237 contain a variant, it's returned as an empty string
1240 nv = name.split(cls.VARIANT_DELIM, 1)
1246 def GetName(cls, name):
1247 """Returns the proper name of the os (without the variant).
1249 @param name: the OS (unprocessed) name
1252 return cls.SplitNameVariant(name)[0]
1255 def GetVariant(cls, name):
1256 """Returns the variant the os (without the base name).
1258 @param name: the OS (unprocessed) name
1261 return cls.SplitNameVariant(name)[1]
1264 class NodeHvState(ConfigObject):
1265 """Hypvervisor state on a node.
1267 @ivar mem_total: Total amount of memory
1268 @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1270 @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1272 @ivar mem_inst: Memory used by instances living on node
1273 @ivar cpu_total: Total node CPU core count
1274 @ivar cpu_node: Number of CPU cores reserved for the node itself
1287 class NodeDiskState(ConfigObject):
1288 """Disk state on a node.
1298 class Node(TaggableObject):
1299 """Config object representing a node.
1301 @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1302 @ivar hv_state_static: Hypervisor state overriden by user
1303 @ivar disk_state: Disk state (e.g. free space)
1304 @ivar disk_state_static: Disk state overriden by user
1323 "disk_state_static",
1324 ] + _TIMESTAMPS + _UUID
1326 def UpgradeConfig(self):
1327 """Fill defaults for missing configuration values.
1330 # pylint: disable=E0203
1331 # because these are "defined" via slots, not manually
1332 if self.master_capable is None:
1333 self.master_capable = True
1335 if self.vm_capable is None:
1336 self.vm_capable = True
1338 if self.ndparams is None:
1341 if self.powered is None:
1345 """Custom function for serializing.
1348 data = super(Node, self).ToDict()
1350 hv_state = data.get("hv_state", None)
1351 if hv_state is not None:
1352 data["hv_state"] = self._ContainerToDicts(hv_state)
1354 disk_state = data.get("disk_state", None)
1355 if disk_state is not None:
1356 data["disk_state"] = \
1357 dict((key, self._ContainerToDicts(value))
1358 for (key, value) in disk_state.items())
1363 def FromDict(cls, val):
1364 """Custom function for deserializing.
1367 obj = super(Node, cls).FromDict(val)
1369 if obj.hv_state is not None:
1370 obj.hv_state = cls._ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1372 if obj.disk_state is not None:
1374 dict((key, cls._ContainerFromDicts(value, dict, NodeDiskState))
1375 for (key, value) in obj.disk_state.items())
1380 class NodeGroup(TaggableObject):
1381 """Config object representing a node group."""
1390 "disk_state_static",
1392 ] + _TIMESTAMPS + _UUID
1395 """Custom function for nodegroup.
1397 This discards the members object, which gets recalculated and is only kept
1401 mydict = super(NodeGroup, self).ToDict()
1402 del mydict["members"]
1406 def FromDict(cls, val):
1407 """Custom function for nodegroup.
1409 The members slot is initialized to an empty list, upon deserialization.
1412 obj = super(NodeGroup, cls).FromDict(val)
1416 def UpgradeConfig(self):
1417 """Fill defaults for missing configuration values.
1420 if self.ndparams is None:
1423 if self.serial_no is None:
1426 if self.alloc_policy is None:
1427 self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1429 # We only update mtime, and not ctime, since we would not be able
1430 # to provide a correct value for creation time.
1431 if self.mtime is None:
1432 self.mtime = time.time()
1434 if self.diskparams is None:
1435 self.diskparams = {}
1436 if self.ipolicy is None:
1437 self.ipolicy = MakeEmptyIPolicy()
1439 def FillND(self, node):
1440 """Return filled out ndparams for L{objects.Node}
1442 @type node: L{objects.Node}
1443 @param node: A Node object to fill
1444 @return a copy of the node's ndparams with defaults filled
1447 return self.SimpleFillND(node.ndparams)
1449 def SimpleFillND(self, ndparams):
1450 """Fill a given ndparams dict with defaults.
1452 @type ndparams: dict
1453 @param ndparams: the dict to fill
1455 @return: a copy of the passed in ndparams with missing keys filled
1456 from the node group defaults
1459 return FillDict(self.ndparams, ndparams)
1462 class Cluster(TaggableObject):
1463 """Config object representing the cluster."""
1467 "highest_used_port",
1470 "volume_group_name",
1472 "drbd_usermode_helper",
1474 "default_hypervisor",
1479 "use_external_mip_script",
1482 "shared_file_storage_dir",
1483 "enabled_hypervisors",
1492 "candidate_pool_size",
1495 "maintain_node_health",
1497 "default_iallocator",
1500 "primary_ip_family",
1501 "prealloc_wipe_disks",
1503 "disk_state_static",
1504 ] + _TIMESTAMPS + _UUID
1506 def UpgradeConfig(self):
1507 """Fill defaults for missing configuration values.
1510 # pylint: disable=E0203
1511 # because these are "defined" via slots, not manually
1512 if self.hvparams is None:
1513 self.hvparams = constants.HVC_DEFAULTS
1515 for hypervisor in self.hvparams:
1516 self.hvparams[hypervisor] = FillDict(
1517 constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1519 if self.os_hvp is None:
1522 # osparams added before 2.2
1523 if self.osparams is None:
1526 self.ndparams = UpgradeNDParams(self.ndparams)
1528 self.beparams = UpgradeGroupedParams(self.beparams,
1529 constants.BEC_DEFAULTS)
1530 for beparams_group in self.beparams:
1531 UpgradeBeParams(self.beparams[beparams_group])
1533 migrate_default_bridge = not self.nicparams
1534 self.nicparams = UpgradeGroupedParams(self.nicparams,
1535 constants.NICC_DEFAULTS)
1536 if migrate_default_bridge:
1537 self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1540 if self.modify_etc_hosts is None:
1541 self.modify_etc_hosts = True
1543 if self.modify_ssh_setup is None:
1544 self.modify_ssh_setup = True
1546 # default_bridge is no longer used in 2.1. The slot is left there to
1547 # support auto-upgrading. It can be removed once we decide to deprecate
1548 # upgrading straight from 2.0.
1549 if self.default_bridge is not None:
1550 self.default_bridge = None
1552 # default_hypervisor is just the first enabled one in 2.1. This slot and
1553 # code can be removed once upgrading straight from 2.0 is deprecated.
1554 if self.default_hypervisor is not None:
1555 self.enabled_hypervisors = ([self.default_hypervisor] +
1556 [hvname for hvname in self.enabled_hypervisors
1557 if hvname != self.default_hypervisor])
1558 self.default_hypervisor = None
1560 # maintain_node_health added after 2.1.1
1561 if self.maintain_node_health is None:
1562 self.maintain_node_health = False
1564 if self.uid_pool is None:
1567 if self.default_iallocator is None:
1568 self.default_iallocator = ""
1570 # reserved_lvs added before 2.2
1571 if self.reserved_lvs is None:
1572 self.reserved_lvs = []
1574 # hidden and blacklisted operating systems added before 2.2.1
1575 if self.hidden_os is None:
1578 if self.blacklisted_os is None:
1579 self.blacklisted_os = []
1581 # primary_ip_family added before 2.3
1582 if self.primary_ip_family is None:
1583 self.primary_ip_family = AF_INET
1585 if self.master_netmask is None:
1586 ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1587 self.master_netmask = ipcls.iplen
1589 if self.prealloc_wipe_disks is None:
1590 self.prealloc_wipe_disks = False
1592 # shared_file_storage_dir added before 2.5
1593 if self.shared_file_storage_dir is None:
1594 self.shared_file_storage_dir = ""
1596 if self.use_external_mip_script is None:
1597 self.use_external_mip_script = False
1600 self.diskparams = UpgradeDiskParams(self.diskparams)
1602 self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1604 # instance policy added before 2.6
1605 if self.ipolicy is None:
1606 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1608 # we can either make sure to upgrade the ipolicy always, or only
1609 # do it in some corner cases (e.g. missing keys); note that this
1610 # will break any removal of keys from the ipolicy dict
1611 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1614 def primary_hypervisor(self):
1615 """The first hypervisor is the primary.
1617 Useful, for example, for L{Node}'s hv/disk state.
1620 return self.enabled_hypervisors[0]
1623 """Custom function for cluster.
1626 mydict = super(Cluster, self).ToDict()
1627 mydict["tcpudp_port_pool"] = list(self.tcpudp_port_pool)
1631 def FromDict(cls, val):
1632 """Custom function for cluster.
1635 obj = super(Cluster, cls).FromDict(val)
1636 if not isinstance(obj.tcpudp_port_pool, set):
1637 obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1640 def SimpleFillDP(self, diskparams):
1641 """Fill a given diskparams dict with cluster defaults.
1643 @param diskparams: The diskparams
1644 @return: The defaults dict
1647 return FillDiskParams(self.diskparams, diskparams)
1649 def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1650 """Get the default hypervisor parameters for the cluster.
1652 @param hypervisor: the hypervisor name
1653 @param os_name: if specified, we'll also update the defaults for this OS
1654 @param skip_keys: if passed, list of keys not to use
1655 @return: the defaults dict
1658 if skip_keys is None:
1661 fill_stack = [self.hvparams.get(hypervisor, {})]
1662 if os_name is not None:
1663 os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1664 fill_stack.append(os_hvp)
1667 for o_dict in fill_stack:
1668 ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1672 def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1673 """Fill a given hvparams dict with cluster defaults.
1675 @type hv_name: string
1676 @param hv_name: the hypervisor to use
1677 @type os_name: string
1678 @param os_name: the OS to use for overriding the hypervisor defaults
1679 @type skip_globals: boolean
1680 @param skip_globals: if True, the global hypervisor parameters will
1683 @return: a copy of the given hvparams with missing keys filled from
1684 the cluster defaults
1688 skip_keys = constants.HVC_GLOBALS
1692 def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1693 return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1695 def FillHV(self, instance, skip_globals=False):
1696 """Fill an instance's hvparams dict with cluster defaults.
1698 @type instance: L{objects.Instance}
1699 @param instance: the instance parameter to fill
1700 @type skip_globals: boolean
1701 @param skip_globals: if True, the global hypervisor parameters will
1704 @return: a copy of the instance's hvparams with missing keys filled from
1705 the cluster defaults
1708 return self.SimpleFillHV(instance.hypervisor, instance.os,
1709 instance.hvparams, skip_globals)
1711 def SimpleFillBE(self, beparams):
1712 """Fill a given beparams dict with cluster defaults.
1714 @type beparams: dict
1715 @param beparams: the dict to fill
1717 @return: a copy of the passed in beparams with missing keys filled
1718 from the cluster defaults
1721 return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1723 def FillBE(self, instance):
1724 """Fill an instance's beparams dict with cluster defaults.
1726 @type instance: L{objects.Instance}
1727 @param instance: the instance parameter to fill
1729 @return: a copy of the instance's beparams with missing keys filled from
1730 the cluster defaults
1733 return self.SimpleFillBE(instance.beparams)
1735 def SimpleFillNIC(self, nicparams):
1736 """Fill a given nicparams dict with cluster defaults.
1738 @type nicparams: dict
1739 @param nicparams: the dict to fill
1741 @return: a copy of the passed in nicparams with missing keys filled
1742 from the cluster defaults
1745 return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1747 def SimpleFillOS(self, os_name, os_params):
1748 """Fill an instance's osparams dict with cluster defaults.
1750 @type os_name: string
1751 @param os_name: the OS name to use
1752 @type os_params: dict
1753 @param os_params: the dict to fill with default values
1755 @return: a copy of the instance's osparams with missing keys filled from
1756 the cluster defaults
1759 name_only = os_name.split("+", 1)[0]
1761 result = self.osparams.get(name_only, {})
1763 result = FillDict(result, self.osparams.get(os_name, {}))
1765 return FillDict(result, os_params)
1768 def SimpleFillHvState(hv_state):
1769 """Fill an hv_state sub dict with cluster defaults.
1772 return FillDict(constants.HVST_DEFAULTS, hv_state)
1775 def SimpleFillDiskState(disk_state):
1776 """Fill an disk_state sub dict with cluster defaults.
1779 return FillDict(constants.DS_DEFAULTS, disk_state)
1781 def FillND(self, node, nodegroup):
1782 """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1784 @type node: L{objects.Node}
1785 @param node: A Node object to fill
1786 @type nodegroup: L{objects.NodeGroup}
1787 @param nodegroup: A Node object to fill
1788 @return a copy of the node's ndparams with defaults filled
1791 return self.SimpleFillND(nodegroup.FillND(node))
1793 def SimpleFillND(self, ndparams):
1794 """Fill a given ndparams dict with defaults.
1796 @type ndparams: dict
1797 @param ndparams: the dict to fill
1799 @return: a copy of the passed in ndparams with missing keys filled
1800 from the cluster defaults
1803 return FillDict(self.ndparams, ndparams)
1805 def SimpleFillIPolicy(self, ipolicy):
1806 """ Fill instance policy dict with defaults.
1809 @param ipolicy: the dict to fill
1811 @return: a copy of passed ipolicy with missing keys filled from
1812 the cluster defaults
1815 return FillIPolicy(self.ipolicy, ipolicy)
1818 class BlockDevStatus(ConfigObject):
1819 """Config object representing the status of a block device."""
1831 class ImportExportStatus(ConfigObject):
1832 """Config object representing the status of an import or export."""
1838 "progress_throughput",
1846 class ImportExportOptions(ConfigObject):
1847 """Options for import/export daemon
1849 @ivar key_name: X509 key name (None for cluster certificate)
1850 @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1851 @ivar compress: Compression method (one of L{constants.IEC_ALL})
1852 @ivar magic: Used to ensure the connection goes to the right disk
1853 @ivar ipv6: Whether to use IPv6
1854 @ivar connect_timeout: Number of seconds for establishing connection
1867 class ConfdRequest(ConfigObject):
1868 """Object holding a confd request.
1870 @ivar protocol: confd protocol version
1871 @ivar type: confd query type
1872 @ivar query: query request
1873 @ivar rsalt: requested reply salt
1884 class ConfdReply(ConfigObject):
1885 """Object holding a confd reply.
1887 @ivar protocol: confd protocol version
1888 @ivar status: reply status code (ok, error)
1889 @ivar answer: confd query reply
1890 @ivar serial: configuration serial number
1901 class QueryFieldDefinition(ConfigObject):
1902 """Object holding a query field definition.
1904 @ivar name: Field name
1905 @ivar title: Human-readable title
1906 @ivar kind: Field type
1907 @ivar doc: Human-readable description
1918 class _QueryResponseBase(ConfigObject):
1924 """Custom function for serializing.
1927 mydict = super(_QueryResponseBase, self).ToDict()
1928 mydict["fields"] = self._ContainerToDicts(mydict["fields"])
1932 def FromDict(cls, val):
1933 """Custom function for de-serializing.
1936 obj = super(_QueryResponseBase, cls).FromDict(val)
1937 obj.fields = cls._ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
1941 class QueryResponse(_QueryResponseBase):
1942 """Object holding the response to a query.
1944 @ivar fields: List of L{QueryFieldDefinition} objects
1945 @ivar data: Requested data
1953 class QueryFieldsRequest(ConfigObject):
1954 """Object holding a request for querying available fields.
1963 class QueryFieldsResponse(_QueryResponseBase):
1964 """Object holding the response to a query for fields.
1966 @ivar fields: List of L{QueryFieldDefinition} objects
1973 class MigrationStatus(ConfigObject):
1974 """Object holding the status of a migration.
1984 class InstanceConsole(ConfigObject):
1985 """Object describing how to access the console of an instance.
2000 """Validates contents of this object.
2003 assert self.kind in constants.CONS_ALL, "Unknown console type"
2004 assert self.instance, "Missing instance name"
2005 assert self.message or self.kind in [constants.CONS_SSH,
2006 constants.CONS_SPICE,
2008 assert self.host or self.kind == constants.CONS_MESSAGE
2009 assert self.port or self.kind in [constants.CONS_MESSAGE,
2011 assert self.user or self.kind in [constants.CONS_MESSAGE,
2012 constants.CONS_SPICE,
2014 assert self.command or self.kind in [constants.CONS_MESSAGE,
2015 constants.CONS_SPICE,
2017 assert self.display or self.kind in [constants.CONS_MESSAGE,
2018 constants.CONS_SPICE,
2023 class SerializableConfigParser(ConfigParser.SafeConfigParser):
2024 """Simple wrapper over ConfigParse that allows serialization.
2026 This class is basically ConfigParser.SafeConfigParser with two
2027 additional methods that allow it to serialize/unserialize to/from a
2032 """Dump this instance and return the string representation."""
2035 return buf.getvalue()
2038 def Loads(cls, data):
2039 """Load data from a string."""
2040 buf = StringIO(data)