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 explicitly 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 objectutils
48 from ganeti import utils
50 from socket import AF_INET
53 __all__ = ["ConfigObject", "ConfigData", "NIC", "Disk", "Instance",
54 "OS", "Node", "NodeGroup", "Cluster", "FillDict", "Network"]
56 _TIMESTAMPS = ["ctime", "mtime"]
60 def FillDict(defaults_dict, custom_dict, skip_keys=None):
61 """Basic function to apply settings on top a default dict.
63 @type defaults_dict: dict
64 @param defaults_dict: dictionary holding the default values
65 @type custom_dict: dict
66 @param custom_dict: dictionary holding customized value
68 @param skip_keys: which keys not to fill
70 @return: dict with the 'full' values
73 ret_dict = copy.deepcopy(defaults_dict)
74 ret_dict.update(custom_dict)
84 def FillIPolicy(default_ipolicy, custom_ipolicy, skip_keys=None):
85 """Fills an instance policy with defaults.
88 assert frozenset(default_ipolicy.keys()) == constants.IPOLICY_ALL_KEYS
90 for key in constants.IPOLICY_ISPECS:
91 ret_dict[key] = FillDict(default_ipolicy[key],
92 custom_ipolicy.get(key, {}),
95 for key in [constants.IPOLICY_DTS]:
96 ret_dict[key] = list(custom_ipolicy.get(key, default_ipolicy[key]))
97 # other items which we know we can directly copy (immutables)
98 for key in constants.IPOLICY_PARAMETERS:
99 ret_dict[key] = custom_ipolicy.get(key, default_ipolicy[key])
104 def FillDiskParams(default_dparams, custom_dparams, skip_keys=None):
105 """Fills the disk parameter defaults.
107 @see: L{FillDict} for parameters and return value
110 assert frozenset(default_dparams.keys()) == constants.DISK_TEMPLATES
112 return dict((dt, FillDict(default_dparams[dt], custom_dparams.get(dt, {}),
113 skip_keys=skip_keys))
114 for dt in constants.DISK_TEMPLATES)
117 def UpgradeGroupedParams(target, defaults):
118 """Update all groups for the target parameter.
120 @type target: dict of dicts
121 @param target: {group: {parameter: value}}
123 @param defaults: default parameter values
127 target = {constants.PP_DEFAULT: defaults}
130 target[group] = FillDict(defaults, target[group])
134 def UpgradeBeParams(target):
135 """Update the be parameters dict to the new format.
138 @param target: "be" parameters dict
141 if constants.BE_MEMORY in target:
142 memory = target[constants.BE_MEMORY]
143 target[constants.BE_MAXMEM] = memory
144 target[constants.BE_MINMEM] = memory
145 del target[constants.BE_MEMORY]
148 def UpgradeDiskParams(diskparams):
149 """Upgrade the disk parameters.
151 @type diskparams: dict
152 @param diskparams: disk parameters to upgrade
154 @return: the upgraded disk parameters dict
160 result = FillDiskParams(constants.DISK_DT_DEFAULTS, diskparams)
165 def UpgradeNDParams(ndparams):
166 """Upgrade ndparams structure.
169 @param ndparams: disk parameters to upgrade
171 @return: the upgraded node parameters dict
177 if (constants.ND_OOB_PROGRAM in ndparams and
178 ndparams[constants.ND_OOB_PROGRAM] is None):
179 # will be reset by the line below
180 del ndparams[constants.ND_OOB_PROGRAM]
181 return FillDict(constants.NDC_DEFAULTS, ndparams)
184 def MakeEmptyIPolicy():
185 """Create empty IPolicy dictionary.
189 (constants.ISPECS_MIN, {}),
190 (constants.ISPECS_MAX, {}),
191 (constants.ISPECS_STD, {}),
195 class ConfigObject(objectutils.ValidatedSlots):
196 """A generic config object.
198 It has the following properties:
200 - provides somewhat safe recursive unpickling and pickling for its classes
201 - unset attributes which are defined in slots are always returned
202 as None instead of raising an error
204 Classes derived from this must always declare __slots__ (we use many
205 config objects and the memory reduction is useful)
210 def __getattr__(self, name):
211 if name not in self.GetAllSlots():
212 raise AttributeError("Invalid object attribute %s.%s" %
213 (type(self).__name__, name))
216 def __setstate__(self, state):
217 slots = self.GetAllSlots()
220 setattr(self, name, state[name])
223 """Validates the slots.
228 """Convert to a dict holding only standard python types.
230 The generic routine just dumps all of this object's attributes in
231 a dict. It does not work if the class has children who are
232 ConfigObjects themselves (e.g. the nics list in an Instance), in
233 which case the object should subclass the function in order to
234 make sure all objects returned are only standard python types.
238 for name in self.GetAllSlots():
239 value = getattr(self, name, None)
240 if value is not None:
244 __getstate__ = ToDict
247 def FromDict(cls, val):
248 """Create an object from a dictionary.
250 This generic routine takes a dict, instantiates a new instance of
251 the given class, and sets attributes based on the dict content.
253 As for `ToDict`, this does not work if the class has children
254 who are ConfigObjects themselves (e.g. the nics list in an
255 Instance), in which case the object should subclass the function
256 and alter the objects.
259 if not isinstance(val, dict):
260 raise errors.ConfigurationError("Invalid object passed to FromDict:"
261 " expected dict, got %s" % type(val))
262 val_str = dict([(str(k), v) for k, v in val.iteritems()])
263 obj = cls(**val_str) # pylint: disable=W0142
267 def _ContainerToDicts(container):
268 """Convert the elements of a container to standard python types.
270 This method converts a container with elements derived from
271 ConfigData to standard python types. If the container is a dict,
272 we don't touch the keys, only the values.
275 if isinstance(container, dict):
276 ret = dict([(k, v.ToDict()) for k, v in container.iteritems()])
277 elif isinstance(container, (list, tuple, set, frozenset)):
278 ret = [elem.ToDict() for elem in container]
280 raise TypeError("Invalid type %s passed to _ContainerToDicts" %
285 def _ContainerFromDicts(source, c_type, e_type):
286 """Convert a container from standard python types.
288 This method converts a container with standard python types to
289 ConfigData objects. If the container is a dict, we don't touch the
290 keys, only the values.
293 if not isinstance(c_type, type):
294 raise TypeError("Container type %s passed to _ContainerFromDicts is"
295 " not a type" % type(c_type))
299 ret = dict([(k, e_type.FromDict(v)) for k, v in source.iteritems()])
300 elif c_type in (list, tuple, set, frozenset):
301 ret = c_type([e_type.FromDict(elem) for elem in source])
303 raise TypeError("Invalid container type %s passed to"
304 " _ContainerFromDicts" % c_type)
308 """Makes a deep copy of the current object and its children.
311 dict_form = self.ToDict()
312 clone_obj = self.__class__.FromDict(dict_form)
316 """Implement __repr__ for ConfigObjects."""
317 return repr(self.ToDict())
319 def UpgradeConfig(self):
320 """Fill defaults for missing configuration values.
322 This method will be called at configuration load time, and its
323 implementation will be object dependent.
329 class TaggableObject(ConfigObject):
330 """An generic class supporting tags.
334 VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
337 def ValidateTag(cls, tag):
338 """Check if a tag is valid.
340 If the tag is invalid, an errors.TagError will be raised. The
341 function has no return value.
344 if not isinstance(tag, basestring):
345 raise errors.TagError("Invalid tag type (not a string)")
346 if len(tag) > constants.MAX_TAG_LEN:
347 raise errors.TagError("Tag too long (>%d characters)" %
348 constants.MAX_TAG_LEN)
350 raise errors.TagError("Tags cannot be empty")
351 if not cls.VALID_TAG_RE.match(tag):
352 raise errors.TagError("Tag contains invalid characters")
355 """Return the tags list.
358 tags = getattr(self, "tags", None)
360 tags = self.tags = set()
363 def AddTag(self, tag):
367 self.ValidateTag(tag)
368 tags = self.GetTags()
369 if len(tags) >= constants.MAX_TAGS_PER_OBJ:
370 raise errors.TagError("Too many tags")
371 self.GetTags().add(tag)
373 def RemoveTag(self, tag):
377 self.ValidateTag(tag)
378 tags = self.GetTags()
382 raise errors.TagError("Tag not found")
385 """Taggable-object-specific conversion to standard python types.
387 This replaces the tags set with a list.
390 bo = super(TaggableObject, self).ToDict()
392 tags = bo.get("tags", None)
393 if isinstance(tags, set):
394 bo["tags"] = list(tags)
398 def FromDict(cls, val):
399 """Custom function for instances.
402 obj = super(TaggableObject, cls).FromDict(val)
403 if hasattr(obj, "tags") and isinstance(obj.tags, list):
404 obj.tags = set(obj.tags)
408 class MasterNetworkParameters(ConfigObject):
409 """Network configuration parameters for the master
411 @ivar name: master name
413 @ivar netmask: master netmask
414 @ivar netdev: master network device
415 @ivar ip_family: master IP family
427 class ConfigData(ConfigObject):
428 """Top-level config object."""
440 """Custom function for top-level config data.
442 This just replaces the list of instances, nodes and the cluster
443 with standard python types.
446 mydict = super(ConfigData, self).ToDict()
447 mydict["cluster"] = mydict["cluster"].ToDict()
448 for key in "nodes", "instances", "nodegroups", "networks":
449 mydict[key] = self._ContainerToDicts(mydict[key])
454 def FromDict(cls, val):
455 """Custom function for top-level config data
458 obj = super(ConfigData, cls).FromDict(val)
459 obj.cluster = Cluster.FromDict(obj.cluster)
460 obj.nodes = cls._ContainerFromDicts(obj.nodes, dict, Node)
461 obj.instances = cls._ContainerFromDicts(obj.instances, dict, Instance)
462 obj.nodegroups = cls._ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
463 obj.networks = cls._ContainerFromDicts(obj.networks, dict, Network)
466 def HasAnyDiskOfType(self, dev_type):
467 """Check if in there is at disk of the given type in the configuration.
469 @type dev_type: L{constants.LDS_BLOCK}
470 @param dev_type: the type to look for
472 @return: boolean indicating if a disk of the given type was found or not
475 for instance in self.instances.values():
476 for disk in instance.disks:
477 if disk.IsBasedOnDiskType(dev_type):
481 def UpgradeConfig(self):
482 """Fill defaults for missing configuration values.
485 self.cluster.UpgradeConfig()
486 for node in self.nodes.values():
488 for instance in self.instances.values():
489 instance.UpgradeConfig()
490 if self.nodegroups is None:
492 for nodegroup in self.nodegroups.values():
493 nodegroup.UpgradeConfig()
494 if self.cluster.drbd_usermode_helper is None:
495 # To decide if we set an helper let's check if at least one instance has
496 # a DRBD disk. This does not cover all the possible scenarios but it
497 # gives a good approximation.
498 if self.HasAnyDiskOfType(constants.LD_DRBD8):
499 self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
500 if self.networks is None:
504 class NIC(ConfigObject):
505 """Config object representing a network card."""
506 __slots__ = ["mac", "ip", "network", "nicparams", "netinfo"]
509 def CheckParameterSyntax(cls, nicparams):
510 """Check the given parameters for validity.
512 @type nicparams: dict
513 @param nicparams: dictionary with parameter names/value
514 @raise errors.ConfigurationError: when a parameter is not valid
517 mode = nicparams[constants.NIC_MODE]
518 if (mode not in constants.NIC_VALID_MODES and
519 mode != constants.VALUE_AUTO):
520 raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
522 if (mode == constants.NIC_MODE_BRIDGED and
523 not nicparams[constants.NIC_LINK]):
524 raise errors.ConfigurationError("Missing bridged NIC link")
527 class Disk(ConfigObject):
528 """Config object representing a block device."""
529 __slots__ = ["dev_type", "logical_id", "physical_id",
530 "children", "iv_name", "size", "mode", "params"]
532 def CreateOnSecondary(self):
533 """Test if this device needs to be created on a secondary node."""
534 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
536 def AssembleOnSecondary(self):
537 """Test if this device needs to be assembled on a secondary node."""
538 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
540 def OpenOnSecondary(self):
541 """Test if this device needs to be opened on a secondary node."""
542 return self.dev_type in (constants.LD_LV,)
544 def StaticDevPath(self):
545 """Return the device path if this device type has a static one.
547 Some devices (LVM for example) live always at the same /dev/ path,
548 irrespective of their status. For such devices, we return this
549 path, for others we return None.
551 @warning: The path returned is not a normalized pathname; callers
552 should check that it is a valid path.
555 if self.dev_type == constants.LD_LV:
556 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
557 elif self.dev_type == constants.LD_BLOCKDEV:
558 return self.logical_id[1]
559 elif self.dev_type == constants.LD_RBD:
560 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
563 def ChildrenNeeded(self):
564 """Compute the needed number of children for activation.
566 This method will return either -1 (all children) or a positive
567 number denoting the minimum number of children needed for
568 activation (only mirrored devices will usually return >=0).
570 Currently, only DRBD8 supports diskless activation (therefore we
571 return 0), for all other we keep the previous semantics and return
575 if self.dev_type == constants.LD_DRBD8:
579 def IsBasedOnDiskType(self, dev_type):
580 """Check if the disk or its children are based on the given type.
582 @type dev_type: L{constants.LDS_BLOCK}
583 @param dev_type: the type to look for
585 @return: boolean indicating if a device of the given type was found or not
589 for child in self.children:
590 if child.IsBasedOnDiskType(dev_type):
592 return self.dev_type == dev_type
594 def GetNodes(self, node):
595 """This function returns the nodes this device lives on.
597 Given the node on which the parent of the device lives on (or, in
598 case of a top-level device, the primary node of the devices'
599 instance), this function will return a list of nodes on which this
600 devices needs to (or can) be assembled.
603 if self.dev_type in [constants.LD_LV, constants.LD_FILE,
604 constants.LD_BLOCKDEV, constants.LD_RBD,
607 elif self.dev_type in constants.LDS_DRBD:
608 result = [self.logical_id[0], self.logical_id[1]]
609 if node not in result:
610 raise errors.ConfigurationError("DRBD device passed unknown node")
612 raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
615 def ComputeNodeTree(self, parent_node):
616 """Compute the node/disk tree for this disk and its children.
618 This method, given the node on which the parent disk lives, will
619 return the list of all (node, disk) pairs which describe the disk
620 tree in the most compact way. For example, a drbd/lvm stack
621 will be returned as (primary_node, drbd) and (secondary_node, drbd)
622 which represents all the top-level devices on the nodes.
625 my_nodes = self.GetNodes(parent_node)
626 result = [(node, self) for node in my_nodes]
627 if not self.children:
630 for node in my_nodes:
631 for child in self.children:
632 child_result = child.ComputeNodeTree(node)
633 if len(child_result) == 1:
634 # child (and all its descendants) is simple, doesn't split
635 # over multiple hosts, so we don't need to describe it, our
636 # own entry for this node describes it completely
639 # check if child nodes differ from my nodes; note that
640 # subdisk can differ from the child itself, and be instead
641 # one of its descendants
642 for subnode, subdisk in child_result:
643 if subnode not in my_nodes:
644 result.append((subnode, subdisk))
645 # otherwise child is under our own node, so we ignore this
646 # entry (but probably the other results in the list will
650 def ComputeGrowth(self, amount):
651 """Compute the per-VG growth requirements.
653 This only works for VG-based disks.
655 @type amount: integer
656 @param amount: the desired increase in (user-visible) disk space
658 @return: a dictionary of volume-groups and the required size
661 if self.dev_type == constants.LD_LV:
662 return {self.logical_id[0]: amount}
663 elif self.dev_type == constants.LD_DRBD8:
665 return self.children[0].ComputeGrowth(amount)
669 # Other disk types do not require VG space
672 def RecordGrow(self, amount):
673 """Update the size of this disk after growth.
675 This method recurses over the disks's children and updates their
676 size correspondigly. The method needs to be kept in sync with the
677 actual algorithms from bdev.
680 if self.dev_type in (constants.LD_LV, constants.LD_FILE,
681 constants.LD_RBD, constants.LD_EXT):
683 elif self.dev_type == constants.LD_DRBD8:
685 self.children[0].RecordGrow(amount)
688 raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
689 " disk type %s" % self.dev_type)
691 def Update(self, size=None, mode=None):
692 """Apply changes to size and mode.
695 if self.dev_type == constants.LD_DRBD8:
697 self.children[0].Update(size=size, mode=mode)
699 assert not self.children
707 """Sets recursively the size to zero for the disk and its children.
711 for child in self.children:
715 def SetPhysicalID(self, target_node, nodes_ip):
716 """Convert the logical ID to the physical ID.
718 This is used only for drbd, which needs ip/port configuration.
720 The routine descends down and updates its children also, because
721 this helps when the only the top device is passed to the remote
725 - target_node: the node we wish to configure for
726 - nodes_ip: a mapping of node name to ip
728 The target_node must exist in in nodes_ip, and must be one of the
729 nodes in the logical ID for each of the DRBD devices encountered
734 for child in self.children:
735 child.SetPhysicalID(target_node, nodes_ip)
737 if self.logical_id is None and self.physical_id is not None:
739 if self.dev_type in constants.LDS_DRBD:
740 pnode, snode, port, pminor, sminor, secret = self.logical_id
741 if target_node not in (pnode, snode):
742 raise errors.ConfigurationError("DRBD device not knowing node %s" %
744 pnode_ip = nodes_ip.get(pnode, None)
745 snode_ip = nodes_ip.get(snode, None)
746 if pnode_ip is None or snode_ip is None:
747 raise errors.ConfigurationError("Can't find primary or secondary node"
748 " for %s" % str(self))
749 p_data = (pnode_ip, port)
750 s_data = (snode_ip, port)
751 if pnode == target_node:
752 self.physical_id = p_data + s_data + (pminor, secret)
753 else: # it must be secondary, we tested above
754 self.physical_id = s_data + p_data + (sminor, secret)
756 self.physical_id = self.logical_id
760 """Disk-specific conversion to standard python types.
762 This replaces the children lists of objects with lists of
763 standard python types.
766 bo = super(Disk, self).ToDict()
768 for attr in ("children",):
769 alist = bo.get(attr, None)
771 bo[attr] = self._ContainerToDicts(alist)
775 def FromDict(cls, val):
776 """Custom function for Disks
779 obj = super(Disk, cls).FromDict(val)
781 obj.children = cls._ContainerFromDicts(obj.children, list, Disk)
782 if obj.logical_id and isinstance(obj.logical_id, list):
783 obj.logical_id = tuple(obj.logical_id)
784 if obj.physical_id and isinstance(obj.physical_id, list):
785 obj.physical_id = tuple(obj.physical_id)
786 if obj.dev_type in constants.LDS_DRBD:
787 # we need a tuple of length six here
788 if len(obj.logical_id) < 6:
789 obj.logical_id += (None,) * (6 - len(obj.logical_id))
793 """Custom str() formatter for disks.
796 if self.dev_type == constants.LD_LV:
797 val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
798 elif self.dev_type in constants.LDS_DRBD:
799 node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
801 if self.physical_id is None:
804 phy = ("configured as %s:%s %s:%s" %
805 (self.physical_id[0], self.physical_id[1],
806 self.physical_id[2], self.physical_id[3]))
808 val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
809 (node_a, minor_a, node_b, minor_b, port, phy))
810 if self.children and self.children.count(None) == 0:
811 val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
813 val += "no local storage"
815 val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
816 (self.dev_type, self.logical_id, self.physical_id, self.children))
817 if self.iv_name is None:
818 val += ", not visible"
820 val += ", visible as /dev/%s" % self.iv_name
821 if isinstance(self.size, int):
822 val += ", size=%dm)>" % self.size
824 val += ", size='%s')>" % (self.size,)
828 """Checks that this disk is correctly configured.
832 if self.mode not in constants.DISK_ACCESS_SET:
833 all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
836 def UpgradeConfig(self):
837 """Fill defaults for missing configuration values.
841 for child in self.children:
842 child.UpgradeConfig()
844 # FIXME: Make this configurable in Ganeti 2.7
846 # add here config upgrade for this disk
849 def ComputeLDParams(disk_template, disk_params):
850 """Computes Logical Disk parameters from Disk Template parameters.
852 @type disk_template: string
853 @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
854 @type disk_params: dict
855 @param disk_params: disk template parameters;
856 dict(template_name -> parameters
858 @return: a list of dicts, one for each node of the disk hierarchy. Each dict
859 contains the LD parameters of the node. The tree is flattened in-order.
862 if disk_template not in constants.DISK_TEMPLATES:
863 raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
865 assert disk_template in disk_params
868 dt_params = disk_params[disk_template]
869 if disk_template == constants.DT_DRBD8:
870 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8], {
871 constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
872 constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
873 constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
874 constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
875 constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
876 constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
877 constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
878 constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
879 constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
880 constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
881 constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
882 constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
886 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
887 constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
891 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
892 constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
895 elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
896 result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
898 elif disk_template == constants.DT_PLAIN:
899 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
900 constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
903 elif disk_template == constants.DT_BLOCK:
904 result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
906 elif disk_template == constants.DT_RBD:
907 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD], {
908 constants.LDP_POOL: dt_params[constants.RBD_POOL],
911 elif disk_template == constants.DT_EXT:
912 result.append(constants.DISK_LD_DEFAULTS[constants.LD_EXT])
917 class InstancePolicy(ConfigObject):
918 """Config object representing instance policy limits dictionary.
921 Note that this object is not actually used in the config, it's just
922 used as a placeholder for a few functions.
926 def CheckParameterSyntax(cls, ipolicy, check_std):
927 """ Check the instance policy for validity.
930 for param in constants.ISPECS_PARAMETERS:
931 InstancePolicy.CheckISpecSyntax(ipolicy, param, check_std)
932 if constants.IPOLICY_DTS in ipolicy:
933 InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
934 for key in constants.IPOLICY_PARAMETERS:
936 InstancePolicy.CheckParameter(key, ipolicy[key])
937 wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
939 raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
940 utils.CommaJoin(wrong_keys))
943 def CheckISpecSyntax(cls, ipolicy, name, check_std):
944 """Check the instance policy for validity on a given key.
946 We check if the instance policy makes sense for a given key, that is
947 if ipolicy[min][name] <= ipolicy[std][name] <= ipolicy[max][name].
950 @param ipolicy: dictionary with min, max, std specs
952 @param name: what are the limits for
953 @type check_std: bool
954 @param check_std: Whether to check std value or just assume compliance
955 @raise errors.ConfigureError: when specs for given name are not valid
958 min_v = ipolicy[constants.ISPECS_MIN].get(name, 0)
961 std_v = ipolicy[constants.ISPECS_STD].get(name, min_v)
967 max_v = ipolicy[constants.ISPECS_MAX].get(name, std_v)
968 err = ("Invalid specification of min/max/std values for %s: %s/%s/%s" %
970 ipolicy[constants.ISPECS_MIN].get(name, "-"),
971 ipolicy[constants.ISPECS_MAX].get(name, "-"),
973 if min_v > std_v or std_v > max_v:
974 raise errors.ConfigurationError(err)
977 def CheckDiskTemplates(cls, disk_templates):
978 """Checks the disk templates for validity.
981 wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
983 raise errors.ConfigurationError("Invalid disk template(s) %s" %
984 utils.CommaJoin(wrong))
987 def CheckParameter(cls, key, value):
988 """Checks a parameter.
990 Currently we expect all parameters to be float values.
995 except (TypeError, ValueError), err:
996 raise errors.ConfigurationError("Invalid value for key" " '%s':"
997 " '%s', error: %s" % (key, value, err))
1000 class Instance(TaggableObject):
1001 """Config object representing an instance."""
1016 ] + _TIMESTAMPS + _UUID
1018 def _ComputeSecondaryNodes(self):
1019 """Compute the list of secondary nodes.
1021 This is a simple wrapper over _ComputeAllNodes.
1024 all_nodes = set(self._ComputeAllNodes())
1025 all_nodes.discard(self.primary_node)
1026 return tuple(all_nodes)
1028 secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1029 "List of names of secondary nodes")
1031 def _ComputeAllNodes(self):
1032 """Compute the list of all nodes.
1034 Since the data is already there (in the drbd disks), keeping it as
1035 a separate normal attribute is redundant and if not properly
1036 synchronised can cause problems. Thus it's better to compute it
1040 def _Helper(nodes, device):
1041 """Recursively computes nodes given a top device."""
1042 if device.dev_type in constants.LDS_DRBD:
1043 nodea, nodeb = device.logical_id[:2]
1047 for child in device.children:
1048 _Helper(nodes, child)
1051 all_nodes.add(self.primary_node)
1052 for device in self.disks:
1053 _Helper(all_nodes, device)
1054 return tuple(all_nodes)
1056 all_nodes = property(_ComputeAllNodes, None, None,
1057 "List of names of all the nodes of the instance")
1059 def MapLVsByNode(self, lvmap=None, devs=None, node=None):
1060 """Provide a mapping of nodes to LVs this instance owns.
1062 This function figures out what logical volumes should belong on
1063 which nodes, recursing through a device tree.
1065 @param lvmap: optional dictionary to receive the
1066 'node' : ['lv', ...] data.
1068 @return: None if lvmap arg is given, otherwise, a dictionary of
1069 the form { 'nodename' : ['volume1', 'volume2', ...], ... };
1070 volumeN is of the form "vg_name/lv_name", compatible with
1075 node = self.primary_node
1083 if not node in lvmap:
1091 if dev.dev_type == constants.LD_LV:
1092 lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1094 elif dev.dev_type in constants.LDS_DRBD:
1096 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1097 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1100 self.MapLVsByNode(lvmap, dev.children, node)
1104 def FindDisk(self, idx):
1105 """Find a disk given having a specified index.
1107 This is just a wrapper that does validation of the index.
1110 @param idx: the disk index
1112 @return: the corresponding disk
1113 @raise errors.OpPrereqError: when the given index is not valid
1118 return self.disks[idx]
1119 except (TypeError, ValueError), err:
1120 raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1123 raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1124 " 0 to %d" % (idx, len(self.disks) - 1),
1128 """Instance-specific conversion to standard python types.
1130 This replaces the children lists of objects with lists of standard
1134 bo = super(Instance, self).ToDict()
1136 for attr in "nics", "disks":
1137 alist = bo.get(attr, None)
1139 nlist = self._ContainerToDicts(alist)
1146 def FromDict(cls, val):
1147 """Custom function for instances.
1150 if "admin_state" not in val:
1151 if val.get("admin_up", False):
1152 val["admin_state"] = constants.ADMINST_UP
1154 val["admin_state"] = constants.ADMINST_DOWN
1155 if "admin_up" in val:
1157 obj = super(Instance, cls).FromDict(val)
1158 obj.nics = cls._ContainerFromDicts(obj.nics, list, NIC)
1159 obj.disks = cls._ContainerFromDicts(obj.disks, list, Disk)
1162 def UpgradeConfig(self):
1163 """Fill defaults for missing configuration values.
1166 for nic in self.nics:
1168 for disk in self.disks:
1169 disk.UpgradeConfig()
1171 for key in constants.HVC_GLOBALS:
1173 del self.hvparams[key]
1176 if self.osparams is None:
1178 UpgradeBeParams(self.beparams)
1181 class OS(ConfigObject):
1182 """Config object representing an operating system.
1184 @type supported_parameters: list
1185 @ivar supported_parameters: a list of tuples, name and description,
1186 containing the supported parameters by this OS
1188 @type VARIANT_DELIM: string
1189 @cvar VARIANT_DELIM: the variant delimiter
1201 "supported_variants",
1202 "supported_parameters",
1208 def SplitNameVariant(cls, name):
1209 """Splits the name into the proper name and variant.
1211 @param name: the OS (unprocessed) name
1213 @return: a list of two elements; if the original name didn't
1214 contain a variant, it's returned as an empty string
1217 nv = name.split(cls.VARIANT_DELIM, 1)
1223 def GetName(cls, name):
1224 """Returns the proper name of the os (without the variant).
1226 @param name: the OS (unprocessed) name
1229 return cls.SplitNameVariant(name)[0]
1232 def GetVariant(cls, name):
1233 """Returns the variant the os (without the base name).
1235 @param name: the OS (unprocessed) name
1238 return cls.SplitNameVariant(name)[1]
1241 class ExtStorage(ConfigObject):
1242 """Config object representing an External Storage Provider.
1255 "supported_parameters",
1259 class NodeHvState(ConfigObject):
1260 """Hypvervisor state on a node.
1262 @ivar mem_total: Total amount of memory
1263 @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1265 @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1267 @ivar mem_inst: Memory used by instances living on node
1268 @ivar cpu_total: Total node CPU core count
1269 @ivar cpu_node: Number of CPU cores reserved for the node itself
1282 class NodeDiskState(ConfigObject):
1283 """Disk state on a node.
1293 class Node(TaggableObject):
1294 """Config object representing a node.
1296 @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1297 @ivar hv_state_static: Hypervisor state overriden by user
1298 @ivar disk_state: Disk state (e.g. free space)
1299 @ivar disk_state_static: Disk state overriden by user
1318 "disk_state_static",
1319 ] + _TIMESTAMPS + _UUID
1321 def UpgradeConfig(self):
1322 """Fill defaults for missing configuration values.
1325 # pylint: disable=E0203
1326 # because these are "defined" via slots, not manually
1327 if self.master_capable is None:
1328 self.master_capable = True
1330 if self.vm_capable is None:
1331 self.vm_capable = True
1333 if self.ndparams is None:
1336 if self.powered is None:
1340 """Custom function for serializing.
1343 data = super(Node, self).ToDict()
1345 hv_state = data.get("hv_state", None)
1346 if hv_state is not None:
1347 data["hv_state"] = self._ContainerToDicts(hv_state)
1349 disk_state = data.get("disk_state", None)
1350 if disk_state is not None:
1351 data["disk_state"] = \
1352 dict((key, self._ContainerToDicts(value))
1353 for (key, value) in disk_state.items())
1358 def FromDict(cls, val):
1359 """Custom function for deserializing.
1362 obj = super(Node, cls).FromDict(val)
1364 if obj.hv_state is not None:
1365 obj.hv_state = cls._ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1367 if obj.disk_state is not None:
1369 dict((key, cls._ContainerFromDicts(value, dict, NodeDiskState))
1370 for (key, value) in obj.disk_state.items())
1375 class NodeGroup(TaggableObject):
1376 """Config object representing a node group."""
1385 "disk_state_static",
1388 ] + _TIMESTAMPS + _UUID
1391 """Custom function for nodegroup.
1393 This discards the members object, which gets recalculated and is only kept
1397 mydict = super(NodeGroup, self).ToDict()
1398 del mydict["members"]
1402 def FromDict(cls, val):
1403 """Custom function for nodegroup.
1405 The members slot is initialized to an empty list, upon deserialization.
1408 obj = super(NodeGroup, cls).FromDict(val)
1412 def UpgradeConfig(self):
1413 """Fill defaults for missing configuration values.
1416 if self.ndparams is None:
1419 if self.serial_no is None:
1422 if self.alloc_policy is None:
1423 self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1425 # We only update mtime, and not ctime, since we would not be able
1426 # to provide a correct value for creation time.
1427 if self.mtime is None:
1428 self.mtime = time.time()
1430 if self.diskparams is None:
1431 self.diskparams = {}
1432 if self.ipolicy is None:
1433 self.ipolicy = MakeEmptyIPolicy()
1435 if self.networks is None:
1438 def FillND(self, node):
1439 """Return filled out ndparams for L{objects.Node}
1441 @type node: L{objects.Node}
1442 @param node: A Node object to fill
1443 @return a copy of the node's ndparams with defaults filled
1446 return self.SimpleFillND(node.ndparams)
1448 def SimpleFillND(self, ndparams):
1449 """Fill a given ndparams dict with defaults.
1451 @type ndparams: dict
1452 @param ndparams: the dict to fill
1454 @return: a copy of the passed in ndparams with missing keys filled
1455 from the node group defaults
1458 return FillDict(self.ndparams, ndparams)
1461 class Cluster(TaggableObject):
1462 """Config object representing the cluster."""
1466 "highest_used_port",
1469 "volume_group_name",
1471 "drbd_usermode_helper",
1473 "default_hypervisor",
1478 "use_external_mip_script",
1481 "shared_file_storage_dir",
1482 "enabled_hypervisors",
1491 "candidate_pool_size",
1494 "maintain_node_health",
1496 "default_iallocator",
1499 "primary_ip_family",
1500 "prealloc_wipe_disks",
1502 "disk_state_static",
1503 ] + _TIMESTAMPS + _UUID
1505 def UpgradeConfig(self):
1506 """Fill defaults for missing configuration values.
1509 # pylint: disable=E0203
1510 # because these are "defined" via slots, not manually
1511 if self.hvparams is None:
1512 self.hvparams = constants.HVC_DEFAULTS
1514 for hypervisor in self.hvparams:
1515 self.hvparams[hypervisor] = FillDict(
1516 constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1518 if self.os_hvp is None:
1521 # osparams added before 2.2
1522 if self.osparams is None:
1525 self.ndparams = UpgradeNDParams(self.ndparams)
1527 self.beparams = UpgradeGroupedParams(self.beparams,
1528 constants.BEC_DEFAULTS)
1529 for beparams_group in self.beparams:
1530 UpgradeBeParams(self.beparams[beparams_group])
1532 migrate_default_bridge = not self.nicparams
1533 self.nicparams = UpgradeGroupedParams(self.nicparams,
1534 constants.NICC_DEFAULTS)
1535 if migrate_default_bridge:
1536 self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1539 if self.modify_etc_hosts is None:
1540 self.modify_etc_hosts = True
1542 if self.modify_ssh_setup is None:
1543 self.modify_ssh_setup = True
1545 # default_bridge is no longer used in 2.1. The slot is left there to
1546 # support auto-upgrading. It can be removed once we decide to deprecate
1547 # upgrading straight from 2.0.
1548 if self.default_bridge is not None:
1549 self.default_bridge = None
1551 # default_hypervisor is just the first enabled one in 2.1. This slot and
1552 # code can be removed once upgrading straight from 2.0 is deprecated.
1553 if self.default_hypervisor is not None:
1554 self.enabled_hypervisors = ([self.default_hypervisor] +
1555 [hvname for hvname in self.enabled_hypervisors
1556 if hvname != self.default_hypervisor])
1557 self.default_hypervisor = None
1559 # maintain_node_health added after 2.1.1
1560 if self.maintain_node_health is None:
1561 self.maintain_node_health = False
1563 if self.uid_pool is None:
1566 if self.default_iallocator is None:
1567 self.default_iallocator = ""
1569 # reserved_lvs added before 2.2
1570 if self.reserved_lvs is None:
1571 self.reserved_lvs = []
1573 # hidden and blacklisted operating systems added before 2.2.1
1574 if self.hidden_os is None:
1577 if self.blacklisted_os is None:
1578 self.blacklisted_os = []
1580 # primary_ip_family added before 2.3
1581 if self.primary_ip_family is None:
1582 self.primary_ip_family = AF_INET
1584 if self.master_netmask is None:
1585 ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1586 self.master_netmask = ipcls.iplen
1588 if self.prealloc_wipe_disks is None:
1589 self.prealloc_wipe_disks = False
1591 # shared_file_storage_dir added before 2.5
1592 if self.shared_file_storage_dir is None:
1593 self.shared_file_storage_dir = ""
1595 if self.use_external_mip_script is None:
1596 self.use_external_mip_script = False
1599 self.diskparams = UpgradeDiskParams(self.diskparams)
1601 self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1603 # instance policy added before 2.6
1604 if self.ipolicy is None:
1605 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1607 # we can either make sure to upgrade the ipolicy always, or only
1608 # do it in some corner cases (e.g. missing keys); note that this
1609 # will break any removal of keys from the ipolicy dict
1610 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1613 def primary_hypervisor(self):
1614 """The first hypervisor is the primary.
1616 Useful, for example, for L{Node}'s hv/disk state.
1619 return self.enabled_hypervisors[0]
1622 """Custom function for cluster.
1625 mydict = super(Cluster, self).ToDict()
1626 mydict["tcpudp_port_pool"] = list(self.tcpudp_port_pool)
1630 def FromDict(cls, val):
1631 """Custom function for cluster.
1634 obj = super(Cluster, cls).FromDict(val)
1635 if not isinstance(obj.tcpudp_port_pool, set):
1636 obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1639 def SimpleFillDP(self, diskparams):
1640 """Fill a given diskparams dict with cluster defaults.
1642 @param diskparams: The diskparams
1643 @return: The defaults dict
1646 return FillDiskParams(self.diskparams, diskparams)
1648 def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1649 """Get the default hypervisor parameters for the cluster.
1651 @param hypervisor: the hypervisor name
1652 @param os_name: if specified, we'll also update the defaults for this OS
1653 @param skip_keys: if passed, list of keys not to use
1654 @return: the defaults dict
1657 if skip_keys is None:
1660 fill_stack = [self.hvparams.get(hypervisor, {})]
1661 if os_name is not None:
1662 os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1663 fill_stack.append(os_hvp)
1666 for o_dict in fill_stack:
1667 ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1671 def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1672 """Fill a given hvparams dict with cluster defaults.
1674 @type hv_name: string
1675 @param hv_name: the hypervisor to use
1676 @type os_name: string
1677 @param os_name: the OS to use for overriding the hypervisor defaults
1678 @type skip_globals: boolean
1679 @param skip_globals: if True, the global hypervisor parameters will
1682 @return: a copy of the given hvparams with missing keys filled from
1683 the cluster defaults
1687 skip_keys = constants.HVC_GLOBALS
1691 def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1692 return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1694 def FillHV(self, instance, skip_globals=False):
1695 """Fill an instance's hvparams dict with cluster defaults.
1697 @type instance: L{objects.Instance}
1698 @param instance: the instance parameter to fill
1699 @type skip_globals: boolean
1700 @param skip_globals: if True, the global hypervisor parameters will
1703 @return: a copy of the instance's hvparams with missing keys filled from
1704 the cluster defaults
1707 return self.SimpleFillHV(instance.hypervisor, instance.os,
1708 instance.hvparams, skip_globals)
1710 def SimpleFillBE(self, beparams):
1711 """Fill a given beparams dict with cluster defaults.
1713 @type beparams: dict
1714 @param beparams: the dict to fill
1716 @return: a copy of the passed in beparams with missing keys filled
1717 from the cluster defaults
1720 return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1722 def FillBE(self, instance):
1723 """Fill an instance's beparams dict with cluster defaults.
1725 @type instance: L{objects.Instance}
1726 @param instance: the instance parameter to fill
1728 @return: a copy of the instance's beparams with missing keys filled from
1729 the cluster defaults
1732 return self.SimpleFillBE(instance.beparams)
1734 def SimpleFillNIC(self, nicparams):
1735 """Fill a given nicparams dict with cluster defaults.
1737 @type nicparams: dict
1738 @param nicparams: the dict to fill
1740 @return: a copy of the passed in nicparams with missing keys filled
1741 from the cluster defaults
1744 return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1746 def SimpleFillOS(self, os_name, os_params):
1747 """Fill an instance's osparams dict with cluster defaults.
1749 @type os_name: string
1750 @param os_name: the OS name to use
1751 @type os_params: dict
1752 @param os_params: the dict to fill with default values
1754 @return: a copy of the instance's osparams with missing keys filled from
1755 the cluster defaults
1758 name_only = os_name.split("+", 1)[0]
1760 result = self.osparams.get(name_only, {})
1762 result = FillDict(result, self.osparams.get(os_name, {}))
1764 return FillDict(result, os_params)
1767 def SimpleFillHvState(hv_state):
1768 """Fill an hv_state sub dict with cluster defaults.
1771 return FillDict(constants.HVST_DEFAULTS, hv_state)
1774 def SimpleFillDiskState(disk_state):
1775 """Fill an disk_state sub dict with cluster defaults.
1778 return FillDict(constants.DS_DEFAULTS, disk_state)
1780 def FillND(self, node, nodegroup):
1781 """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1783 @type node: L{objects.Node}
1784 @param node: A Node object to fill
1785 @type nodegroup: L{objects.NodeGroup}
1786 @param nodegroup: A Node object to fill
1787 @return a copy of the node's ndparams with defaults filled
1790 return self.SimpleFillND(nodegroup.FillND(node))
1792 def SimpleFillND(self, ndparams):
1793 """Fill a given ndparams dict with defaults.
1795 @type ndparams: dict
1796 @param ndparams: the dict to fill
1798 @return: a copy of the passed in ndparams with missing keys filled
1799 from the cluster defaults
1802 return FillDict(self.ndparams, ndparams)
1804 def SimpleFillIPolicy(self, ipolicy):
1805 """ Fill instance policy dict with defaults.
1808 @param ipolicy: the dict to fill
1810 @return: a copy of passed ipolicy with missing keys filled from
1811 the cluster defaults
1814 return FillIPolicy(self.ipolicy, ipolicy)
1817 class BlockDevStatus(ConfigObject):
1818 """Config object representing the status of a block device."""
1830 class ImportExportStatus(ConfigObject):
1831 """Config object representing the status of an import or export."""
1837 "progress_throughput",
1845 class ImportExportOptions(ConfigObject):
1846 """Options for import/export daemon
1848 @ivar key_name: X509 key name (None for cluster certificate)
1849 @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1850 @ivar compress: Compression method (one of L{constants.IEC_ALL})
1851 @ivar magic: Used to ensure the connection goes to the right disk
1852 @ivar ipv6: Whether to use IPv6
1853 @ivar connect_timeout: Number of seconds for establishing connection
1866 class ConfdRequest(ConfigObject):
1867 """Object holding a confd request.
1869 @ivar protocol: confd protocol version
1870 @ivar type: confd query type
1871 @ivar query: query request
1872 @ivar rsalt: requested reply salt
1883 class ConfdReply(ConfigObject):
1884 """Object holding a confd reply.
1886 @ivar protocol: confd protocol version
1887 @ivar status: reply status code (ok, error)
1888 @ivar answer: confd query reply
1889 @ivar serial: configuration serial number
1900 class QueryFieldDefinition(ConfigObject):
1901 """Object holding a query field definition.
1903 @ivar name: Field name
1904 @ivar title: Human-readable title
1905 @ivar kind: Field type
1906 @ivar doc: Human-readable description
1917 class _QueryResponseBase(ConfigObject):
1923 """Custom function for serializing.
1926 mydict = super(_QueryResponseBase, self).ToDict()
1927 mydict["fields"] = self._ContainerToDicts(mydict["fields"])
1931 def FromDict(cls, val):
1932 """Custom function for de-serializing.
1935 obj = super(_QueryResponseBase, cls).FromDict(val)
1936 obj.fields = cls._ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
1940 class QueryResponse(_QueryResponseBase):
1941 """Object holding the response to a query.
1943 @ivar fields: List of L{QueryFieldDefinition} objects
1944 @ivar data: Requested data
1952 class QueryFieldsRequest(ConfigObject):
1953 """Object holding a request for querying available fields.
1962 class QueryFieldsResponse(_QueryResponseBase):
1963 """Object holding the response to a query for fields.
1965 @ivar fields: List of L{QueryFieldDefinition} objects
1971 class MigrationStatus(ConfigObject):
1972 """Object holding the status of a migration.
1982 class InstanceConsole(ConfigObject):
1983 """Object describing how to access the console of an instance.
1998 """Validates contents of this object.
2001 assert self.kind in constants.CONS_ALL, "Unknown console type"
2002 assert self.instance, "Missing instance name"
2003 assert self.message or self.kind in [constants.CONS_SSH,
2004 constants.CONS_SPICE,
2006 assert self.host or self.kind == constants.CONS_MESSAGE
2007 assert self.port or self.kind in [constants.CONS_MESSAGE,
2009 assert self.user or self.kind in [constants.CONS_MESSAGE,
2010 constants.CONS_SPICE,
2012 assert self.command or self.kind in [constants.CONS_MESSAGE,
2013 constants.CONS_SPICE,
2015 assert self.display or self.kind in [constants.CONS_MESSAGE,
2016 constants.CONS_SPICE,
2021 class Network(TaggableObject):
2022 """Object representing a network definition for ganeti.
2038 ] + _TIMESTAMPS + _UUID
2041 class SerializableConfigParser(ConfigParser.SafeConfigParser):
2042 """Simple wrapper over ConfigParse that allows serialization.
2044 This class is basically ConfigParser.SafeConfigParser with two
2045 additional methods that allow it to serialize/unserialize to/from a
2050 """Dump this instance and return the string representation."""
2053 return buf.getvalue()
2056 def Loads(cls, data):
2057 """Load data from a string."""
2058 buf = StringIO(data)
2064 class LvmPvInfo(ConfigObject):
2065 """Information about an LVM physical volume (PV).
2068 @ivar name: name of the PV
2069 @type vg_name: string
2070 @ivar vg_name: name of the volume group containing the PV
2072 @ivar size: size of the PV in MiB
2074 @ivar free: free space in the PV, in MiB
2075 @type attributes: string
2076 @ivar attributes: PV attributes
2077 @type lv_list: list of strings
2078 @ivar lv_list: names of the LVs hosted on the PV
2090 """Is this PV empty?
2093 return self.size <= (self.free + 1)
2095 def IsAllocatable(self):
2096 """Is this PV allocatable?
2099 return ("a" in self.attributes)