4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 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
43 from cStringIO import StringIO
45 from ganeti import errors
46 from ganeti import constants
47 from ganeti import netutils
48 from ganeti import outils
49 from ganeti import utils
51 from socket import AF_INET
54 __all__ = ["ConfigObject", "ConfigData", "NIC", "Disk", "Instance",
55 "OS", "Node", "NodeGroup", "Cluster", "FillDict", "Network"]
57 _TIMESTAMPS = ["ctime", "mtime"]
61 def FillDict(defaults_dict, custom_dict, skip_keys=None):
62 """Basic function to apply settings on top a default dict.
64 @type defaults_dict: dict
65 @param defaults_dict: dictionary holding the default values
66 @type custom_dict: dict
67 @param custom_dict: dictionary holding customized value
69 @param skip_keys: which keys not to fill
71 @return: dict with the 'full' values
74 ret_dict = copy.deepcopy(defaults_dict)
75 ret_dict.update(custom_dict)
85 def FillIPolicy(default_ipolicy, custom_ipolicy, skip_keys=None):
86 """Fills an instance policy with defaults.
89 assert frozenset(default_ipolicy.keys()) == constants.IPOLICY_ALL_KEYS
91 for key in constants.IPOLICY_ISPECS:
92 ret_dict[key] = FillDict(default_ipolicy[key],
93 custom_ipolicy.get(key, {}),
96 for key in [constants.IPOLICY_DTS]:
97 ret_dict[key] = list(custom_ipolicy.get(key, default_ipolicy[key]))
98 # other items which we know we can directly copy (immutables)
99 for key in constants.IPOLICY_PARAMETERS:
100 ret_dict[key] = custom_ipolicy.get(key, default_ipolicy[key])
105 def FillDiskParams(default_dparams, custom_dparams, skip_keys=None):
106 """Fills the disk parameter defaults.
108 @see: L{FillDict} for parameters and return value
111 assert frozenset(default_dparams.keys()) == constants.DISK_TEMPLATES
113 return dict((dt, FillDict(default_dparams[dt], custom_dparams.get(dt, {}),
114 skip_keys=skip_keys))
115 for dt in constants.DISK_TEMPLATES)
118 def UpgradeGroupedParams(target, defaults):
119 """Update all groups for the target parameter.
121 @type target: dict of dicts
122 @param target: {group: {parameter: value}}
124 @param defaults: default parameter values
128 target = {constants.PP_DEFAULT: defaults}
131 target[group] = FillDict(defaults, target[group])
135 def UpgradeBeParams(target):
136 """Update the be parameters dict to the new format.
139 @param target: "be" parameters dict
142 if constants.BE_MEMORY in target:
143 memory = target[constants.BE_MEMORY]
144 target[constants.BE_MAXMEM] = memory
145 target[constants.BE_MINMEM] = memory
146 del target[constants.BE_MEMORY]
149 def UpgradeDiskParams(diskparams):
150 """Upgrade the disk parameters.
152 @type diskparams: dict
153 @param diskparams: disk parameters to upgrade
155 @return: the upgraded disk parameters dict
161 result = FillDiskParams(constants.DISK_DT_DEFAULTS, diskparams)
166 def UpgradeNDParams(ndparams):
167 """Upgrade ndparams structure.
170 @param ndparams: disk parameters to upgrade
172 @return: the upgraded node parameters dict
178 if (constants.ND_OOB_PROGRAM in ndparams and
179 ndparams[constants.ND_OOB_PROGRAM] is None):
180 # will be reset by the line below
181 del ndparams[constants.ND_OOB_PROGRAM]
182 return FillDict(constants.NDC_DEFAULTS, ndparams)
185 def MakeEmptyIPolicy():
186 """Create empty IPolicy dictionary.
190 (constants.ISPECS_MIN, {}),
191 (constants.ISPECS_MAX, {}),
192 (constants.ISPECS_STD, {}),
196 class ConfigObject(outils.ValidatedSlots):
197 """A generic config object.
199 It has the following properties:
201 - provides somewhat safe recursive unpickling and pickling for its classes
202 - unset attributes which are defined in slots are always returned
203 as None instead of raising an error
205 Classes derived from this must always declare __slots__ (we use many
206 config objects and the memory reduction is useful)
211 def __getattr__(self, name):
212 if name not in self.GetAllSlots():
213 raise AttributeError("Invalid object attribute %s.%s" %
214 (type(self).__name__, name))
217 def __setstate__(self, state):
218 slots = self.GetAllSlots()
221 setattr(self, name, state[name])
224 """Validates the slots.
229 """Convert to a dict holding only standard python types.
231 The generic routine just dumps all of this object's attributes in
232 a dict. It does not work if the class has children who are
233 ConfigObjects themselves (e.g. the nics list in an Instance), in
234 which case the object should subclass the function in order to
235 make sure all objects returned are only standard python types.
239 for name in self.GetAllSlots():
240 value = getattr(self, name, None)
241 if value is not None:
245 __getstate__ = ToDict
248 def FromDict(cls, val):
249 """Create an object from a dictionary.
251 This generic routine takes a dict, instantiates a new instance of
252 the given class, and sets attributes based on the dict content.
254 As for `ToDict`, this does not work if the class has children
255 who are ConfigObjects themselves (e.g. the nics list in an
256 Instance), in which case the object should subclass the function
257 and alter the objects.
260 if not isinstance(val, dict):
261 raise errors.ConfigurationError("Invalid object passed to FromDict:"
262 " expected dict, got %s" % type(val))
263 val_str = dict([(str(k), v) for k, v in val.iteritems()])
264 obj = cls(**val_str) # pylint: disable=W0142
268 """Makes a deep copy of the current object and its children.
271 dict_form = self.ToDict()
272 clone_obj = self.__class__.FromDict(dict_form)
276 """Implement __repr__ for ConfigObjects."""
277 return repr(self.ToDict())
279 def UpgradeConfig(self):
280 """Fill defaults for missing configuration values.
282 This method will be called at configuration load time, and its
283 implementation will be object dependent.
289 class TaggableObject(ConfigObject):
290 """An generic class supporting tags.
294 VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
297 def ValidateTag(cls, tag):
298 """Check if a tag is valid.
300 If the tag is invalid, an errors.TagError will be raised. The
301 function has no return value.
304 if not isinstance(tag, basestring):
305 raise errors.TagError("Invalid tag type (not a string)")
306 if len(tag) > constants.MAX_TAG_LEN:
307 raise errors.TagError("Tag too long (>%d characters)" %
308 constants.MAX_TAG_LEN)
310 raise errors.TagError("Tags cannot be empty")
311 if not cls.VALID_TAG_RE.match(tag):
312 raise errors.TagError("Tag contains invalid characters")
315 """Return the tags list.
318 tags = getattr(self, "tags", None)
320 tags = self.tags = set()
323 def AddTag(self, tag):
327 self.ValidateTag(tag)
328 tags = self.GetTags()
329 if len(tags) >= constants.MAX_TAGS_PER_OBJ:
330 raise errors.TagError("Too many tags")
331 self.GetTags().add(tag)
333 def RemoveTag(self, tag):
337 self.ValidateTag(tag)
338 tags = self.GetTags()
342 raise errors.TagError("Tag not found")
345 """Taggable-object-specific conversion to standard python types.
347 This replaces the tags set with a list.
350 bo = super(TaggableObject, self).ToDict()
352 tags = bo.get("tags", None)
353 if isinstance(tags, set):
354 bo["tags"] = list(tags)
358 def FromDict(cls, val):
359 """Custom function for instances.
362 obj = super(TaggableObject, cls).FromDict(val)
363 if hasattr(obj, "tags") and isinstance(obj.tags, list):
364 obj.tags = set(obj.tags)
368 class MasterNetworkParameters(ConfigObject):
369 """Network configuration parameters for the master
371 @ivar name: master name
373 @ivar netmask: master netmask
374 @ivar netdev: master network device
375 @ivar ip_family: master IP family
387 class ConfigData(ConfigObject):
388 """Top-level config object."""
400 """Custom function for top-level config data.
402 This just replaces the list of instances, nodes and the cluster
403 with standard python types.
406 mydict = super(ConfigData, self).ToDict()
407 mydict["cluster"] = mydict["cluster"].ToDict()
408 for key in "nodes", "instances", "nodegroups", "networks":
409 mydict[key] = outils.ContainerToDicts(mydict[key])
414 def FromDict(cls, val):
415 """Custom function for top-level config data
418 obj = super(ConfigData, cls).FromDict(val)
419 obj.cluster = Cluster.FromDict(obj.cluster)
420 obj.nodes = outils.ContainerFromDicts(obj.nodes, dict, Node)
422 outils.ContainerFromDicts(obj.instances, dict, Instance)
424 outils.ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
425 obj.networks = outils.ContainerFromDicts(obj.networks, dict, Network)
428 def HasAnyDiskOfType(self, dev_type):
429 """Check if in there is at disk of the given type in the configuration.
431 @type dev_type: L{constants.LDS_BLOCK}
432 @param dev_type: the type to look for
434 @return: boolean indicating if a disk of the given type was found or not
437 for instance in self.instances.values():
438 for disk in instance.disks:
439 if disk.IsBasedOnDiskType(dev_type):
443 def UpgradeConfig(self):
444 """Fill defaults for missing configuration values.
447 self.cluster.UpgradeConfig()
448 for node in self.nodes.values():
450 for instance in self.instances.values():
451 instance.UpgradeConfig()
452 if self.nodegroups is None:
454 for nodegroup in self.nodegroups.values():
455 nodegroup.UpgradeConfig()
456 if self.cluster.drbd_usermode_helper is None:
457 # To decide if we set an helper let's check if at least one instance has
458 # a DRBD disk. This does not cover all the possible scenarios but it
459 # gives a good approximation.
460 if self.HasAnyDiskOfType(constants.LD_DRBD8):
461 self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
462 if self.networks is None:
464 for network in self.networks.values():
465 network.UpgradeConfig()
468 class NIC(ConfigObject):
469 """Config object representing a network card."""
470 __slots__ = ["mac", "ip", "network", "nicparams", "netinfo"]
473 def CheckParameterSyntax(cls, nicparams):
474 """Check the given parameters for validity.
476 @type nicparams: dict
477 @param nicparams: dictionary with parameter names/value
478 @raise errors.ConfigurationError: when a parameter is not valid
481 mode = nicparams[constants.NIC_MODE]
482 if (mode not in constants.NIC_VALID_MODES and
483 mode != constants.VALUE_AUTO):
484 raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
486 if (mode == constants.NIC_MODE_BRIDGED and
487 not nicparams[constants.NIC_LINK]):
488 raise errors.ConfigurationError("Missing bridged NIC link")
491 class Disk(ConfigObject):
492 """Config object representing a block device."""
493 __slots__ = ["dev_type", "logical_id", "physical_id",
494 "children", "iv_name", "size", "mode", "params"]
496 def CreateOnSecondary(self):
497 """Test if this device needs to be created on a secondary node."""
498 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
500 def AssembleOnSecondary(self):
501 """Test if this device needs to be assembled on a secondary node."""
502 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
504 def OpenOnSecondary(self):
505 """Test if this device needs to be opened on a secondary node."""
506 return self.dev_type in (constants.LD_LV,)
508 def StaticDevPath(self):
509 """Return the device path if this device type has a static one.
511 Some devices (LVM for example) live always at the same /dev/ path,
512 irrespective of their status. For such devices, we return this
513 path, for others we return None.
515 @warning: The path returned is not a normalized pathname; callers
516 should check that it is a valid path.
519 if self.dev_type == constants.LD_LV:
520 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
521 elif self.dev_type == constants.LD_BLOCKDEV:
522 return self.logical_id[1]
523 elif self.dev_type == constants.LD_RBD:
524 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
527 def ChildrenNeeded(self):
528 """Compute the needed number of children for activation.
530 This method will return either -1 (all children) or a positive
531 number denoting the minimum number of children needed for
532 activation (only mirrored devices will usually return >=0).
534 Currently, only DRBD8 supports diskless activation (therefore we
535 return 0), for all other we keep the previous semantics and return
539 if self.dev_type == constants.LD_DRBD8:
543 def IsBasedOnDiskType(self, dev_type):
544 """Check if the disk or its children are based on the given type.
546 @type dev_type: L{constants.LDS_BLOCK}
547 @param dev_type: the type to look for
549 @return: boolean indicating if a device of the given type was found or not
553 for child in self.children:
554 if child.IsBasedOnDiskType(dev_type):
556 return self.dev_type == dev_type
558 def GetNodes(self, node):
559 """This function returns the nodes this device lives on.
561 Given the node on which the parent of the device lives on (or, in
562 case of a top-level device, the primary node of the devices'
563 instance), this function will return a list of nodes on which this
564 devices needs to (or can) be assembled.
567 if self.dev_type in [constants.LD_LV, constants.LD_FILE,
568 constants.LD_BLOCKDEV, constants.LD_RBD,
571 elif self.dev_type in constants.LDS_DRBD:
572 result = [self.logical_id[0], self.logical_id[1]]
573 if node not in result:
574 raise errors.ConfigurationError("DRBD device passed unknown node")
576 raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
579 def ComputeNodeTree(self, parent_node):
580 """Compute the node/disk tree for this disk and its children.
582 This method, given the node on which the parent disk lives, will
583 return the list of all (node, disk) pairs which describe the disk
584 tree in the most compact way. For example, a drbd/lvm stack
585 will be returned as (primary_node, drbd) and (secondary_node, drbd)
586 which represents all the top-level devices on the nodes.
589 my_nodes = self.GetNodes(parent_node)
590 result = [(node, self) for node in my_nodes]
591 if not self.children:
594 for node in my_nodes:
595 for child in self.children:
596 child_result = child.ComputeNodeTree(node)
597 if len(child_result) == 1:
598 # child (and all its descendants) is simple, doesn't split
599 # over multiple hosts, so we don't need to describe it, our
600 # own entry for this node describes it completely
603 # check if child nodes differ from my nodes; note that
604 # subdisk can differ from the child itself, and be instead
605 # one of its descendants
606 for subnode, subdisk in child_result:
607 if subnode not in my_nodes:
608 result.append((subnode, subdisk))
609 # otherwise child is under our own node, so we ignore this
610 # entry (but probably the other results in the list will
614 def ComputeGrowth(self, amount):
615 """Compute the per-VG growth requirements.
617 This only works for VG-based disks.
619 @type amount: integer
620 @param amount: the desired increase in (user-visible) disk space
622 @return: a dictionary of volume-groups and the required size
625 if self.dev_type == constants.LD_LV:
626 return {self.logical_id[0]: amount}
627 elif self.dev_type == constants.LD_DRBD8:
629 return self.children[0].ComputeGrowth(amount)
633 # Other disk types do not require VG space
636 def RecordGrow(self, amount):
637 """Update the size of this disk after growth.
639 This method recurses over the disks's children and updates their
640 size correspondigly. The method needs to be kept in sync with the
641 actual algorithms from bdev.
644 if self.dev_type in (constants.LD_LV, constants.LD_FILE,
645 constants.LD_RBD, constants.LD_EXT):
647 elif self.dev_type == constants.LD_DRBD8:
649 self.children[0].RecordGrow(amount)
652 raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
653 " disk type %s" % self.dev_type)
655 def Update(self, size=None, mode=None):
656 """Apply changes to size and mode.
659 if self.dev_type == constants.LD_DRBD8:
661 self.children[0].Update(size=size, mode=mode)
663 assert not self.children
671 """Sets recursively the size to zero for the disk and its children.
675 for child in self.children:
679 def SetPhysicalID(self, target_node, nodes_ip):
680 """Convert the logical ID to the physical ID.
682 This is used only for drbd, which needs ip/port configuration.
684 The routine descends down and updates its children also, because
685 this helps when the only the top device is passed to the remote
689 - target_node: the node we wish to configure for
690 - nodes_ip: a mapping of node name to ip
692 The target_node must exist in in nodes_ip, and must be one of the
693 nodes in the logical ID for each of the DRBD devices encountered
698 for child in self.children:
699 child.SetPhysicalID(target_node, nodes_ip)
701 if self.logical_id is None and self.physical_id is not None:
703 if self.dev_type in constants.LDS_DRBD:
704 pnode, snode, port, pminor, sminor, secret = self.logical_id
705 if target_node not in (pnode, snode):
706 raise errors.ConfigurationError("DRBD device not knowing node %s" %
708 pnode_ip = nodes_ip.get(pnode, None)
709 snode_ip = nodes_ip.get(snode, None)
710 if pnode_ip is None or snode_ip is None:
711 raise errors.ConfigurationError("Can't find primary or secondary node"
712 " for %s" % str(self))
713 p_data = (pnode_ip, port)
714 s_data = (snode_ip, port)
715 if pnode == target_node:
716 self.physical_id = p_data + s_data + (pminor, secret)
717 else: # it must be secondary, we tested above
718 self.physical_id = s_data + p_data + (sminor, secret)
720 self.physical_id = self.logical_id
724 """Disk-specific conversion to standard python types.
726 This replaces the children lists of objects with lists of
727 standard python types.
730 bo = super(Disk, self).ToDict()
732 for attr in ("children",):
733 alist = bo.get(attr, None)
735 bo[attr] = outils.ContainerToDicts(alist)
739 def FromDict(cls, val):
740 """Custom function for Disks
743 obj = super(Disk, cls).FromDict(val)
745 obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
746 if obj.logical_id and isinstance(obj.logical_id, list):
747 obj.logical_id = tuple(obj.logical_id)
748 if obj.physical_id and isinstance(obj.physical_id, list):
749 obj.physical_id = tuple(obj.physical_id)
750 if obj.dev_type in constants.LDS_DRBD:
751 # we need a tuple of length six here
752 if len(obj.logical_id) < 6:
753 obj.logical_id += (None,) * (6 - len(obj.logical_id))
757 """Custom str() formatter for disks.
760 if self.dev_type == constants.LD_LV:
761 val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
762 elif self.dev_type in constants.LDS_DRBD:
763 node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
765 if self.physical_id is None:
768 phy = ("configured as %s:%s %s:%s" %
769 (self.physical_id[0], self.physical_id[1],
770 self.physical_id[2], self.physical_id[3]))
772 val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
773 (node_a, minor_a, node_b, minor_b, port, phy))
774 if self.children and self.children.count(None) == 0:
775 val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
777 val += "no local storage"
779 val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
780 (self.dev_type, self.logical_id, self.physical_id, self.children))
781 if self.iv_name is None:
782 val += ", not visible"
784 val += ", visible as /dev/%s" % self.iv_name
785 if isinstance(self.size, int):
786 val += ", size=%dm)>" % self.size
788 val += ", size='%s')>" % (self.size,)
792 """Checks that this disk is correctly configured.
796 if self.mode not in constants.DISK_ACCESS_SET:
797 all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
800 def UpgradeConfig(self):
801 """Fill defaults for missing configuration values.
805 for child in self.children:
806 child.UpgradeConfig()
808 # FIXME: Make this configurable in Ganeti 2.7
810 # add here config upgrade for this disk
813 def ComputeLDParams(disk_template, disk_params):
814 """Computes Logical Disk parameters from Disk Template parameters.
816 @type disk_template: string
817 @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
818 @type disk_params: dict
819 @param disk_params: disk template parameters;
820 dict(template_name -> parameters
822 @return: a list of dicts, one for each node of the disk hierarchy. Each dict
823 contains the LD parameters of the node. The tree is flattened in-order.
826 if disk_template not in constants.DISK_TEMPLATES:
827 raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
829 assert disk_template in disk_params
832 dt_params = disk_params[disk_template]
833 if disk_template == constants.DT_DRBD8:
834 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8], {
835 constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
836 constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
837 constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
838 constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
839 constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
840 constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
841 constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
842 constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
843 constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
844 constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
845 constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
846 constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
850 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
851 constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
855 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
856 constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
859 elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
860 result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
862 elif disk_template == constants.DT_PLAIN:
863 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
864 constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
867 elif disk_template == constants.DT_BLOCK:
868 result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
870 elif disk_template == constants.DT_RBD:
871 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD], {
872 constants.LDP_POOL: dt_params[constants.RBD_POOL],
875 elif disk_template == constants.DT_EXT:
876 result.append(constants.DISK_LD_DEFAULTS[constants.LD_EXT])
881 class InstancePolicy(ConfigObject):
882 """Config object representing instance policy limits dictionary.
885 Note that this object is not actually used in the config, it's just
886 used as a placeholder for a few functions.
890 def CheckParameterSyntax(cls, ipolicy, check_std):
891 """ Check the instance policy for validity.
894 for param in constants.ISPECS_PARAMETERS:
895 InstancePolicy.CheckISpecSyntax(ipolicy, param, check_std)
896 if constants.IPOLICY_DTS in ipolicy:
897 InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
898 for key in constants.IPOLICY_PARAMETERS:
900 InstancePolicy.CheckParameter(key, ipolicy[key])
901 wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
903 raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
904 utils.CommaJoin(wrong_keys))
907 def CheckISpecSyntax(cls, ipolicy, name, check_std):
908 """Check the instance policy for validity on a given key.
910 We check if the instance policy makes sense for a given key, that is
911 if ipolicy[min][name] <= ipolicy[std][name] <= ipolicy[max][name].
914 @param ipolicy: dictionary with min, max, std specs
916 @param name: what are the limits for
917 @type check_std: bool
918 @param check_std: Whether to check std value or just assume compliance
919 @raise errors.ConfigureError: when specs for given name are not valid
922 min_v = ipolicy[constants.ISPECS_MIN].get(name, 0)
925 std_v = ipolicy[constants.ISPECS_STD].get(name, min_v)
931 max_v = ipolicy[constants.ISPECS_MAX].get(name, std_v)
932 err = ("Invalid specification of min/max/std values for %s: %s/%s/%s" %
934 ipolicy[constants.ISPECS_MIN].get(name, "-"),
935 ipolicy[constants.ISPECS_MAX].get(name, "-"),
937 if min_v > std_v or std_v > max_v:
938 raise errors.ConfigurationError(err)
941 def CheckDiskTemplates(cls, disk_templates):
942 """Checks the disk templates for validity.
945 if not disk_templates:
946 raise errors.ConfigurationError("Instance policy must contain" +
947 " at least one disk template")
948 wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
950 raise errors.ConfigurationError("Invalid disk template(s) %s" %
951 utils.CommaJoin(wrong))
954 def CheckParameter(cls, key, value):
955 """Checks a parameter.
957 Currently we expect all parameters to be float values.
962 except (TypeError, ValueError), err:
963 raise errors.ConfigurationError("Invalid value for key" " '%s':"
964 " '%s', error: %s" % (key, value, err))
967 class Instance(TaggableObject):
968 """Config object representing an instance."""
983 ] + _TIMESTAMPS + _UUID
985 def _ComputeSecondaryNodes(self):
986 """Compute the list of secondary nodes.
988 This is a simple wrapper over _ComputeAllNodes.
991 all_nodes = set(self._ComputeAllNodes())
992 all_nodes.discard(self.primary_node)
993 return tuple(all_nodes)
995 secondary_nodes = property(_ComputeSecondaryNodes, None, None,
996 "List of names of secondary nodes")
998 def _ComputeAllNodes(self):
999 """Compute the list of all nodes.
1001 Since the data is already there (in the drbd disks), keeping it as
1002 a separate normal attribute is redundant and if not properly
1003 synchronised can cause problems. Thus it's better to compute it
1007 def _Helper(nodes, device):
1008 """Recursively computes nodes given a top device."""
1009 if device.dev_type in constants.LDS_DRBD:
1010 nodea, nodeb = device.logical_id[:2]
1014 for child in device.children:
1015 _Helper(nodes, child)
1018 all_nodes.add(self.primary_node)
1019 for device in self.disks:
1020 _Helper(all_nodes, device)
1021 return tuple(all_nodes)
1023 all_nodes = property(_ComputeAllNodes, None, None,
1024 "List of names of all the nodes of the instance")
1026 def MapLVsByNode(self, lvmap=None, devs=None, node=None):
1027 """Provide a mapping of nodes to LVs this instance owns.
1029 This function figures out what logical volumes should belong on
1030 which nodes, recursing through a device tree.
1032 @param lvmap: optional dictionary to receive the
1033 'node' : ['lv', ...] data.
1035 @return: None if lvmap arg is given, otherwise, a dictionary of
1036 the form { 'nodename' : ['volume1', 'volume2', ...], ... };
1037 volumeN is of the form "vg_name/lv_name", compatible with
1042 node = self.primary_node
1050 if not node in lvmap:
1058 if dev.dev_type == constants.LD_LV:
1059 lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1061 elif dev.dev_type in constants.LDS_DRBD:
1063 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1064 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1067 self.MapLVsByNode(lvmap, dev.children, node)
1071 def FindDisk(self, idx):
1072 """Find a disk given having a specified index.
1074 This is just a wrapper that does validation of the index.
1077 @param idx: the disk index
1079 @return: the corresponding disk
1080 @raise errors.OpPrereqError: when the given index is not valid
1085 return self.disks[idx]
1086 except (TypeError, ValueError), err:
1087 raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1090 raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1091 " 0 to %d" % (idx, len(self.disks) - 1),
1095 """Instance-specific conversion to standard python types.
1097 This replaces the children lists of objects with lists of standard
1101 bo = super(Instance, self).ToDict()
1103 for attr in "nics", "disks":
1104 alist = bo.get(attr, None)
1106 nlist = outils.ContainerToDicts(alist)
1113 def FromDict(cls, val):
1114 """Custom function for instances.
1117 if "admin_state" not in val:
1118 if val.get("admin_up", False):
1119 val["admin_state"] = constants.ADMINST_UP
1121 val["admin_state"] = constants.ADMINST_DOWN
1122 if "admin_up" in val:
1124 obj = super(Instance, cls).FromDict(val)
1125 obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1126 obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1129 def UpgradeConfig(self):
1130 """Fill defaults for missing configuration values.
1133 for nic in self.nics:
1135 for disk in self.disks:
1136 disk.UpgradeConfig()
1138 for key in constants.HVC_GLOBALS:
1140 del self.hvparams[key]
1143 if self.osparams is None:
1145 UpgradeBeParams(self.beparams)
1148 class OS(ConfigObject):
1149 """Config object representing an operating system.
1151 @type supported_parameters: list
1152 @ivar supported_parameters: a list of tuples, name and description,
1153 containing the supported parameters by this OS
1155 @type VARIANT_DELIM: string
1156 @cvar VARIANT_DELIM: the variant delimiter
1168 "supported_variants",
1169 "supported_parameters",
1175 def SplitNameVariant(cls, name):
1176 """Splits the name into the proper name and variant.
1178 @param name: the OS (unprocessed) name
1180 @return: a list of two elements; if the original name didn't
1181 contain a variant, it's returned as an empty string
1184 nv = name.split(cls.VARIANT_DELIM, 1)
1190 def GetName(cls, name):
1191 """Returns the proper name of the os (without the variant).
1193 @param name: the OS (unprocessed) name
1196 return cls.SplitNameVariant(name)[0]
1199 def GetVariant(cls, name):
1200 """Returns the variant the os (without the base name).
1202 @param name: the OS (unprocessed) name
1205 return cls.SplitNameVariant(name)[1]
1208 class ExtStorage(ConfigObject):
1209 """Config object representing an External Storage Provider.
1222 "supported_parameters",
1226 class NodeHvState(ConfigObject):
1227 """Hypvervisor state on a node.
1229 @ivar mem_total: Total amount of memory
1230 @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1232 @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1234 @ivar mem_inst: Memory used by instances living on node
1235 @ivar cpu_total: Total node CPU core count
1236 @ivar cpu_node: Number of CPU cores reserved for the node itself
1249 class NodeDiskState(ConfigObject):
1250 """Disk state on a node.
1260 class Node(TaggableObject):
1261 """Config object representing a node.
1263 @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1264 @ivar hv_state_static: Hypervisor state overriden by user
1265 @ivar disk_state: Disk state (e.g. free space)
1266 @ivar disk_state_static: Disk state overriden by user
1285 "disk_state_static",
1286 ] + _TIMESTAMPS + _UUID
1288 def UpgradeConfig(self):
1289 """Fill defaults for missing configuration values.
1292 # pylint: disable=E0203
1293 # because these are "defined" via slots, not manually
1294 if self.master_capable is None:
1295 self.master_capable = True
1297 if self.vm_capable is None:
1298 self.vm_capable = True
1300 if self.ndparams is None:
1302 # And remove any global parameter
1303 for key in constants.NDC_GLOBALS:
1304 if key in self.ndparams:
1305 logging.warning("Ignoring %s node parameter for node %s",
1307 del self.ndparams[key]
1309 if self.powered is None:
1313 """Custom function for serializing.
1316 data = super(Node, self).ToDict()
1318 hv_state = data.get("hv_state", None)
1319 if hv_state is not None:
1320 data["hv_state"] = outils.ContainerToDicts(hv_state)
1322 disk_state = data.get("disk_state", None)
1323 if disk_state is not None:
1324 data["disk_state"] = \
1325 dict((key, outils.ContainerToDicts(value))
1326 for (key, value) in disk_state.items())
1331 def FromDict(cls, val):
1332 """Custom function for deserializing.
1335 obj = super(Node, cls).FromDict(val)
1337 if obj.hv_state is not None:
1339 outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1341 if obj.disk_state is not None:
1343 dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1344 for (key, value) in obj.disk_state.items())
1349 class NodeGroup(TaggableObject):
1350 """Config object representing a node group."""
1359 "disk_state_static",
1362 ] + _TIMESTAMPS + _UUID
1365 """Custom function for nodegroup.
1367 This discards the members object, which gets recalculated and is only kept
1371 mydict = super(NodeGroup, self).ToDict()
1372 del mydict["members"]
1376 def FromDict(cls, val):
1377 """Custom function for nodegroup.
1379 The members slot is initialized to an empty list, upon deserialization.
1382 obj = super(NodeGroup, cls).FromDict(val)
1386 def UpgradeConfig(self):
1387 """Fill defaults for missing configuration values.
1390 if self.ndparams is None:
1393 if self.serial_no is None:
1396 if self.alloc_policy is None:
1397 self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1399 # We only update mtime, and not ctime, since we would not be able
1400 # to provide a correct value for creation time.
1401 if self.mtime is None:
1402 self.mtime = time.time()
1404 if self.diskparams is None:
1405 self.diskparams = {}
1406 if self.ipolicy is None:
1407 self.ipolicy = MakeEmptyIPolicy()
1409 if self.networks is None:
1412 def FillND(self, node):
1413 """Return filled out ndparams for L{objects.Node}
1415 @type node: L{objects.Node}
1416 @param node: A Node object to fill
1417 @return a copy of the node's ndparams with defaults filled
1420 return self.SimpleFillND(node.ndparams)
1422 def SimpleFillND(self, ndparams):
1423 """Fill a given ndparams dict with defaults.
1425 @type ndparams: dict
1426 @param ndparams: the dict to fill
1428 @return: a copy of the passed in ndparams with missing keys filled
1429 from the node group defaults
1432 return FillDict(self.ndparams, ndparams)
1435 class Cluster(TaggableObject):
1436 """Config object representing the cluster."""
1440 "highest_used_port",
1443 "volume_group_name",
1445 "drbd_usermode_helper",
1447 "default_hypervisor",
1452 "use_external_mip_script",
1455 "shared_file_storage_dir",
1456 "enabled_hypervisors",
1465 "candidate_pool_size",
1468 "maintain_node_health",
1470 "default_iallocator",
1473 "primary_ip_family",
1474 "prealloc_wipe_disks",
1476 "disk_state_static",
1477 "enabled_storage_types",
1478 ] + _TIMESTAMPS + _UUID
1480 def UpgradeConfig(self):
1481 """Fill defaults for missing configuration values.
1484 # pylint: disable=E0203
1485 # because these are "defined" via slots, not manually
1486 if self.hvparams is None:
1487 self.hvparams = constants.HVC_DEFAULTS
1489 for hypervisor in self.hvparams:
1490 self.hvparams[hypervisor] = FillDict(
1491 constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1493 if self.os_hvp is None:
1496 # osparams added before 2.2
1497 if self.osparams is None:
1500 self.ndparams = UpgradeNDParams(self.ndparams)
1502 self.beparams = UpgradeGroupedParams(self.beparams,
1503 constants.BEC_DEFAULTS)
1504 for beparams_group in self.beparams:
1505 UpgradeBeParams(self.beparams[beparams_group])
1507 migrate_default_bridge = not self.nicparams
1508 self.nicparams = UpgradeGroupedParams(self.nicparams,
1509 constants.NICC_DEFAULTS)
1510 if migrate_default_bridge:
1511 self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1514 if self.modify_etc_hosts is None:
1515 self.modify_etc_hosts = True
1517 if self.modify_ssh_setup is None:
1518 self.modify_ssh_setup = True
1520 # default_bridge is no longer used in 2.1. The slot is left there to
1521 # support auto-upgrading. It can be removed once we decide to deprecate
1522 # upgrading straight from 2.0.
1523 if self.default_bridge is not None:
1524 self.default_bridge = None
1526 # default_hypervisor is just the first enabled one in 2.1. This slot and
1527 # code can be removed once upgrading straight from 2.0 is deprecated.
1528 if self.default_hypervisor is not None:
1529 self.enabled_hypervisors = ([self.default_hypervisor] +
1530 [hvname for hvname in self.enabled_hypervisors
1531 if hvname != self.default_hypervisor])
1532 self.default_hypervisor = None
1534 # maintain_node_health added after 2.1.1
1535 if self.maintain_node_health is None:
1536 self.maintain_node_health = False
1538 if self.uid_pool is None:
1541 if self.default_iallocator is None:
1542 self.default_iallocator = ""
1544 # reserved_lvs added before 2.2
1545 if self.reserved_lvs is None:
1546 self.reserved_lvs = []
1548 # hidden and blacklisted operating systems added before 2.2.1
1549 if self.hidden_os is None:
1552 if self.blacklisted_os is None:
1553 self.blacklisted_os = []
1555 # primary_ip_family added before 2.3
1556 if self.primary_ip_family is None:
1557 self.primary_ip_family = AF_INET
1559 if self.master_netmask is None:
1560 ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1561 self.master_netmask = ipcls.iplen
1563 if self.prealloc_wipe_disks is None:
1564 self.prealloc_wipe_disks = False
1566 # shared_file_storage_dir added before 2.5
1567 if self.shared_file_storage_dir is None:
1568 self.shared_file_storage_dir = ""
1570 if self.use_external_mip_script is None:
1571 self.use_external_mip_script = False
1574 self.diskparams = UpgradeDiskParams(self.diskparams)
1576 self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1578 # instance policy added before 2.6
1579 if self.ipolicy is None:
1580 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1582 # we can either make sure to upgrade the ipolicy always, or only
1583 # do it in some corner cases (e.g. missing keys); note that this
1584 # will break any removal of keys from the ipolicy dict
1585 wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1587 # These keys would be silently removed by FillIPolicy()
1588 msg = ("Cluster instance policy contains spourious keys: %s" %
1589 utils.CommaJoin(wrongkeys))
1590 raise errors.ConfigurationError(msg)
1591 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1594 def primary_hypervisor(self):
1595 """The first hypervisor is the primary.
1597 Useful, for example, for L{Node}'s hv/disk state.
1600 return self.enabled_hypervisors[0]
1603 """Custom function for cluster.
1606 mydict = super(Cluster, self).ToDict()
1608 if self.tcpudp_port_pool is None:
1609 tcpudp_port_pool = []
1611 tcpudp_port_pool = list(self.tcpudp_port_pool)
1613 mydict["tcpudp_port_pool"] = tcpudp_port_pool
1618 def FromDict(cls, val):
1619 """Custom function for cluster.
1622 obj = super(Cluster, cls).FromDict(val)
1624 if obj.tcpudp_port_pool is None:
1625 obj.tcpudp_port_pool = set()
1626 elif not isinstance(obj.tcpudp_port_pool, set):
1627 obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1631 def SimpleFillDP(self, diskparams):
1632 """Fill a given diskparams dict with cluster defaults.
1634 @param diskparams: The diskparams
1635 @return: The defaults dict
1638 return FillDiskParams(self.diskparams, diskparams)
1640 def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1641 """Get the default hypervisor parameters for the cluster.
1643 @param hypervisor: the hypervisor name
1644 @param os_name: if specified, we'll also update the defaults for this OS
1645 @param skip_keys: if passed, list of keys not to use
1646 @return: the defaults dict
1649 if skip_keys is None:
1652 fill_stack = [self.hvparams.get(hypervisor, {})]
1653 if os_name is not None:
1654 os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1655 fill_stack.append(os_hvp)
1658 for o_dict in fill_stack:
1659 ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1663 def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1664 """Fill a given hvparams dict with cluster defaults.
1666 @type hv_name: string
1667 @param hv_name: the hypervisor to use
1668 @type os_name: string
1669 @param os_name: the OS to use for overriding the hypervisor defaults
1670 @type skip_globals: boolean
1671 @param skip_globals: if True, the global hypervisor parameters will
1674 @return: a copy of the given hvparams with missing keys filled from
1675 the cluster defaults
1679 skip_keys = constants.HVC_GLOBALS
1683 def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1684 return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1686 def FillHV(self, instance, skip_globals=False):
1687 """Fill an instance's hvparams dict with cluster defaults.
1689 @type instance: L{objects.Instance}
1690 @param instance: the instance parameter to fill
1691 @type skip_globals: boolean
1692 @param skip_globals: if True, the global hypervisor parameters will
1695 @return: a copy of the instance's hvparams with missing keys filled from
1696 the cluster defaults
1699 return self.SimpleFillHV(instance.hypervisor, instance.os,
1700 instance.hvparams, skip_globals)
1702 def SimpleFillBE(self, beparams):
1703 """Fill a given beparams dict with cluster defaults.
1705 @type beparams: dict
1706 @param beparams: the dict to fill
1708 @return: a copy of the passed in beparams with missing keys filled
1709 from the cluster defaults
1712 return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1714 def FillBE(self, instance):
1715 """Fill an instance's beparams dict with cluster defaults.
1717 @type instance: L{objects.Instance}
1718 @param instance: the instance parameter to fill
1720 @return: a copy of the instance's beparams with missing keys filled from
1721 the cluster defaults
1724 return self.SimpleFillBE(instance.beparams)
1726 def SimpleFillNIC(self, nicparams):
1727 """Fill a given nicparams dict with cluster defaults.
1729 @type nicparams: dict
1730 @param nicparams: the dict to fill
1732 @return: a copy of the passed in nicparams with missing keys filled
1733 from the cluster defaults
1736 return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1738 def SimpleFillOS(self, os_name, os_params):
1739 """Fill an instance's osparams dict with cluster defaults.
1741 @type os_name: string
1742 @param os_name: the OS name to use
1743 @type os_params: dict
1744 @param os_params: the dict to fill with default values
1746 @return: a copy of the instance's osparams with missing keys filled from
1747 the cluster defaults
1750 name_only = os_name.split("+", 1)[0]
1752 result = self.osparams.get(name_only, {})
1754 result = FillDict(result, self.osparams.get(os_name, {}))
1756 return FillDict(result, os_params)
1759 def SimpleFillHvState(hv_state):
1760 """Fill an hv_state sub dict with cluster defaults.
1763 return FillDict(constants.HVST_DEFAULTS, hv_state)
1766 def SimpleFillDiskState(disk_state):
1767 """Fill an disk_state sub dict with cluster defaults.
1770 return FillDict(constants.DS_DEFAULTS, disk_state)
1772 def FillND(self, node, nodegroup):
1773 """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1775 @type node: L{objects.Node}
1776 @param node: A Node object to fill
1777 @type nodegroup: L{objects.NodeGroup}
1778 @param nodegroup: A Node object to fill
1779 @return a copy of the node's ndparams with defaults filled
1782 return self.SimpleFillND(nodegroup.FillND(node))
1784 def SimpleFillND(self, ndparams):
1785 """Fill a given ndparams dict with defaults.
1787 @type ndparams: dict
1788 @param ndparams: the dict to fill
1790 @return: a copy of the passed in ndparams with missing keys filled
1791 from the cluster defaults
1794 return FillDict(self.ndparams, ndparams)
1796 def SimpleFillIPolicy(self, ipolicy):
1797 """ Fill instance policy dict with defaults.
1800 @param ipolicy: the dict to fill
1802 @return: a copy of passed ipolicy with missing keys filled from
1803 the cluster defaults
1806 return FillIPolicy(self.ipolicy, ipolicy)
1809 class BlockDevStatus(ConfigObject):
1810 """Config object representing the status of a block device."""
1822 class ImportExportStatus(ConfigObject):
1823 """Config object representing the status of an import or export."""
1829 "progress_throughput",
1837 class ImportExportOptions(ConfigObject):
1838 """Options for import/export daemon
1840 @ivar key_name: X509 key name (None for cluster certificate)
1841 @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1842 @ivar compress: Compression method (one of L{constants.IEC_ALL})
1843 @ivar magic: Used to ensure the connection goes to the right disk
1844 @ivar ipv6: Whether to use IPv6
1845 @ivar connect_timeout: Number of seconds for establishing connection
1858 class ConfdRequest(ConfigObject):
1859 """Object holding a confd request.
1861 @ivar protocol: confd protocol version
1862 @ivar type: confd query type
1863 @ivar query: query request
1864 @ivar rsalt: requested reply salt
1875 class ConfdReply(ConfigObject):
1876 """Object holding a confd reply.
1878 @ivar protocol: confd protocol version
1879 @ivar status: reply status code (ok, error)
1880 @ivar answer: confd query reply
1881 @ivar serial: configuration serial number
1892 class QueryFieldDefinition(ConfigObject):
1893 """Object holding a query field definition.
1895 @ivar name: Field name
1896 @ivar title: Human-readable title
1897 @ivar kind: Field type
1898 @ivar doc: Human-readable description
1909 class _QueryResponseBase(ConfigObject):
1915 """Custom function for serializing.
1918 mydict = super(_QueryResponseBase, self).ToDict()
1919 mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
1923 def FromDict(cls, val):
1924 """Custom function for de-serializing.
1927 obj = super(_QueryResponseBase, cls).FromDict(val)
1929 outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
1933 class QueryResponse(_QueryResponseBase):
1934 """Object holding the response to a query.
1936 @ivar fields: List of L{QueryFieldDefinition} objects
1937 @ivar data: Requested data
1945 class QueryFieldsRequest(ConfigObject):
1946 """Object holding a request for querying available fields.
1955 class QueryFieldsResponse(_QueryResponseBase):
1956 """Object holding the response to a query for fields.
1958 @ivar fields: List of L{QueryFieldDefinition} objects
1964 class MigrationStatus(ConfigObject):
1965 """Object holding the status of a migration.
1975 class InstanceConsole(ConfigObject):
1976 """Object describing how to access the console of an instance.
1991 """Validates contents of this object.
1994 assert self.kind in constants.CONS_ALL, "Unknown console type"
1995 assert self.instance, "Missing instance name"
1996 assert self.message or self.kind in [constants.CONS_SSH,
1997 constants.CONS_SPICE,
1999 assert self.host or self.kind == constants.CONS_MESSAGE
2000 assert self.port or self.kind in [constants.CONS_MESSAGE,
2002 assert self.user or self.kind in [constants.CONS_MESSAGE,
2003 constants.CONS_SPICE,
2005 assert self.command or self.kind in [constants.CONS_MESSAGE,
2006 constants.CONS_SPICE,
2008 assert self.display or self.kind in [constants.CONS_MESSAGE,
2009 constants.CONS_SPICE,
2014 class Network(TaggableObject):
2015 """Object representing a network definition for ganeti.
2028 ] + _TIMESTAMPS + _UUID
2030 def HooksDict(self, prefix=""):
2031 """Export a dictionary used by hooks with a network's information.
2033 @type prefix: String
2034 @param prefix: Prefix to prepend to the dict entries
2038 "%sNETWORK_NAME" % prefix: self.name,
2039 "%sNETWORK_UUID" % prefix: self.uuid,
2040 "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2043 result["%sNETWORK_SUBNET" % prefix] = self.network
2045 result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2047 result["%sNETWORK_SUBNET6" % prefix] = self.network6
2049 result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2051 result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2056 def FromDict(cls, val):
2057 """Custom function for networks.
2059 Remove deprecated network_type and family.
2062 if "network_type" in val:
2063 del val["network_type"]
2066 obj = super(Network, cls).FromDict(val)
2070 class SerializableConfigParser(ConfigParser.SafeConfigParser):
2071 """Simple wrapper over ConfigParse that allows serialization.
2073 This class is basically ConfigParser.SafeConfigParser with two
2074 additional methods that allow it to serialize/unserialize to/from a
2079 """Dump this instance and return the string representation."""
2082 return buf.getvalue()
2085 def Loads(cls, data):
2086 """Load data from a string."""
2087 buf = StringIO(data)
2093 class LvmPvInfo(ConfigObject):
2094 """Information about an LVM physical volume (PV).
2097 @ivar name: name of the PV
2098 @type vg_name: string
2099 @ivar vg_name: name of the volume group containing the PV
2101 @ivar size: size of the PV in MiB
2103 @ivar free: free space in the PV, in MiB
2104 @type attributes: string
2105 @ivar attributes: PV attributes
2106 @type lv_list: list of strings
2107 @ivar lv_list: names of the LVs hosted on the PV
2119 """Is this PV empty?
2122 return self.size <= (self.free + 1)
2124 def IsAllocatable(self):
2125 """Is this PV allocatable?
2128 return ("a" in self.attributes)