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 if (constants.ND_OOB_PROGRAM in ndparams and
177 ndparams[constants.ND_OOB_PROGRAM] is None):
178 # will be reset by the line below
179 del ndparams[constants.ND_OOB_PROGRAM]
180 return FillDict(constants.NDC_DEFAULTS, ndparams)
183 def MakeEmptyIPolicy():
184 """Create empty IPolicy dictionary.
188 (constants.ISPECS_MIN, {}),
189 (constants.ISPECS_MAX, {}),
190 (constants.ISPECS_STD, {}),
194 class ConfigObject(object):
195 """A generic config object.
197 It has the following properties:
199 - provides somewhat safe recursive unpickling and pickling for its classes
200 - unset attributes which are defined in slots are always returned
201 as None instead of raising an error
203 Classes derived from this must always declare __slots__ (we use many
204 config objects and the memory reduction is useful)
209 def __init__(self, **kwargs):
210 for k, v in kwargs.iteritems():
213 def __getattr__(self, name):
214 if name not in self._all_slots():
215 raise AttributeError("Invalid object attribute %s.%s" %
216 (type(self).__name__, name))
219 def __setstate__(self, state):
220 slots = self._all_slots()
223 setattr(self, name, state[name])
227 """Compute the list of all declared slots for a class.
231 for parent in cls.__mro__:
232 slots.extend(getattr(parent, "__slots__", []))
235 #: Public getter for the defined slots
236 GetAllSlots = _all_slots
239 """Convert to a dict holding only standard python types.
241 The generic routine just dumps all of this object's attributes in
242 a dict. It does not work if the class has children who are
243 ConfigObjects themselves (e.g. the nics list in an Instance), in
244 which case the object should subclass the function in order to
245 make sure all objects returned are only standard python types.
249 for name in self._all_slots():
250 value = getattr(self, name, None)
251 if value is not None:
255 __getstate__ = ToDict
258 def FromDict(cls, val):
259 """Create an object from a dictionary.
261 This generic routine takes a dict, instantiates a new instance of
262 the given class, and sets attributes based on the dict content.
264 As for `ToDict`, this does not work if the class has children
265 who are ConfigObjects themselves (e.g. the nics list in an
266 Instance), in which case the object should subclass the function
267 and alter the objects.
270 if not isinstance(val, dict):
271 raise errors.ConfigurationError("Invalid object passed to FromDict:"
272 " expected dict, got %s" % type(val))
273 val_str = dict([(str(k), v) for k, v in val.iteritems()])
274 obj = cls(**val_str) # pylint: disable=W0142
278 def _ContainerToDicts(container):
279 """Convert the elements of a container to standard python types.
281 This method converts a container with elements derived from
282 ConfigData to standard python types. If the container is a dict,
283 we don't touch the keys, only the values.
286 if isinstance(container, dict):
287 ret = dict([(k, v.ToDict()) for k, v in container.iteritems()])
288 elif isinstance(container, (list, tuple, set, frozenset)):
289 ret = [elem.ToDict() for elem in container]
291 raise TypeError("Invalid type %s passed to _ContainerToDicts" %
296 def _ContainerFromDicts(source, c_type, e_type):
297 """Convert a container from standard python types.
299 This method converts a container with standard python types to
300 ConfigData objects. If the container is a dict, we don't touch the
301 keys, only the values.
304 if not isinstance(c_type, type):
305 raise TypeError("Container type %s passed to _ContainerFromDicts is"
306 " not a type" % type(c_type))
310 ret = dict([(k, e_type.FromDict(v)) for k, v in source.iteritems()])
311 elif c_type in (list, tuple, set, frozenset):
312 ret = c_type([e_type.FromDict(elem) for elem in source])
314 raise TypeError("Invalid container type %s passed to"
315 " _ContainerFromDicts" % c_type)
319 """Makes a deep copy of the current object and its children.
322 dict_form = self.ToDict()
323 clone_obj = self.__class__.FromDict(dict_form)
327 """Implement __repr__ for ConfigObjects."""
328 return repr(self.ToDict())
330 def UpgradeConfig(self):
331 """Fill defaults for missing configuration values.
333 This method will be called at configuration load time, and its
334 implementation will be object dependent.
340 class TaggableObject(ConfigObject):
341 """An generic class supporting tags.
345 VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
348 def ValidateTag(cls, tag):
349 """Check if a tag is valid.
351 If the tag is invalid, an errors.TagError will be raised. The
352 function has no return value.
355 if not isinstance(tag, basestring):
356 raise errors.TagError("Invalid tag type (not a string)")
357 if len(tag) > constants.MAX_TAG_LEN:
358 raise errors.TagError("Tag too long (>%d characters)" %
359 constants.MAX_TAG_LEN)
361 raise errors.TagError("Tags cannot be empty")
362 if not cls.VALID_TAG_RE.match(tag):
363 raise errors.TagError("Tag contains invalid characters")
366 """Return the tags list.
369 tags = getattr(self, "tags", None)
371 tags = self.tags = set()
374 def AddTag(self, tag):
378 self.ValidateTag(tag)
379 tags = self.GetTags()
380 if len(tags) >= constants.MAX_TAGS_PER_OBJ:
381 raise errors.TagError("Too many tags")
382 self.GetTags().add(tag)
384 def RemoveTag(self, tag):
388 self.ValidateTag(tag)
389 tags = self.GetTags()
393 raise errors.TagError("Tag not found")
396 """Taggable-object-specific conversion to standard python types.
398 This replaces the tags set with a list.
401 bo = super(TaggableObject, self).ToDict()
403 tags = bo.get("tags", None)
404 if isinstance(tags, set):
405 bo["tags"] = list(tags)
409 def FromDict(cls, val):
410 """Custom function for instances.
413 obj = super(TaggableObject, cls).FromDict(val)
414 if hasattr(obj, "tags") and isinstance(obj.tags, list):
415 obj.tags = set(obj.tags)
419 class MasterNetworkParameters(ConfigObject):
420 """Network configuration parameters for the master
422 @ivar name: master name
424 @ivar netmask: master netmask
425 @ivar netdev: master network device
426 @ivar ip_family: master IP family
438 class ConfigData(ConfigObject):
439 """Top-level config object."""
450 """Custom function for top-level config data.
452 This just replaces the list of instances, nodes and the cluster
453 with standard python types.
456 mydict = super(ConfigData, self).ToDict()
457 mydict["cluster"] = mydict["cluster"].ToDict()
458 for key in "nodes", "instances", "nodegroups":
459 mydict[key] = self._ContainerToDicts(mydict[key])
464 def FromDict(cls, val):
465 """Custom function for top-level config data
468 obj = super(ConfigData, cls).FromDict(val)
469 obj.cluster = Cluster.FromDict(obj.cluster)
470 obj.nodes = cls._ContainerFromDicts(obj.nodes, dict, Node)
471 obj.instances = cls._ContainerFromDicts(obj.instances, dict, Instance)
472 obj.nodegroups = cls._ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
475 def HasAnyDiskOfType(self, dev_type):
476 """Check if in there is at disk of the given type in the configuration.
478 @type dev_type: L{constants.LDS_BLOCK}
479 @param dev_type: the type to look for
481 @return: boolean indicating if a disk of the given type was found or not
484 for instance in self.instances.values():
485 for disk in instance.disks:
486 if disk.IsBasedOnDiskType(dev_type):
490 def UpgradeConfig(self):
491 """Fill defaults for missing configuration values.
494 self.cluster.UpgradeConfig()
495 for node in self.nodes.values():
497 for instance in self.instances.values():
498 instance.UpgradeConfig()
499 if self.nodegroups is None:
501 for nodegroup in self.nodegroups.values():
502 nodegroup.UpgradeConfig()
503 if self.cluster.drbd_usermode_helper is None:
504 # To decide if we set an helper let's check if at least one instance has
505 # a DRBD disk. This does not cover all the possible scenarios but it
506 # gives a good approximation.
507 if self.HasAnyDiskOfType(constants.LD_DRBD8):
508 self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
511 class NIC(ConfigObject):
512 """Config object representing a network card."""
513 __slots__ = ["mac", "ip", "nicparams"]
516 def CheckParameterSyntax(cls, nicparams):
517 """Check the given parameters for validity.
519 @type nicparams: dict
520 @param nicparams: dictionary with parameter names/value
521 @raise errors.ConfigurationError: when a parameter is not valid
524 if (nicparams[constants.NIC_MODE] not in constants.NIC_VALID_MODES and
525 nicparams[constants.NIC_MODE] != constants.VALUE_AUTO):
526 err = "Invalid nic mode: %s" % nicparams[constants.NIC_MODE]
527 raise errors.ConfigurationError(err)
529 if (nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED and
530 not nicparams[constants.NIC_LINK]):
531 err = "Missing bridged nic link"
532 raise errors.ConfigurationError(err)
535 class Disk(ConfigObject):
536 """Config object representing a block device."""
537 __slots__ = ["dev_type", "logical_id", "physical_id",
538 "children", "iv_name", "size", "mode", "params"]
540 def CreateOnSecondary(self):
541 """Test if this device needs to be created on a secondary node."""
542 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
544 def AssembleOnSecondary(self):
545 """Test if this device needs to be assembled on a secondary node."""
546 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
548 def OpenOnSecondary(self):
549 """Test if this device needs to be opened on a secondary node."""
550 return self.dev_type in (constants.LD_LV,)
552 def StaticDevPath(self):
553 """Return the device path if this device type has a static one.
555 Some devices (LVM for example) live always at the same /dev/ path,
556 irrespective of their status. For such devices, we return this
557 path, for others we return None.
559 @warning: The path returned is not a normalized pathname; callers
560 should check that it is a valid path.
563 if self.dev_type == constants.LD_LV:
564 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
565 elif self.dev_type == constants.LD_BLOCKDEV:
566 return self.logical_id[1]
567 elif self.dev_type == constants.LD_RBD:
568 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
571 def ChildrenNeeded(self):
572 """Compute the needed number of children for activation.
574 This method will return either -1 (all children) or a positive
575 number denoting the minimum number of children needed for
576 activation (only mirrored devices will usually return >=0).
578 Currently, only DRBD8 supports diskless activation (therefore we
579 return 0), for all other we keep the previous semantics and return
583 if self.dev_type == constants.LD_DRBD8:
587 def IsBasedOnDiskType(self, dev_type):
588 """Check if the disk or its children are based on the given type.
590 @type dev_type: L{constants.LDS_BLOCK}
591 @param dev_type: the type to look for
593 @return: boolean indicating if a device of the given type was found or not
597 for child in self.children:
598 if child.IsBasedOnDiskType(dev_type):
600 return self.dev_type == dev_type
602 def GetNodes(self, node):
603 """This function returns the nodes this device lives on.
605 Given the node on which the parent of the device lives on (or, in
606 case of a top-level device, the primary node of the devices'
607 instance), this function will return a list of nodes on which this
608 devices needs to (or can) be assembled.
611 if self.dev_type in [constants.LD_LV, constants.LD_FILE,
612 constants.LD_BLOCKDEV, constants.LD_RBD]:
614 elif self.dev_type in constants.LDS_DRBD:
615 result = [self.logical_id[0], self.logical_id[1]]
616 if node not in result:
617 raise errors.ConfigurationError("DRBD device passed unknown node")
619 raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
622 def ComputeNodeTree(self, parent_node):
623 """Compute the node/disk tree for this disk and its children.
625 This method, given the node on which the parent disk lives, will
626 return the list of all (node, disk) pairs which describe the disk
627 tree in the most compact way. For example, a drbd/lvm stack
628 will be returned as (primary_node, drbd) and (secondary_node, drbd)
629 which represents all the top-level devices on the nodes.
632 my_nodes = self.GetNodes(parent_node)
633 result = [(node, self) for node in my_nodes]
634 if not self.children:
637 for node in my_nodes:
638 for child in self.children:
639 child_result = child.ComputeNodeTree(node)
640 if len(child_result) == 1:
641 # child (and all its descendants) is simple, doesn't split
642 # over multiple hosts, so we don't need to describe it, our
643 # own entry for this node describes it completely
646 # check if child nodes differ from my nodes; note that
647 # subdisk can differ from the child itself, and be instead
648 # one of its descendants
649 for subnode, subdisk in child_result:
650 if subnode not in my_nodes:
651 result.append((subnode, subdisk))
652 # otherwise child is under our own node, so we ignore this
653 # entry (but probably the other results in the list will
657 def ComputeGrowth(self, amount):
658 """Compute the per-VG growth requirements.
660 This only works for VG-based disks.
662 @type amount: integer
663 @param amount: the desired increase in (user-visible) disk space
665 @return: a dictionary of volume-groups and the required size
668 if self.dev_type == constants.LD_LV:
669 return {self.logical_id[0]: amount}
670 elif self.dev_type == constants.LD_DRBD8:
672 return self.children[0].ComputeGrowth(amount)
676 # Other disk types do not require VG space
679 def RecordGrow(self, amount):
680 """Update the size of this disk after growth.
682 This method recurses over the disks's children and updates their
683 size correspondigly. The method needs to be kept in sync with the
684 actual algorithms from bdev.
687 if self.dev_type in (constants.LD_LV, constants.LD_FILE,
690 elif self.dev_type == constants.LD_DRBD8:
692 self.children[0].RecordGrow(amount)
695 raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
696 " disk type %s" % self.dev_type)
698 def Update(self, size=None, mode=None):
699 """Apply changes to size and mode.
702 if self.dev_type == constants.LD_DRBD8:
704 self.children[0].Update(size=size, mode=mode)
706 assert not self.children
714 """Sets recursively the size to zero for the disk and its children.
718 for child in self.children:
722 def SetPhysicalID(self, target_node, nodes_ip):
723 """Convert the logical ID to the physical ID.
725 This is used only for drbd, which needs ip/port configuration.
727 The routine descends down and updates its children also, because
728 this helps when the only the top device is passed to the remote
732 - target_node: the node we wish to configure for
733 - nodes_ip: a mapping of node name to ip
735 The target_node must exist in in nodes_ip, and must be one of the
736 nodes in the logical ID for each of the DRBD devices encountered
741 for child in self.children:
742 child.SetPhysicalID(target_node, nodes_ip)
744 if self.logical_id is None and self.physical_id is not None:
746 if self.dev_type in constants.LDS_DRBD:
747 pnode, snode, port, pminor, sminor, secret = self.logical_id
748 if target_node not in (pnode, snode):
749 raise errors.ConfigurationError("DRBD device not knowing node %s" %
751 pnode_ip = nodes_ip.get(pnode, None)
752 snode_ip = nodes_ip.get(snode, None)
753 if pnode_ip is None or snode_ip is None:
754 raise errors.ConfigurationError("Can't find primary or secondary node"
755 " for %s" % str(self))
756 p_data = (pnode_ip, port)
757 s_data = (snode_ip, port)
758 if pnode == target_node:
759 self.physical_id = p_data + s_data + (pminor, secret)
760 else: # it must be secondary, we tested above
761 self.physical_id = s_data + p_data + (sminor, secret)
763 self.physical_id = self.logical_id
767 """Disk-specific conversion to standard python types.
769 This replaces the children lists of objects with lists of
770 standard python types.
773 bo = super(Disk, self).ToDict()
775 for attr in ("children",):
776 alist = bo.get(attr, None)
778 bo[attr] = self._ContainerToDicts(alist)
782 def FromDict(cls, val):
783 """Custom function for Disks
786 obj = super(Disk, cls).FromDict(val)
788 obj.children = cls._ContainerFromDicts(obj.children, list, Disk)
789 if obj.logical_id and isinstance(obj.logical_id, list):
790 obj.logical_id = tuple(obj.logical_id)
791 if obj.physical_id and isinstance(obj.physical_id, list):
792 obj.physical_id = tuple(obj.physical_id)
793 if obj.dev_type in constants.LDS_DRBD:
794 # we need a tuple of length six here
795 if len(obj.logical_id) < 6:
796 obj.logical_id += (None,) * (6 - len(obj.logical_id))
800 """Custom str() formatter for disks.
803 if self.dev_type == constants.LD_LV:
804 val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
805 elif self.dev_type in constants.LDS_DRBD:
806 node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
808 if self.physical_id is None:
811 phy = ("configured as %s:%s %s:%s" %
812 (self.physical_id[0], self.physical_id[1],
813 self.physical_id[2], self.physical_id[3]))
815 val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
816 (node_a, minor_a, node_b, minor_b, port, phy))
817 if self.children and self.children.count(None) == 0:
818 val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
820 val += "no local storage"
822 val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
823 (self.dev_type, self.logical_id, self.physical_id, self.children))
824 if self.iv_name is None:
825 val += ", not visible"
827 val += ", visible as /dev/%s" % self.iv_name
828 if isinstance(self.size, int):
829 val += ", size=%dm)>" % self.size
831 val += ", size='%s')>" % (self.size,)
835 """Checks that this disk is correctly configured.
839 if self.mode not in constants.DISK_ACCESS_SET:
840 all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
843 def UpgradeConfig(self):
844 """Fill defaults for missing configuration values.
848 for child in self.children:
849 child.UpgradeConfig()
851 # FIXME: Make this configurable in Ganeti 2.7
853 # add here config upgrade for this disk
856 def ComputeLDParams(disk_template, disk_params):
857 """Computes Logical Disk parameters from Disk Template parameters.
859 @type disk_template: string
860 @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
861 @type disk_params: dict
862 @param disk_params: disk template parameters;
863 dict(template_name -> parameters
865 @return: a list of dicts, one for each node of the disk hierarchy. Each dict
866 contains the LD parameters of the node. The tree is flattened in-order.
869 if disk_template not in constants.DISK_TEMPLATES:
870 raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
872 assert disk_template in disk_params
875 dt_params = disk_params[disk_template]
876 if disk_template == constants.DT_DRBD8:
878 constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
879 constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
880 constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
881 constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
882 constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
883 constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
884 constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
885 constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
886 constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
887 constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
888 constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
889 constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
893 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8],
896 result.append(drbd_params)
900 constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
903 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
905 result.append(data_params)
909 constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
912 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
914 result.append(meta_params)
916 elif (disk_template == constants.DT_FILE or
917 disk_template == constants.DT_SHARED_FILE):
918 result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
920 elif disk_template == constants.DT_PLAIN:
922 constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
925 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV],
927 result.append(params)
929 elif disk_template == constants.DT_BLOCK:
930 result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
932 elif disk_template == constants.DT_RBD:
934 constants.LDP_POOL: dt_params[constants.RBD_POOL]
937 FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD],
939 result.append(params)
944 class InstancePolicy(ConfigObject):
945 """Config object representing instance policy limits dictionary.
948 Note that this object is not actually used in the config, it's just
949 used as a placeholder for a few functions.
953 def CheckParameterSyntax(cls, ipolicy, check_std):
954 """ Check the instance policy for validity.
957 for param in constants.ISPECS_PARAMETERS:
958 InstancePolicy.CheckISpecSyntax(ipolicy, param, check_std)
959 if constants.IPOLICY_DTS in ipolicy:
960 InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
961 for key in constants.IPOLICY_PARAMETERS:
963 InstancePolicy.CheckParameter(key, ipolicy[key])
964 wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
966 raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
967 utils.CommaJoin(wrong_keys))
970 def CheckISpecSyntax(cls, ipolicy, name, check_std):
971 """Check the instance policy for validity on a given key.
973 We check if the instance policy makes sense for a given key, that is
974 if ipolicy[min][name] <= ipolicy[std][name] <= ipolicy[max][name].
977 @param ipolicy: dictionary with min, max, std specs
979 @param name: what are the limits for
980 @type check_std: bool
981 @param check_std: Whether to check std value or just assume compliance
982 @raise errors.ConfigureError: when specs for given name are not valid
985 min_v = ipolicy[constants.ISPECS_MIN].get(name, 0)
988 std_v = ipolicy[constants.ISPECS_STD].get(name, min_v)
994 max_v = ipolicy[constants.ISPECS_MAX].get(name, std_v)
995 err = ("Invalid specification of min/max/std values for %s: %s/%s/%s" %
997 ipolicy[constants.ISPECS_MIN].get(name, "-"),
998 ipolicy[constants.ISPECS_MAX].get(name, "-"),
1000 if min_v > std_v or std_v > max_v:
1001 raise errors.ConfigurationError(err)
1004 def CheckDiskTemplates(cls, disk_templates):
1005 """Checks the disk templates for validity.
1008 wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1010 raise errors.ConfigurationError("Invalid disk template(s) %s" %
1011 utils.CommaJoin(wrong))
1014 def CheckParameter(cls, key, value):
1015 """Checks a parameter.
1017 Currently we expect all parameters to be float values.
1022 except (TypeError, ValueError), err:
1023 raise errors.ConfigurationError("Invalid value for key" " '%s':"
1024 " '%s', error: %s" % (key, value, err))
1027 class Instance(TaggableObject):
1028 """Config object representing an instance."""
1043 ] + _TIMESTAMPS + _UUID
1045 def _ComputeSecondaryNodes(self):
1046 """Compute the list of secondary nodes.
1048 This is a simple wrapper over _ComputeAllNodes.
1051 all_nodes = set(self._ComputeAllNodes())
1052 all_nodes.discard(self.primary_node)
1053 return tuple(all_nodes)
1055 secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1056 "List of secondary nodes")
1058 def _ComputeAllNodes(self):
1059 """Compute the list of all nodes.
1061 Since the data is already there (in the drbd disks), keeping it as
1062 a separate normal attribute is redundant and if not properly
1063 synchronised can cause problems. Thus it's better to compute it
1067 def _Helper(nodes, device):
1068 """Recursively computes nodes given a top device."""
1069 if device.dev_type in constants.LDS_DRBD:
1070 nodea, nodeb = device.logical_id[:2]
1074 for child in device.children:
1075 _Helper(nodes, child)
1078 all_nodes.add(self.primary_node)
1079 for device in self.disks:
1080 _Helper(all_nodes, device)
1081 return tuple(all_nodes)
1083 all_nodes = property(_ComputeAllNodes, None, None,
1084 "List of all nodes of the instance")
1086 def MapLVsByNode(self, lvmap=None, devs=None, node=None):
1087 """Provide a mapping of nodes to LVs this instance owns.
1089 This function figures out what logical volumes should belong on
1090 which nodes, recursing through a device tree.
1092 @param lvmap: optional dictionary to receive the
1093 'node' : ['lv', ...] data.
1095 @return: None if lvmap arg is given, otherwise, a dictionary of
1096 the form { 'nodename' : ['volume1', 'volume2', ...], ... };
1097 volumeN is of the form "vg_name/lv_name", compatible with
1102 node = self.primary_node
1110 if not node in lvmap:
1118 if dev.dev_type == constants.LD_LV:
1119 lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1121 elif dev.dev_type in constants.LDS_DRBD:
1123 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1124 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1127 self.MapLVsByNode(lvmap, dev.children, node)
1131 def FindDisk(self, idx):
1132 """Find a disk given having a specified index.
1134 This is just a wrapper that does validation of the index.
1137 @param idx: the disk index
1139 @return: the corresponding disk
1140 @raise errors.OpPrereqError: when the given index is not valid
1145 return self.disks[idx]
1146 except (TypeError, ValueError), err:
1147 raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1150 raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1151 " 0 to %d" % (idx, len(self.disks) - 1),
1155 """Instance-specific conversion to standard python types.
1157 This replaces the children lists of objects with lists of standard
1161 bo = super(Instance, self).ToDict()
1163 for attr in "nics", "disks":
1164 alist = bo.get(attr, None)
1166 nlist = self._ContainerToDicts(alist)
1173 def FromDict(cls, val):
1174 """Custom function for instances.
1177 if "admin_state" not in val:
1178 if val.get("admin_up", False):
1179 val["admin_state"] = constants.ADMINST_UP
1181 val["admin_state"] = constants.ADMINST_DOWN
1182 if "admin_up" in val:
1184 obj = super(Instance, cls).FromDict(val)
1185 obj.nics = cls._ContainerFromDicts(obj.nics, list, NIC)
1186 obj.disks = cls._ContainerFromDicts(obj.disks, list, Disk)
1189 def UpgradeConfig(self):
1190 """Fill defaults for missing configuration values.
1193 for nic in self.nics:
1195 for disk in self.disks:
1196 disk.UpgradeConfig()
1198 for key in constants.HVC_GLOBALS:
1200 del self.hvparams[key]
1203 if self.osparams is None:
1205 UpgradeBeParams(self.beparams)
1208 class OS(ConfigObject):
1209 """Config object representing an operating system.
1211 @type supported_parameters: list
1212 @ivar supported_parameters: a list of tuples, name and description,
1213 containing the supported parameters by this OS
1215 @type VARIANT_DELIM: string
1216 @cvar VARIANT_DELIM: the variant delimiter
1228 "supported_variants",
1229 "supported_parameters",
1235 def SplitNameVariant(cls, name):
1236 """Splits the name into the proper name and variant.
1238 @param name: the OS (unprocessed) name
1240 @return: a list of two elements; if the original name didn't
1241 contain a variant, it's returned as an empty string
1244 nv = name.split(cls.VARIANT_DELIM, 1)
1250 def GetName(cls, name):
1251 """Returns the proper name of the os (without the variant).
1253 @param name: the OS (unprocessed) name
1256 return cls.SplitNameVariant(name)[0]
1259 def GetVariant(cls, name):
1260 """Returns the variant the os (without the base name).
1262 @param name: the OS (unprocessed) name
1265 return cls.SplitNameVariant(name)[1]
1268 class NodeHvState(ConfigObject):
1269 """Hypvervisor state on a node.
1271 @ivar mem_total: Total amount of memory
1272 @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1274 @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1276 @ivar mem_inst: Memory used by instances living on node
1277 @ivar cpu_total: Total node CPU core count
1278 @ivar cpu_node: Number of CPU cores reserved for the node itself
1291 class NodeDiskState(ConfigObject):
1292 """Disk state on a node.
1302 class Node(TaggableObject):
1303 """Config object representing a node.
1305 @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1306 @ivar hv_state_static: Hypervisor state overriden by user
1307 @ivar disk_state: Disk state (e.g. free space)
1308 @ivar disk_state_static: Disk state overriden by user
1327 "disk_state_static",
1328 ] + _TIMESTAMPS + _UUID
1330 def UpgradeConfig(self):
1331 """Fill defaults for missing configuration values.
1334 # pylint: disable=E0203
1335 # because these are "defined" via slots, not manually
1336 if self.master_capable is None:
1337 self.master_capable = True
1339 if self.vm_capable is None:
1340 self.vm_capable = True
1342 if self.ndparams is None:
1345 if self.powered is None:
1349 """Custom function for serializing.
1352 data = super(Node, self).ToDict()
1354 hv_state = data.get("hv_state", None)
1355 if hv_state is not None:
1356 data["hv_state"] = self._ContainerToDicts(hv_state)
1358 disk_state = data.get("disk_state", None)
1359 if disk_state is not None:
1360 data["disk_state"] = \
1361 dict((key, self._ContainerToDicts(value))
1362 for (key, value) in disk_state.items())
1367 def FromDict(cls, val):
1368 """Custom function for deserializing.
1371 obj = super(Node, cls).FromDict(val)
1373 if obj.hv_state is not None:
1374 obj.hv_state = cls._ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1376 if obj.disk_state is not None:
1378 dict((key, cls._ContainerFromDicts(value, dict, NodeDiskState))
1379 for (key, value) in obj.disk_state.items())
1384 class NodeGroup(TaggableObject):
1385 """Config object representing a node group."""
1394 "disk_state_static",
1396 ] + _TIMESTAMPS + _UUID
1399 """Custom function for nodegroup.
1401 This discards the members object, which gets recalculated and is only kept
1405 mydict = super(NodeGroup, self).ToDict()
1406 del mydict["members"]
1410 def FromDict(cls, val):
1411 """Custom function for nodegroup.
1413 The members slot is initialized to an empty list, upon deserialization.
1416 obj = super(NodeGroup, cls).FromDict(val)
1420 def UpgradeConfig(self):
1421 """Fill defaults for missing configuration values.
1424 if self.ndparams is None:
1427 if self.serial_no is None:
1430 if self.alloc_policy is None:
1431 self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1433 # We only update mtime, and not ctime, since we would not be able
1434 # to provide a correct value for creation time.
1435 if self.mtime is None:
1436 self.mtime = time.time()
1438 if self.diskparams is None:
1439 self.diskparams = {}
1440 if self.ipolicy is None:
1441 self.ipolicy = MakeEmptyIPolicy()
1443 def FillND(self, node):
1444 """Return filled out ndparams for L{objects.Node}
1446 @type node: L{objects.Node}
1447 @param node: A Node object to fill
1448 @return a copy of the node's ndparams with defaults filled
1451 return self.SimpleFillND(node.ndparams)
1453 def SimpleFillND(self, ndparams):
1454 """Fill a given ndparams dict with defaults.
1456 @type ndparams: dict
1457 @param ndparams: the dict to fill
1459 @return: a copy of the passed in ndparams with missing keys filled
1460 from the node group defaults
1463 return FillDict(self.ndparams, ndparams)
1466 class Cluster(TaggableObject):
1467 """Config object representing the cluster."""
1471 "highest_used_port",
1474 "volume_group_name",
1476 "drbd_usermode_helper",
1478 "default_hypervisor",
1483 "use_external_mip_script",
1486 "shared_file_storage_dir",
1487 "enabled_hypervisors",
1496 "candidate_pool_size",
1499 "maintain_node_health",
1501 "default_iallocator",
1504 "primary_ip_family",
1505 "prealloc_wipe_disks",
1507 "disk_state_static",
1508 ] + _TIMESTAMPS + _UUID
1510 def UpgradeConfig(self):
1511 """Fill defaults for missing configuration values.
1514 # pylint: disable=E0203
1515 # because these are "defined" via slots, not manually
1516 if self.hvparams is None:
1517 self.hvparams = constants.HVC_DEFAULTS
1519 for hypervisor in self.hvparams:
1520 self.hvparams[hypervisor] = FillDict(
1521 constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1523 if self.os_hvp is None:
1526 # osparams added before 2.2
1527 if self.osparams is None:
1530 self.ndparams = UpgradeNDParams(self.ndparams)
1532 self.beparams = UpgradeGroupedParams(self.beparams,
1533 constants.BEC_DEFAULTS)
1534 for beparams_group in self.beparams:
1535 UpgradeBeParams(self.beparams[beparams_group])
1537 migrate_default_bridge = not self.nicparams
1538 self.nicparams = UpgradeGroupedParams(self.nicparams,
1539 constants.NICC_DEFAULTS)
1540 if migrate_default_bridge:
1541 self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1544 if self.modify_etc_hosts is None:
1545 self.modify_etc_hosts = True
1547 if self.modify_ssh_setup is None:
1548 self.modify_ssh_setup = True
1550 # default_bridge is no longer used in 2.1. The slot is left there to
1551 # support auto-upgrading. It can be removed once we decide to deprecate
1552 # upgrading straight from 2.0.
1553 if self.default_bridge is not None:
1554 self.default_bridge = None
1556 # default_hypervisor is just the first enabled one in 2.1. This slot and
1557 # code can be removed once upgrading straight from 2.0 is deprecated.
1558 if self.default_hypervisor is not None:
1559 self.enabled_hypervisors = ([self.default_hypervisor] +
1560 [hvname for hvname in self.enabled_hypervisors
1561 if hvname != self.default_hypervisor])
1562 self.default_hypervisor = None
1564 # maintain_node_health added after 2.1.1
1565 if self.maintain_node_health is None:
1566 self.maintain_node_health = False
1568 if self.uid_pool is None:
1571 if self.default_iallocator is None:
1572 self.default_iallocator = ""
1574 # reserved_lvs added before 2.2
1575 if self.reserved_lvs is None:
1576 self.reserved_lvs = []
1578 # hidden and blacklisted operating systems added before 2.2.1
1579 if self.hidden_os is None:
1582 if self.blacklisted_os is None:
1583 self.blacklisted_os = []
1585 # primary_ip_family added before 2.3
1586 if self.primary_ip_family is None:
1587 self.primary_ip_family = AF_INET
1589 if self.master_netmask is None:
1590 ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1591 self.master_netmask = ipcls.iplen
1593 if self.prealloc_wipe_disks is None:
1594 self.prealloc_wipe_disks = False
1596 # shared_file_storage_dir added before 2.5
1597 if self.shared_file_storage_dir is None:
1598 self.shared_file_storage_dir = ""
1600 if self.use_external_mip_script is None:
1601 self.use_external_mip_script = False
1604 self.diskparams = UpgradeDiskParams(self.diskparams)
1606 self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1608 # instance policy added before 2.6
1609 if self.ipolicy is None:
1610 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1612 # we can either make sure to upgrade the ipolicy always, or only
1613 # do it in some corner cases (e.g. missing keys); note that this
1614 # will break any removal of keys from the ipolicy dict
1615 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1618 def primary_hypervisor(self):
1619 """The first hypervisor is the primary.
1621 Useful, for example, for L{Node}'s hv/disk state.
1624 return self.enabled_hypervisors[0]
1627 """Custom function for cluster.
1630 mydict = super(Cluster, self).ToDict()
1631 mydict["tcpudp_port_pool"] = list(self.tcpudp_port_pool)
1635 def FromDict(cls, val):
1636 """Custom function for cluster.
1639 obj = super(Cluster, cls).FromDict(val)
1640 if not isinstance(obj.tcpudp_port_pool, set):
1641 obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1644 def SimpleFillDP(self, diskparams):
1645 """Fill a given diskparams dict with cluster defaults.
1647 @param diskparams: The diskparams
1648 @return: The defaults dict
1651 return FillDiskParams(self.diskparams, diskparams)
1653 def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1654 """Get the default hypervisor parameters for the cluster.
1656 @param hypervisor: the hypervisor name
1657 @param os_name: if specified, we'll also update the defaults for this OS
1658 @param skip_keys: if passed, list of keys not to use
1659 @return: the defaults dict
1662 if skip_keys is None:
1665 fill_stack = [self.hvparams.get(hypervisor, {})]
1666 if os_name is not None:
1667 os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1668 fill_stack.append(os_hvp)
1671 for o_dict in fill_stack:
1672 ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1676 def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1677 """Fill a given hvparams dict with cluster defaults.
1679 @type hv_name: string
1680 @param hv_name: the hypervisor to use
1681 @type os_name: string
1682 @param os_name: the OS to use for overriding the hypervisor defaults
1683 @type skip_globals: boolean
1684 @param skip_globals: if True, the global hypervisor parameters will
1687 @return: a copy of the given hvparams with missing keys filled from
1688 the cluster defaults
1692 skip_keys = constants.HVC_GLOBALS
1696 def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1697 return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1699 def FillHV(self, instance, skip_globals=False):
1700 """Fill an instance's hvparams dict with cluster defaults.
1702 @type instance: L{objects.Instance}
1703 @param instance: the instance parameter to fill
1704 @type skip_globals: boolean
1705 @param skip_globals: if True, the global hypervisor parameters will
1708 @return: a copy of the instance's hvparams with missing keys filled from
1709 the cluster defaults
1712 return self.SimpleFillHV(instance.hypervisor, instance.os,
1713 instance.hvparams, skip_globals)
1715 def SimpleFillBE(self, beparams):
1716 """Fill a given beparams dict with cluster defaults.
1718 @type beparams: dict
1719 @param beparams: the dict to fill
1721 @return: a copy of the passed in beparams with missing keys filled
1722 from the cluster defaults
1725 return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1727 def FillBE(self, instance):
1728 """Fill an instance's beparams dict with cluster defaults.
1730 @type instance: L{objects.Instance}
1731 @param instance: the instance parameter to fill
1733 @return: a copy of the instance's beparams with missing keys filled from
1734 the cluster defaults
1737 return self.SimpleFillBE(instance.beparams)
1739 def SimpleFillNIC(self, nicparams):
1740 """Fill a given nicparams dict with cluster defaults.
1742 @type nicparams: dict
1743 @param nicparams: the dict to fill
1745 @return: a copy of the passed in nicparams with missing keys filled
1746 from the cluster defaults
1749 return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1751 def SimpleFillOS(self, os_name, os_params):
1752 """Fill an instance's osparams dict with cluster defaults.
1754 @type os_name: string
1755 @param os_name: the OS name to use
1756 @type os_params: dict
1757 @param os_params: the dict to fill with default values
1759 @return: a copy of the instance's osparams with missing keys filled from
1760 the cluster defaults
1763 name_only = os_name.split("+", 1)[0]
1765 result = self.osparams.get(name_only, {})
1767 result = FillDict(result, self.osparams.get(os_name, {}))
1769 return FillDict(result, os_params)
1772 def SimpleFillHvState(hv_state):
1773 """Fill an hv_state sub dict with cluster defaults.
1776 return FillDict(constants.HVST_DEFAULTS, hv_state)
1779 def SimpleFillDiskState(disk_state):
1780 """Fill an disk_state sub dict with cluster defaults.
1783 return FillDict(constants.DS_DEFAULTS, disk_state)
1785 def FillND(self, node, nodegroup):
1786 """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1788 @type node: L{objects.Node}
1789 @param node: A Node object to fill
1790 @type nodegroup: L{objects.NodeGroup}
1791 @param nodegroup: A Node object to fill
1792 @return a copy of the node's ndparams with defaults filled
1795 return self.SimpleFillND(nodegroup.FillND(node))
1797 def SimpleFillND(self, ndparams):
1798 """Fill a given ndparams dict with defaults.
1800 @type ndparams: dict
1801 @param ndparams: the dict to fill
1803 @return: a copy of the passed in ndparams with missing keys filled
1804 from the cluster defaults
1807 return FillDict(self.ndparams, ndparams)
1809 def SimpleFillIPolicy(self, ipolicy):
1810 """ Fill instance policy dict with defaults.
1813 @param ipolicy: the dict to fill
1815 @return: a copy of passed ipolicy with missing keys filled from
1816 the cluster defaults
1819 return FillIPolicy(self.ipolicy, ipolicy)
1822 class BlockDevStatus(ConfigObject):
1823 """Config object representing the status of a block device."""
1835 class ImportExportStatus(ConfigObject):
1836 """Config object representing the status of an import or export."""
1842 "progress_throughput",
1850 class ImportExportOptions(ConfigObject):
1851 """Options for import/export daemon
1853 @ivar key_name: X509 key name (None for cluster certificate)
1854 @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1855 @ivar compress: Compression method (one of L{constants.IEC_ALL})
1856 @ivar magic: Used to ensure the connection goes to the right disk
1857 @ivar ipv6: Whether to use IPv6
1858 @ivar connect_timeout: Number of seconds for establishing connection
1871 class ConfdRequest(ConfigObject):
1872 """Object holding a confd request.
1874 @ivar protocol: confd protocol version
1875 @ivar type: confd query type
1876 @ivar query: query request
1877 @ivar rsalt: requested reply salt
1888 class ConfdReply(ConfigObject):
1889 """Object holding a confd reply.
1891 @ivar protocol: confd protocol version
1892 @ivar status: reply status code (ok, error)
1893 @ivar answer: confd query reply
1894 @ivar serial: configuration serial number
1905 class QueryFieldDefinition(ConfigObject):
1906 """Object holding a query field definition.
1908 @ivar name: Field name
1909 @ivar title: Human-readable title
1910 @ivar kind: Field type
1911 @ivar doc: Human-readable description
1922 class _QueryResponseBase(ConfigObject):
1928 """Custom function for serializing.
1931 mydict = super(_QueryResponseBase, self).ToDict()
1932 mydict["fields"] = self._ContainerToDicts(mydict["fields"])
1936 def FromDict(cls, val):
1937 """Custom function for de-serializing.
1940 obj = super(_QueryResponseBase, cls).FromDict(val)
1941 obj.fields = cls._ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
1945 class QueryResponse(_QueryResponseBase):
1946 """Object holding the response to a query.
1948 @ivar fields: List of L{QueryFieldDefinition} objects
1949 @ivar data: Requested data
1957 class QueryFieldsRequest(ConfigObject):
1958 """Object holding a request for querying available fields.
1967 class QueryFieldsResponse(_QueryResponseBase):
1968 """Object holding the response to a query for fields.
1970 @ivar fields: List of L{QueryFieldDefinition} objects
1977 class MigrationStatus(ConfigObject):
1978 """Object holding the status of a migration.
1988 class InstanceConsole(ConfigObject):
1989 """Object describing how to access the console of an instance.
2004 """Validates contents of this object.
2007 assert self.kind in constants.CONS_ALL, "Unknown console type"
2008 assert self.instance, "Missing instance name"
2009 assert self.message or self.kind in [constants.CONS_SSH,
2010 constants.CONS_SPICE,
2012 assert self.host or self.kind == constants.CONS_MESSAGE
2013 assert self.port or self.kind in [constants.CONS_MESSAGE,
2015 assert self.user or self.kind in [constants.CONS_MESSAGE,
2016 constants.CONS_SPICE,
2018 assert self.command or self.kind in [constants.CONS_MESSAGE,
2019 constants.CONS_SPICE,
2021 assert self.display or self.kind in [constants.CONS_MESSAGE,
2022 constants.CONS_SPICE,
2027 class SerializableConfigParser(ConfigParser.SafeConfigParser):
2028 """Simple wrapper over ConfigParse that allows serialization.
2030 This class is basically ConfigParser.SafeConfigParser with two
2031 additional methods that allow it to serialize/unserialize to/from a
2036 """Dump this instance and return the string representation."""
2039 return buf.getvalue()
2042 def Loads(cls, data):
2043 """Load data from a string."""
2044 buf = StringIO(data)