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):
86 """Fills an instance policy with defaults.
89 assert frozenset(default_ipolicy.keys()) == constants.IPOLICY_ALL_KEYS
90 ret_dict = copy.deepcopy(custom_ipolicy)
91 for key in default_ipolicy:
92 if key not in ret_dict:
93 ret_dict[key] = copy.deepcopy(default_ipolicy[key])
94 elif key == constants.ISPECS_STD:
95 ret_dict[key] = FillDict(default_ipolicy[key], ret_dict[key])
99 def FillDiskParams(default_dparams, custom_dparams, skip_keys=None):
100 """Fills the disk parameter defaults.
102 @see: L{FillDict} for parameters and return value
105 assert frozenset(default_dparams.keys()) == constants.DISK_TEMPLATES
107 return dict((dt, FillDict(default_dparams[dt], custom_dparams.get(dt, {}),
108 skip_keys=skip_keys))
109 for dt in constants.DISK_TEMPLATES)
112 def UpgradeGroupedParams(target, defaults):
113 """Update all groups for the target parameter.
115 @type target: dict of dicts
116 @param target: {group: {parameter: value}}
118 @param defaults: default parameter values
122 target = {constants.PP_DEFAULT: defaults}
125 target[group] = FillDict(defaults, target[group])
129 def UpgradeBeParams(target):
130 """Update the be parameters dict to the new format.
133 @param target: "be" parameters dict
136 if constants.BE_MEMORY in target:
137 memory = target[constants.BE_MEMORY]
138 target[constants.BE_MAXMEM] = memory
139 target[constants.BE_MINMEM] = memory
140 del target[constants.BE_MEMORY]
143 def UpgradeDiskParams(diskparams):
144 """Upgrade the disk parameters.
146 @type diskparams: dict
147 @param diskparams: disk parameters to upgrade
149 @return: the upgraded disk parameters dict
155 result = FillDiskParams(constants.DISK_DT_DEFAULTS, diskparams)
160 def UpgradeNDParams(ndparams):
161 """Upgrade ndparams structure.
164 @param ndparams: disk parameters to upgrade
166 @return: the upgraded node parameters dict
172 if (constants.ND_OOB_PROGRAM in ndparams and
173 ndparams[constants.ND_OOB_PROGRAM] is None):
174 # will be reset by the line below
175 del ndparams[constants.ND_OOB_PROGRAM]
176 return FillDict(constants.NDC_DEFAULTS, ndparams)
179 def MakeEmptyIPolicy():
180 """Create empty IPolicy dictionary.
186 class ConfigObject(outils.ValidatedSlots):
187 """A generic config object.
189 It has the following properties:
191 - provides somewhat safe recursive unpickling and pickling for its classes
192 - unset attributes which are defined in slots are always returned
193 as None instead of raising an error
195 Classes derived from this must always declare __slots__ (we use many
196 config objects and the memory reduction is useful)
201 def __getattr__(self, name):
202 if name not in self.GetAllSlots():
203 raise AttributeError("Invalid object attribute %s.%s" %
204 (type(self).__name__, name))
207 def __setstate__(self, state):
208 slots = self.GetAllSlots()
211 setattr(self, name, state[name])
214 """Validates the slots.
219 """Convert to a dict holding only standard python types.
221 The generic routine just dumps all of this object's attributes in
222 a dict. It does not work if the class has children who are
223 ConfigObjects themselves (e.g. the nics list in an Instance), in
224 which case the object should subclass the function in order to
225 make sure all objects returned are only standard python types.
229 for name in self.GetAllSlots():
230 value = getattr(self, name, None)
231 if value is not None:
235 __getstate__ = ToDict
238 def FromDict(cls, val):
239 """Create an object from a dictionary.
241 This generic routine takes a dict, instantiates a new instance of
242 the given class, and sets attributes based on the dict content.
244 As for `ToDict`, this does not work if the class has children
245 who are ConfigObjects themselves (e.g. the nics list in an
246 Instance), in which case the object should subclass the function
247 and alter the objects.
250 if not isinstance(val, dict):
251 raise errors.ConfigurationError("Invalid object passed to FromDict:"
252 " expected dict, got %s" % type(val))
253 val_str = dict([(str(k), v) for k, v in val.iteritems()])
254 obj = cls(**val_str) # pylint: disable=W0142
258 """Makes a deep copy of the current object and its children.
261 dict_form = self.ToDict()
262 clone_obj = self.__class__.FromDict(dict_form)
266 """Implement __repr__ for ConfigObjects."""
267 return repr(self.ToDict())
269 def UpgradeConfig(self):
270 """Fill defaults for missing configuration values.
272 This method will be called at configuration load time, and its
273 implementation will be object dependent.
279 class TaggableObject(ConfigObject):
280 """An generic class supporting tags.
284 VALID_TAG_RE = re.compile("^[\w.+*/:@-]+$")
287 def ValidateTag(cls, tag):
288 """Check if a tag is valid.
290 If the tag is invalid, an errors.TagError will be raised. The
291 function has no return value.
294 if not isinstance(tag, basestring):
295 raise errors.TagError("Invalid tag type (not a string)")
296 if len(tag) > constants.MAX_TAG_LEN:
297 raise errors.TagError("Tag too long (>%d characters)" %
298 constants.MAX_TAG_LEN)
300 raise errors.TagError("Tags cannot be empty")
301 if not cls.VALID_TAG_RE.match(tag):
302 raise errors.TagError("Tag contains invalid characters")
305 """Return the tags list.
308 tags = getattr(self, "tags", None)
310 tags = self.tags = set()
313 def AddTag(self, tag):
317 self.ValidateTag(tag)
318 tags = self.GetTags()
319 if len(tags) >= constants.MAX_TAGS_PER_OBJ:
320 raise errors.TagError("Too many tags")
321 self.GetTags().add(tag)
323 def RemoveTag(self, tag):
327 self.ValidateTag(tag)
328 tags = self.GetTags()
332 raise errors.TagError("Tag not found")
335 """Taggable-object-specific conversion to standard python types.
337 This replaces the tags set with a list.
340 bo = super(TaggableObject, self).ToDict()
342 tags = bo.get("tags", None)
343 if isinstance(tags, set):
344 bo["tags"] = list(tags)
348 def FromDict(cls, val):
349 """Custom function for instances.
352 obj = super(TaggableObject, cls).FromDict(val)
353 if hasattr(obj, "tags") and isinstance(obj.tags, list):
354 obj.tags = set(obj.tags)
358 class MasterNetworkParameters(ConfigObject):
359 """Network configuration parameters for the master
361 @ivar name: master name
363 @ivar netmask: master netmask
364 @ivar netdev: master network device
365 @ivar ip_family: master IP family
377 class ConfigData(ConfigObject):
378 """Top-level config object."""
390 """Custom function for top-level config data.
392 This just replaces the list of instances, nodes and the cluster
393 with standard python types.
396 mydict = super(ConfigData, self).ToDict()
397 mydict["cluster"] = mydict["cluster"].ToDict()
398 for key in "nodes", "instances", "nodegroups", "networks":
399 mydict[key] = outils.ContainerToDicts(mydict[key])
404 def FromDict(cls, val):
405 """Custom function for top-level config data
408 obj = super(ConfigData, cls).FromDict(val)
409 obj.cluster = Cluster.FromDict(obj.cluster)
410 obj.nodes = outils.ContainerFromDicts(obj.nodes, dict, Node)
412 outils.ContainerFromDicts(obj.instances, dict, Instance)
414 outils.ContainerFromDicts(obj.nodegroups, dict, NodeGroup)
415 obj.networks = outils.ContainerFromDicts(obj.networks, dict, Network)
418 def HasAnyDiskOfType(self, dev_type):
419 """Check if in there is at disk of the given type in the configuration.
421 @type dev_type: L{constants.LDS_BLOCK}
422 @param dev_type: the type to look for
424 @return: boolean indicating if a disk of the given type was found or not
427 for instance in self.instances.values():
428 for disk in instance.disks:
429 if disk.IsBasedOnDiskType(dev_type):
433 def UpgradeConfig(self):
434 """Fill defaults for missing configuration values.
437 self.cluster.UpgradeConfig()
438 for node in self.nodes.values():
440 for instance in self.instances.values():
441 instance.UpgradeConfig()
442 if self.nodegroups is None:
444 for nodegroup in self.nodegroups.values():
445 nodegroup.UpgradeConfig()
446 if self.cluster.drbd_usermode_helper is None:
447 # To decide if we set an helper let's check if at least one instance has
448 # a DRBD disk. This does not cover all the possible scenarios but it
449 # gives a good approximation.
450 if self.HasAnyDiskOfType(constants.LD_DRBD8):
451 self.cluster.drbd_usermode_helper = constants.DEFAULT_DRBD_HELPER
452 if self.networks is None:
454 for network in self.networks.values():
455 network.UpgradeConfig()
456 self._UpgradeEnabledDiskTemplates()
458 def _UpgradeEnabledDiskTemplates(self):
459 """Upgrade the cluster's enabled disk templates by inspecting the currently
460 enabled and/or used disk templates.
463 # enabled_disk_templates in the cluster config were introduced in 2.8.
464 # Remove this code once upgrading from earlier versions is deprecated.
465 if not self.cluster.enabled_disk_templates:
467 set([inst.disk_template for inst in self.instances.values()])
468 # Add drbd and plain, if lvm is enabled (by specifying a volume group)
469 if self.cluster.volume_group_name:
470 template_set.add(constants.DT_DRBD8)
471 template_set.add(constants.DT_PLAIN)
472 # FIXME: Adapt this when dis/enabling at configure time is removed.
473 # Enable 'file' and 'sharedfile', if they are enabled, even though they
474 # might currently not be used.
475 if constants.ENABLE_FILE_STORAGE:
476 template_set.add(constants.DT_FILE)
477 if constants.ENABLE_SHARED_FILE_STORAGE:
478 template_set.add(constants.DT_SHARED_FILE)
479 # Set enabled_disk_templates to the inferred disk templates. Order them
480 # according to a preference list that is based on Ganeti's history of
481 # supported disk templates.
482 self.cluster.enabled_disk_templates = []
483 for preferred_template in constants.DISK_TEMPLATE_PREFERENCE:
484 if preferred_template in template_set:
485 self.cluster.enabled_disk_templates.append(preferred_template)
486 template_set.remove(preferred_template)
487 self.cluster.enabled_disk_templates.extend(list(template_set))
490 class NIC(ConfigObject):
491 """Config object representing a network card."""
492 __slots__ = ["name", "mac", "ip", "network", "nicparams", "netinfo"] + _UUID
495 def CheckParameterSyntax(cls, nicparams):
496 """Check the given parameters for validity.
498 @type nicparams: dict
499 @param nicparams: dictionary with parameter names/value
500 @raise errors.ConfigurationError: when a parameter is not valid
503 mode = nicparams[constants.NIC_MODE]
504 if (mode not in constants.NIC_VALID_MODES and
505 mode != constants.VALUE_AUTO):
506 raise errors.ConfigurationError("Invalid NIC mode '%s'" % mode)
508 if (mode == constants.NIC_MODE_BRIDGED and
509 not nicparams[constants.NIC_LINK]):
510 raise errors.ConfigurationError("Missing bridged NIC link")
513 class Disk(ConfigObject):
514 """Config object representing a block device."""
515 __slots__ = ["name", "dev_type", "logical_id", "physical_id",
516 "children", "iv_name", "size", "mode", "params"] + _UUID
518 def CreateOnSecondary(self):
519 """Test if this device needs to be created on a secondary node."""
520 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
522 def AssembleOnSecondary(self):
523 """Test if this device needs to be assembled on a secondary node."""
524 return self.dev_type in (constants.LD_DRBD8, constants.LD_LV)
526 def OpenOnSecondary(self):
527 """Test if this device needs to be opened on a secondary node."""
528 return self.dev_type in (constants.LD_LV,)
530 def StaticDevPath(self):
531 """Return the device path if this device type has a static one.
533 Some devices (LVM for example) live always at the same /dev/ path,
534 irrespective of their status. For such devices, we return this
535 path, for others we return None.
537 @warning: The path returned is not a normalized pathname; callers
538 should check that it is a valid path.
541 if self.dev_type == constants.LD_LV:
542 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
543 elif self.dev_type == constants.LD_BLOCKDEV:
544 return self.logical_id[1]
545 elif self.dev_type == constants.LD_RBD:
546 return "/dev/%s/%s" % (self.logical_id[0], self.logical_id[1])
549 def ChildrenNeeded(self):
550 """Compute the needed number of children for activation.
552 This method will return either -1 (all children) or a positive
553 number denoting the minimum number of children needed for
554 activation (only mirrored devices will usually return >=0).
556 Currently, only DRBD8 supports diskless activation (therefore we
557 return 0), for all other we keep the previous semantics and return
561 if self.dev_type == constants.LD_DRBD8:
565 def IsBasedOnDiskType(self, dev_type):
566 """Check if the disk or its children are based on the given type.
568 @type dev_type: L{constants.LDS_BLOCK}
569 @param dev_type: the type to look for
571 @return: boolean indicating if a device of the given type was found or not
575 for child in self.children:
576 if child.IsBasedOnDiskType(dev_type):
578 return self.dev_type == dev_type
580 def GetNodes(self, node):
581 """This function returns the nodes this device lives on.
583 Given the node on which the parent of the device lives on (or, in
584 case of a top-level device, the primary node of the devices'
585 instance), this function will return a list of nodes on which this
586 devices needs to (or can) be assembled.
589 if self.dev_type in [constants.LD_LV, constants.LD_FILE,
590 constants.LD_BLOCKDEV, constants.LD_RBD,
593 elif self.dev_type in constants.LDS_DRBD:
594 result = [self.logical_id[0], self.logical_id[1]]
595 if node not in result:
596 raise errors.ConfigurationError("DRBD device passed unknown node")
598 raise errors.ProgrammerError("Unhandled device type %s" % self.dev_type)
601 def ComputeNodeTree(self, parent_node):
602 """Compute the node/disk tree for this disk and its children.
604 This method, given the node on which the parent disk lives, will
605 return the list of all (node, disk) pairs which describe the disk
606 tree in the most compact way. For example, a drbd/lvm stack
607 will be returned as (primary_node, drbd) and (secondary_node, drbd)
608 which represents all the top-level devices on the nodes.
611 my_nodes = self.GetNodes(parent_node)
612 result = [(node, self) for node in my_nodes]
613 if not self.children:
616 for node in my_nodes:
617 for child in self.children:
618 child_result = child.ComputeNodeTree(node)
619 if len(child_result) == 1:
620 # child (and all its descendants) is simple, doesn't split
621 # over multiple hosts, so we don't need to describe it, our
622 # own entry for this node describes it completely
625 # check if child nodes differ from my nodes; note that
626 # subdisk can differ from the child itself, and be instead
627 # one of its descendants
628 for subnode, subdisk in child_result:
629 if subnode not in my_nodes:
630 result.append((subnode, subdisk))
631 # otherwise child is under our own node, so we ignore this
632 # entry (but probably the other results in the list will
636 def ComputeGrowth(self, amount):
637 """Compute the per-VG growth requirements.
639 This only works for VG-based disks.
641 @type amount: integer
642 @param amount: the desired increase in (user-visible) disk space
644 @return: a dictionary of volume-groups and the required size
647 if self.dev_type == constants.LD_LV:
648 return {self.logical_id[0]: amount}
649 elif self.dev_type == constants.LD_DRBD8:
651 return self.children[0].ComputeGrowth(amount)
655 # Other disk types do not require VG space
658 def RecordGrow(self, amount):
659 """Update the size of this disk after growth.
661 This method recurses over the disks's children and updates their
662 size correspondigly. The method needs to be kept in sync with the
663 actual algorithms from bdev.
666 if self.dev_type in (constants.LD_LV, constants.LD_FILE,
667 constants.LD_RBD, constants.LD_EXT):
669 elif self.dev_type == constants.LD_DRBD8:
671 self.children[0].RecordGrow(amount)
674 raise errors.ProgrammerError("Disk.RecordGrow called for unsupported"
675 " disk type %s" % self.dev_type)
677 def Update(self, size=None, mode=None):
678 """Apply changes to size and mode.
681 if self.dev_type == constants.LD_DRBD8:
683 self.children[0].Update(size=size, mode=mode)
685 assert not self.children
693 """Sets recursively the size to zero for the disk and its children.
697 for child in self.children:
701 def SetPhysicalID(self, target_node, nodes_ip):
702 """Convert the logical ID to the physical ID.
704 This is used only for drbd, which needs ip/port configuration.
706 The routine descends down and updates its children also, because
707 this helps when the only the top device is passed to the remote
711 - target_node: the node we wish to configure for
712 - nodes_ip: a mapping of node name to ip
714 The target_node must exist in in nodes_ip, and must be one of the
715 nodes in the logical ID for each of the DRBD devices encountered
720 for child in self.children:
721 child.SetPhysicalID(target_node, nodes_ip)
723 if self.logical_id is None and self.physical_id is not None:
725 if self.dev_type in constants.LDS_DRBD:
726 pnode, snode, port, pminor, sminor, secret = self.logical_id
727 if target_node not in (pnode, snode):
728 raise errors.ConfigurationError("DRBD device not knowing node %s" %
730 pnode_ip = nodes_ip.get(pnode, None)
731 snode_ip = nodes_ip.get(snode, None)
732 if pnode_ip is None or snode_ip is None:
733 raise errors.ConfigurationError("Can't find primary or secondary node"
734 " for %s" % str(self))
735 p_data = (pnode_ip, port)
736 s_data = (snode_ip, port)
737 if pnode == target_node:
738 self.physical_id = p_data + s_data + (pminor, secret)
739 else: # it must be secondary, we tested above
740 self.physical_id = s_data + p_data + (sminor, secret)
742 self.physical_id = self.logical_id
746 """Disk-specific conversion to standard python types.
748 This replaces the children lists of objects with lists of
749 standard python types.
752 bo = super(Disk, self).ToDict()
754 for attr in ("children",):
755 alist = bo.get(attr, None)
757 bo[attr] = outils.ContainerToDicts(alist)
761 def FromDict(cls, val):
762 """Custom function for Disks
765 obj = super(Disk, cls).FromDict(val)
767 obj.children = outils.ContainerFromDicts(obj.children, list, Disk)
768 if obj.logical_id and isinstance(obj.logical_id, list):
769 obj.logical_id = tuple(obj.logical_id)
770 if obj.physical_id and isinstance(obj.physical_id, list):
771 obj.physical_id = tuple(obj.physical_id)
772 if obj.dev_type in constants.LDS_DRBD:
773 # we need a tuple of length six here
774 if len(obj.logical_id) < 6:
775 obj.logical_id += (None,) * (6 - len(obj.logical_id))
779 """Custom str() formatter for disks.
782 if self.dev_type == constants.LD_LV:
783 val = "<LogicalVolume(/dev/%s/%s" % self.logical_id
784 elif self.dev_type in constants.LDS_DRBD:
785 node_a, node_b, port, minor_a, minor_b = self.logical_id[:5]
787 if self.physical_id is None:
790 phy = ("configured as %s:%s %s:%s" %
791 (self.physical_id[0], self.physical_id[1],
792 self.physical_id[2], self.physical_id[3]))
794 val += ("hosts=%s/%d-%s/%d, port=%s, %s, " %
795 (node_a, minor_a, node_b, minor_b, port, phy))
796 if self.children and self.children.count(None) == 0:
797 val += "backend=%s, metadev=%s" % (self.children[0], self.children[1])
799 val += "no local storage"
801 val = ("<Disk(type=%s, logical_id=%s, physical_id=%s, children=%s" %
802 (self.dev_type, self.logical_id, self.physical_id, self.children))
803 if self.iv_name is None:
804 val += ", not visible"
806 val += ", visible as /dev/%s" % self.iv_name
807 if isinstance(self.size, int):
808 val += ", size=%dm)>" % self.size
810 val += ", size='%s')>" % (self.size,)
814 """Checks that this disk is correctly configured.
818 if self.mode not in constants.DISK_ACCESS_SET:
819 all_errors.append("Disk access mode '%s' is invalid" % (self.mode, ))
822 def UpgradeConfig(self):
823 """Fill defaults for missing configuration values.
827 for child in self.children:
828 child.UpgradeConfig()
830 # FIXME: Make this configurable in Ganeti 2.7
832 # add here config upgrade for this disk
835 def ComputeLDParams(disk_template, disk_params):
836 """Computes Logical Disk parameters from Disk Template parameters.
838 @type disk_template: string
839 @param disk_template: disk template, one of L{constants.DISK_TEMPLATES}
840 @type disk_params: dict
841 @param disk_params: disk template parameters;
842 dict(template_name -> parameters
844 @return: a list of dicts, one for each node of the disk hierarchy. Each dict
845 contains the LD parameters of the node. The tree is flattened in-order.
848 if disk_template not in constants.DISK_TEMPLATES:
849 raise errors.ProgrammerError("Unknown disk template %s" % disk_template)
851 assert disk_template in disk_params
854 dt_params = disk_params[disk_template]
855 if disk_template == constants.DT_DRBD8:
856 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_DRBD8], {
857 constants.LDP_RESYNC_RATE: dt_params[constants.DRBD_RESYNC_RATE],
858 constants.LDP_BARRIERS: dt_params[constants.DRBD_DISK_BARRIERS],
859 constants.LDP_NO_META_FLUSH: dt_params[constants.DRBD_META_BARRIERS],
860 constants.LDP_DEFAULT_METAVG: dt_params[constants.DRBD_DEFAULT_METAVG],
861 constants.LDP_DISK_CUSTOM: dt_params[constants.DRBD_DISK_CUSTOM],
862 constants.LDP_NET_CUSTOM: dt_params[constants.DRBD_NET_CUSTOM],
863 constants.LDP_DYNAMIC_RESYNC: dt_params[constants.DRBD_DYNAMIC_RESYNC],
864 constants.LDP_PLAN_AHEAD: dt_params[constants.DRBD_PLAN_AHEAD],
865 constants.LDP_FILL_TARGET: dt_params[constants.DRBD_FILL_TARGET],
866 constants.LDP_DELAY_TARGET: dt_params[constants.DRBD_DELAY_TARGET],
867 constants.LDP_MAX_RATE: dt_params[constants.DRBD_MAX_RATE],
868 constants.LDP_MIN_RATE: dt_params[constants.DRBD_MIN_RATE],
872 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
873 constants.LDP_STRIPES: dt_params[constants.DRBD_DATA_STRIPES],
877 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
878 constants.LDP_STRIPES: dt_params[constants.DRBD_META_STRIPES],
881 elif disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
882 result.append(constants.DISK_LD_DEFAULTS[constants.LD_FILE])
884 elif disk_template == constants.DT_PLAIN:
885 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_LV], {
886 constants.LDP_STRIPES: dt_params[constants.LV_STRIPES],
889 elif disk_template == constants.DT_BLOCK:
890 result.append(constants.DISK_LD_DEFAULTS[constants.LD_BLOCKDEV])
892 elif disk_template == constants.DT_RBD:
893 result.append(FillDict(constants.DISK_LD_DEFAULTS[constants.LD_RBD], {
894 constants.LDP_POOL: dt_params[constants.RBD_POOL],
897 elif disk_template == constants.DT_EXT:
898 result.append(constants.DISK_LD_DEFAULTS[constants.LD_EXT])
903 class InstancePolicy(ConfigObject):
904 """Config object representing instance policy limits dictionary.
906 Note that this object is not actually used in the config, it's just
907 used as a placeholder for a few functions.
911 def CheckParameterSyntax(cls, ipolicy, check_std):
912 """ Check the instance policy for validity.
915 @param ipolicy: dictionary with min/max/std specs and policies
916 @type check_std: bool
917 @param check_std: Whether to check std value or just assume compliance
918 @raise errors.ConfigurationError: when the policy is not legal
921 InstancePolicy.CheckISpecSyntax(ipolicy, check_std)
922 if constants.IPOLICY_DTS in ipolicy:
923 InstancePolicy.CheckDiskTemplates(ipolicy[constants.IPOLICY_DTS])
924 for key in constants.IPOLICY_PARAMETERS:
926 InstancePolicy.CheckParameter(key, ipolicy[key])
927 wrong_keys = frozenset(ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
929 raise errors.ConfigurationError("Invalid keys in ipolicy: %s" %
930 utils.CommaJoin(wrong_keys))
933 def _CheckIncompleteSpec(cls, spec, keyname):
934 missing_params = constants.ISPECS_PARAMETERS - frozenset(spec.keys())
936 msg = ("Missing instance specs parameters for %s: %s" %
937 (keyname, utils.CommaJoin(missing_params)))
938 raise errors.ConfigurationError(msg)
941 def CheckISpecSyntax(cls, ipolicy, check_std):
942 """Check the instance policy specs for validity.
945 @param ipolicy: dictionary with min/max/std specs
946 @type check_std: bool
947 @param check_std: Whether to check std value or just assume compliance
948 @raise errors.ConfigurationError: when specs are not valid
951 if constants.ISPECS_MINMAX not in ipolicy:
955 if check_std and constants.ISPECS_STD not in ipolicy:
956 msg = "Missing key in ipolicy: %s" % constants.ISPECS_STD
957 raise errors.ConfigurationError(msg)
958 stdspec = ipolicy.get(constants.ISPECS_STD)
960 InstancePolicy._CheckIncompleteSpec(stdspec, constants.ISPECS_STD)
962 if not ipolicy[constants.ISPECS_MINMAX]:
963 raise errors.ConfigurationError("Empty minmax specifications")
965 for minmaxspecs in ipolicy[constants.ISPECS_MINMAX]:
966 missing = constants.ISPECS_MINMAX_KEYS - frozenset(minmaxspecs.keys())
968 msg = "Missing instance specification: %s" % utils.CommaJoin(missing)
969 raise errors.ConfigurationError(msg)
970 for (key, spec) in minmaxspecs.items():
971 InstancePolicy._CheckIncompleteSpec(spec, key)
974 for param in constants.ISPECS_PARAMETERS:
975 par_std_ok = InstancePolicy._CheckISpecParamSyntax(minmaxspecs, stdspec,
977 spec_std_ok = spec_std_ok and par_std_ok
978 std_is_good = std_is_good or spec_std_ok
980 raise errors.ConfigurationError("Invalid std specifications")
983 def _CheckISpecParamSyntax(cls, minmaxspecs, stdspec, name, check_std):
984 """Check the instance policy specs for validity on a given key.
986 We check if the instance specs makes sense for a given key, that is
987 if minmaxspecs[min][name] <= stdspec[name] <= minmaxspec[max][name].
989 @type minmaxspecs: dict
990 @param minmaxspecs: dictionary with min and max instance spec
992 @param stdspec: dictionary with standard instance spec
994 @param name: what are the limits for
995 @type check_std: bool
996 @param check_std: Whether to check std value or just assume compliance
998 @return: C{True} when specs are valid, C{False} when standard spec for the
999 given name is not valid
1000 @raise errors.ConfigurationError: when min/max specs for the given name
1004 minspec = minmaxspecs[constants.ISPECS_MIN]
1005 maxspec = minmaxspecs[constants.ISPECS_MAX]
1006 min_v = minspec[name]
1007 max_v = maxspec[name]
1010 err = ("Invalid specification of min/max values for %s: %s/%s" %
1011 (name, min_v, max_v))
1012 raise errors.ConfigurationError(err)
1014 std_v = stdspec.get(name, min_v)
1015 return std_v >= min_v and std_v <= max_v
1020 def CheckDiskTemplates(cls, disk_templates):
1021 """Checks the disk templates for validity.
1024 if not disk_templates:
1025 raise errors.ConfigurationError("Instance policy must contain" +
1026 " at least one disk template")
1027 wrong = frozenset(disk_templates).difference(constants.DISK_TEMPLATES)
1029 raise errors.ConfigurationError("Invalid disk template(s) %s" %
1030 utils.CommaJoin(wrong))
1033 def CheckParameter(cls, key, value):
1034 """Checks a parameter.
1036 Currently we expect all parameters to be float values.
1041 except (TypeError, ValueError), err:
1042 raise errors.ConfigurationError("Invalid value for key" " '%s':"
1043 " '%s', error: %s" % (key, value, err))
1046 class Instance(TaggableObject):
1047 """Config object representing an instance."""
1062 ] + _TIMESTAMPS + _UUID
1064 def _ComputeSecondaryNodes(self):
1065 """Compute the list of secondary nodes.
1067 This is a simple wrapper over _ComputeAllNodes.
1070 all_nodes = set(self._ComputeAllNodes())
1071 all_nodes.discard(self.primary_node)
1072 return tuple(all_nodes)
1074 secondary_nodes = property(_ComputeSecondaryNodes, None, None,
1075 "List of names of secondary nodes")
1077 def _ComputeAllNodes(self):
1078 """Compute the list of all nodes.
1080 Since the data is already there (in the drbd disks), keeping it as
1081 a separate normal attribute is redundant and if not properly
1082 synchronised can cause problems. Thus it's better to compute it
1086 def _Helper(nodes, device):
1087 """Recursively computes nodes given a top device."""
1088 if device.dev_type in constants.LDS_DRBD:
1089 nodea, nodeb = device.logical_id[:2]
1093 for child in device.children:
1094 _Helper(nodes, child)
1097 all_nodes.add(self.primary_node)
1098 for device in self.disks:
1099 _Helper(all_nodes, device)
1100 return tuple(all_nodes)
1102 all_nodes = property(_ComputeAllNodes, None, None,
1103 "List of names of all the nodes of the instance")
1105 def MapLVsByNode(self, lvmap=None, devs=None, node=None):
1106 """Provide a mapping of nodes to LVs this instance owns.
1108 This function figures out what logical volumes should belong on
1109 which nodes, recursing through a device tree.
1111 @param lvmap: optional dictionary to receive the
1112 'node' : ['lv', ...] data.
1114 @return: None if lvmap arg is given, otherwise, a dictionary of
1115 the form { 'nodename' : ['volume1', 'volume2', ...], ... };
1116 volumeN is of the form "vg_name/lv_name", compatible with
1121 node = self.primary_node
1129 if not node in lvmap:
1137 if dev.dev_type == constants.LD_LV:
1138 lvmap[node].append(dev.logical_id[0] + "/" + dev.logical_id[1])
1140 elif dev.dev_type in constants.LDS_DRBD:
1142 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[0])
1143 self.MapLVsByNode(lvmap, dev.children, dev.logical_id[1])
1146 self.MapLVsByNode(lvmap, dev.children, node)
1150 def FindDisk(self, idx):
1151 """Find a disk given having a specified index.
1153 This is just a wrapper that does validation of the index.
1156 @param idx: the disk index
1158 @return: the corresponding disk
1159 @raise errors.OpPrereqError: when the given index is not valid
1164 return self.disks[idx]
1165 except (TypeError, ValueError), err:
1166 raise errors.OpPrereqError("Invalid disk index: '%s'" % str(err),
1169 raise errors.OpPrereqError("Invalid disk index: %d (instace has disks"
1170 " 0 to %d" % (idx, len(self.disks) - 1),
1174 """Instance-specific conversion to standard python types.
1176 This replaces the children lists of objects with lists of standard
1180 bo = super(Instance, self).ToDict()
1182 for attr in "nics", "disks":
1183 alist = bo.get(attr, None)
1185 nlist = outils.ContainerToDicts(alist)
1192 def FromDict(cls, val):
1193 """Custom function for instances.
1196 if "admin_state" not in val:
1197 if val.get("admin_up", False):
1198 val["admin_state"] = constants.ADMINST_UP
1200 val["admin_state"] = constants.ADMINST_DOWN
1201 if "admin_up" in val:
1203 obj = super(Instance, cls).FromDict(val)
1204 obj.nics = outils.ContainerFromDicts(obj.nics, list, NIC)
1205 obj.disks = outils.ContainerFromDicts(obj.disks, list, Disk)
1208 def UpgradeConfig(self):
1209 """Fill defaults for missing configuration values.
1212 for nic in self.nics:
1214 for disk in self.disks:
1215 disk.UpgradeConfig()
1217 for key in constants.HVC_GLOBALS:
1219 del self.hvparams[key]
1222 if self.osparams is None:
1224 UpgradeBeParams(self.beparams)
1227 class OS(ConfigObject):
1228 """Config object representing an operating system.
1230 @type supported_parameters: list
1231 @ivar supported_parameters: a list of tuples, name and description,
1232 containing the supported parameters by this OS
1234 @type VARIANT_DELIM: string
1235 @cvar VARIANT_DELIM: the variant delimiter
1247 "supported_variants",
1248 "supported_parameters",
1254 def SplitNameVariant(cls, name):
1255 """Splits the name into the proper name and variant.
1257 @param name: the OS (unprocessed) name
1259 @return: a list of two elements; if the original name didn't
1260 contain a variant, it's returned as an empty string
1263 nv = name.split(cls.VARIANT_DELIM, 1)
1269 def GetName(cls, name):
1270 """Returns the proper name of the os (without the variant).
1272 @param name: the OS (unprocessed) name
1275 return cls.SplitNameVariant(name)[0]
1278 def GetVariant(cls, name):
1279 """Returns the variant the os (without the base name).
1281 @param name: the OS (unprocessed) name
1284 return cls.SplitNameVariant(name)[1]
1287 class ExtStorage(ConfigObject):
1288 """Config object representing an External Storage Provider.
1301 "supported_parameters",
1305 class NodeHvState(ConfigObject):
1306 """Hypvervisor state on a node.
1308 @ivar mem_total: Total amount of memory
1309 @ivar mem_node: Memory used by, or reserved for, the node itself (not always
1311 @ivar mem_hv: Memory used by hypervisor or lost due to instance allocation
1313 @ivar mem_inst: Memory used by instances living on node
1314 @ivar cpu_total: Total node CPU core count
1315 @ivar cpu_node: Number of CPU cores reserved for the node itself
1328 class NodeDiskState(ConfigObject):
1329 """Disk state on a node.
1339 class Node(TaggableObject):
1340 """Config object representing a node.
1342 @ivar hv_state: Hypervisor state (e.g. number of CPUs)
1343 @ivar hv_state_static: Hypervisor state overriden by user
1344 @ivar disk_state: Disk state (e.g. free space)
1345 @ivar disk_state_static: Disk state overriden by user
1364 "disk_state_static",
1365 ] + _TIMESTAMPS + _UUID
1367 def UpgradeConfig(self):
1368 """Fill defaults for missing configuration values.
1371 # pylint: disable=E0203
1372 # because these are "defined" via slots, not manually
1373 if self.master_capable is None:
1374 self.master_capable = True
1376 if self.vm_capable is None:
1377 self.vm_capable = True
1379 if self.ndparams is None:
1381 # And remove any global parameter
1382 for key in constants.NDC_GLOBALS:
1383 if key in self.ndparams:
1384 logging.warning("Ignoring %s node parameter for node %s",
1386 del self.ndparams[key]
1388 if self.powered is None:
1392 """Custom function for serializing.
1395 data = super(Node, self).ToDict()
1397 hv_state = data.get("hv_state", None)
1398 if hv_state is not None:
1399 data["hv_state"] = outils.ContainerToDicts(hv_state)
1401 disk_state = data.get("disk_state", None)
1402 if disk_state is not None:
1403 data["disk_state"] = \
1404 dict((key, outils.ContainerToDicts(value))
1405 for (key, value) in disk_state.items())
1410 def FromDict(cls, val):
1411 """Custom function for deserializing.
1414 obj = super(Node, cls).FromDict(val)
1416 if obj.hv_state is not None:
1418 outils.ContainerFromDicts(obj.hv_state, dict, NodeHvState)
1420 if obj.disk_state is not None:
1422 dict((key, outils.ContainerFromDicts(value, dict, NodeDiskState))
1423 for (key, value) in obj.disk_state.items())
1428 class NodeGroup(TaggableObject):
1429 """Config object representing a node group."""
1438 "disk_state_static",
1441 ] + _TIMESTAMPS + _UUID
1444 """Custom function for nodegroup.
1446 This discards the members object, which gets recalculated and is only kept
1450 mydict = super(NodeGroup, self).ToDict()
1451 del mydict["members"]
1455 def FromDict(cls, val):
1456 """Custom function for nodegroup.
1458 The members slot is initialized to an empty list, upon deserialization.
1461 obj = super(NodeGroup, cls).FromDict(val)
1465 def UpgradeConfig(self):
1466 """Fill defaults for missing configuration values.
1469 if self.ndparams is None:
1472 if self.serial_no is None:
1475 if self.alloc_policy is None:
1476 self.alloc_policy = constants.ALLOC_POLICY_PREFERRED
1478 # We only update mtime, and not ctime, since we would not be able
1479 # to provide a correct value for creation time.
1480 if self.mtime is None:
1481 self.mtime = time.time()
1483 if self.diskparams is None:
1484 self.diskparams = {}
1485 if self.ipolicy is None:
1486 self.ipolicy = MakeEmptyIPolicy()
1488 if self.networks is None:
1491 def FillND(self, node):
1492 """Return filled out ndparams for L{objects.Node}
1494 @type node: L{objects.Node}
1495 @param node: A Node object to fill
1496 @return a copy of the node's ndparams with defaults filled
1499 return self.SimpleFillND(node.ndparams)
1501 def SimpleFillND(self, ndparams):
1502 """Fill a given ndparams dict with defaults.
1504 @type ndparams: dict
1505 @param ndparams: the dict to fill
1507 @return: a copy of the passed in ndparams with missing keys filled
1508 from the node group defaults
1511 return FillDict(self.ndparams, ndparams)
1514 class Cluster(TaggableObject):
1515 """Config object representing the cluster."""
1519 "highest_used_port",
1522 "volume_group_name",
1524 "drbd_usermode_helper",
1526 "default_hypervisor",
1531 "use_external_mip_script",
1534 "shared_file_storage_dir",
1535 "enabled_hypervisors",
1544 "candidate_pool_size",
1547 "maintain_node_health",
1549 "default_iallocator",
1552 "primary_ip_family",
1553 "prealloc_wipe_disks",
1555 "disk_state_static",
1556 "enabled_disk_templates",
1557 ] + _TIMESTAMPS + _UUID
1559 def UpgradeConfig(self):
1560 """Fill defaults for missing configuration values.
1563 # pylint: disable=E0203
1564 # because these are "defined" via slots, not manually
1565 if self.hvparams is None:
1566 self.hvparams = constants.HVC_DEFAULTS
1568 for hypervisor in self.hvparams:
1569 self.hvparams[hypervisor] = FillDict(
1570 constants.HVC_DEFAULTS[hypervisor], self.hvparams[hypervisor])
1572 if self.os_hvp is None:
1575 # osparams added before 2.2
1576 if self.osparams is None:
1579 self.ndparams = UpgradeNDParams(self.ndparams)
1581 self.beparams = UpgradeGroupedParams(self.beparams,
1582 constants.BEC_DEFAULTS)
1583 for beparams_group in self.beparams:
1584 UpgradeBeParams(self.beparams[beparams_group])
1586 migrate_default_bridge = not self.nicparams
1587 self.nicparams = UpgradeGroupedParams(self.nicparams,
1588 constants.NICC_DEFAULTS)
1589 if migrate_default_bridge:
1590 self.nicparams[constants.PP_DEFAULT][constants.NIC_LINK] = \
1593 if self.modify_etc_hosts is None:
1594 self.modify_etc_hosts = True
1596 if self.modify_ssh_setup is None:
1597 self.modify_ssh_setup = True
1599 # default_bridge is no longer used in 2.1. The slot is left there to
1600 # support auto-upgrading. It can be removed once we decide to deprecate
1601 # upgrading straight from 2.0.
1602 if self.default_bridge is not None:
1603 self.default_bridge = None
1605 # default_hypervisor is just the first enabled one in 2.1. This slot and
1606 # code can be removed once upgrading straight from 2.0 is deprecated.
1607 if self.default_hypervisor is not None:
1608 self.enabled_hypervisors = ([self.default_hypervisor] +
1609 [hvname for hvname in self.enabled_hypervisors
1610 if hvname != self.default_hypervisor])
1611 self.default_hypervisor = None
1613 # maintain_node_health added after 2.1.1
1614 if self.maintain_node_health is None:
1615 self.maintain_node_health = False
1617 if self.uid_pool is None:
1620 if self.default_iallocator is None:
1621 self.default_iallocator = ""
1623 # reserved_lvs added before 2.2
1624 if self.reserved_lvs is None:
1625 self.reserved_lvs = []
1627 # hidden and blacklisted operating systems added before 2.2.1
1628 if self.hidden_os is None:
1631 if self.blacklisted_os is None:
1632 self.blacklisted_os = []
1634 # primary_ip_family added before 2.3
1635 if self.primary_ip_family is None:
1636 self.primary_ip_family = AF_INET
1638 if self.master_netmask is None:
1639 ipcls = netutils.IPAddress.GetClassFromIpFamily(self.primary_ip_family)
1640 self.master_netmask = ipcls.iplen
1642 if self.prealloc_wipe_disks is None:
1643 self.prealloc_wipe_disks = False
1645 # shared_file_storage_dir added before 2.5
1646 if self.shared_file_storage_dir is None:
1647 self.shared_file_storage_dir = ""
1649 if self.use_external_mip_script is None:
1650 self.use_external_mip_script = False
1653 self.diskparams = UpgradeDiskParams(self.diskparams)
1655 self.diskparams = constants.DISK_DT_DEFAULTS.copy()
1657 # instance policy added before 2.6
1658 if self.ipolicy is None:
1659 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, {})
1661 # we can either make sure to upgrade the ipolicy always, or only
1662 # do it in some corner cases (e.g. missing keys); note that this
1663 # will break any removal of keys from the ipolicy dict
1664 wrongkeys = frozenset(self.ipolicy.keys()) - constants.IPOLICY_ALL_KEYS
1666 # These keys would be silently removed by FillIPolicy()
1667 msg = ("Cluster instance policy contains spurious keys: %s" %
1668 utils.CommaJoin(wrongkeys))
1669 raise errors.ConfigurationError(msg)
1670 self.ipolicy = FillIPolicy(constants.IPOLICY_DEFAULTS, self.ipolicy)
1673 def primary_hypervisor(self):
1674 """The first hypervisor is the primary.
1676 Useful, for example, for L{Node}'s hv/disk state.
1679 return self.enabled_hypervisors[0]
1682 """Custom function for cluster.
1685 mydict = super(Cluster, self).ToDict()
1687 if self.tcpudp_port_pool is None:
1688 tcpudp_port_pool = []
1690 tcpudp_port_pool = list(self.tcpudp_port_pool)
1692 mydict["tcpudp_port_pool"] = tcpudp_port_pool
1697 def FromDict(cls, val):
1698 """Custom function for cluster.
1701 obj = super(Cluster, cls).FromDict(val)
1703 if obj.tcpudp_port_pool is None:
1704 obj.tcpudp_port_pool = set()
1705 elif not isinstance(obj.tcpudp_port_pool, set):
1706 obj.tcpudp_port_pool = set(obj.tcpudp_port_pool)
1710 def SimpleFillDP(self, diskparams):
1711 """Fill a given diskparams dict with cluster defaults.
1713 @param diskparams: The diskparams
1714 @return: The defaults dict
1717 return FillDiskParams(self.diskparams, diskparams)
1719 def GetHVDefaults(self, hypervisor, os_name=None, skip_keys=None):
1720 """Get the default hypervisor parameters for the cluster.
1722 @param hypervisor: the hypervisor name
1723 @param os_name: if specified, we'll also update the defaults for this OS
1724 @param skip_keys: if passed, list of keys not to use
1725 @return: the defaults dict
1728 if skip_keys is None:
1731 fill_stack = [self.hvparams.get(hypervisor, {})]
1732 if os_name is not None:
1733 os_hvp = self.os_hvp.get(os_name, {}).get(hypervisor, {})
1734 fill_stack.append(os_hvp)
1737 for o_dict in fill_stack:
1738 ret_dict = FillDict(ret_dict, o_dict, skip_keys=skip_keys)
1742 def SimpleFillHV(self, hv_name, os_name, hvparams, skip_globals=False):
1743 """Fill a given hvparams dict with cluster defaults.
1745 @type hv_name: string
1746 @param hv_name: the hypervisor to use
1747 @type os_name: string
1748 @param os_name: the OS to use for overriding the hypervisor defaults
1749 @type skip_globals: boolean
1750 @param skip_globals: if True, the global hypervisor parameters will
1753 @return: a copy of the given hvparams with missing keys filled from
1754 the cluster defaults
1758 skip_keys = constants.HVC_GLOBALS
1762 def_dict = self.GetHVDefaults(hv_name, os_name, skip_keys=skip_keys)
1763 return FillDict(def_dict, hvparams, skip_keys=skip_keys)
1765 def FillHV(self, instance, skip_globals=False):
1766 """Fill an instance's hvparams dict with cluster defaults.
1768 @type instance: L{objects.Instance}
1769 @param instance: the instance parameter to fill
1770 @type skip_globals: boolean
1771 @param skip_globals: if True, the global hypervisor parameters will
1774 @return: a copy of the instance's hvparams with missing keys filled from
1775 the cluster defaults
1778 return self.SimpleFillHV(instance.hypervisor, instance.os,
1779 instance.hvparams, skip_globals)
1781 def SimpleFillBE(self, beparams):
1782 """Fill a given beparams dict with cluster defaults.
1784 @type beparams: dict
1785 @param beparams: the dict to fill
1787 @return: a copy of the passed in beparams with missing keys filled
1788 from the cluster defaults
1791 return FillDict(self.beparams.get(constants.PP_DEFAULT, {}), beparams)
1793 def FillBE(self, instance):
1794 """Fill an instance's beparams dict with cluster defaults.
1796 @type instance: L{objects.Instance}
1797 @param instance: the instance parameter to fill
1799 @return: a copy of the instance's beparams with missing keys filled from
1800 the cluster defaults
1803 return self.SimpleFillBE(instance.beparams)
1805 def SimpleFillNIC(self, nicparams):
1806 """Fill a given nicparams dict with cluster defaults.
1808 @type nicparams: dict
1809 @param nicparams: the dict to fill
1811 @return: a copy of the passed in nicparams with missing keys filled
1812 from the cluster defaults
1815 return FillDict(self.nicparams.get(constants.PP_DEFAULT, {}), nicparams)
1817 def SimpleFillOS(self, os_name, os_params):
1818 """Fill an instance's osparams dict with cluster defaults.
1820 @type os_name: string
1821 @param os_name: the OS name to use
1822 @type os_params: dict
1823 @param os_params: the dict to fill with default values
1825 @return: a copy of the instance's osparams with missing keys filled from
1826 the cluster defaults
1829 name_only = os_name.split("+", 1)[0]
1831 result = self.osparams.get(name_only, {})
1833 result = FillDict(result, self.osparams.get(os_name, {}))
1835 return FillDict(result, os_params)
1838 def SimpleFillHvState(hv_state):
1839 """Fill an hv_state sub dict with cluster defaults.
1842 return FillDict(constants.HVST_DEFAULTS, hv_state)
1845 def SimpleFillDiskState(disk_state):
1846 """Fill an disk_state sub dict with cluster defaults.
1849 return FillDict(constants.DS_DEFAULTS, disk_state)
1851 def FillND(self, node, nodegroup):
1852 """Return filled out ndparams for L{objects.NodeGroup} and L{objects.Node}
1854 @type node: L{objects.Node}
1855 @param node: A Node object to fill
1856 @type nodegroup: L{objects.NodeGroup}
1857 @param nodegroup: A Node object to fill
1858 @return a copy of the node's ndparams with defaults filled
1861 return self.SimpleFillND(nodegroup.FillND(node))
1863 def SimpleFillND(self, ndparams):
1864 """Fill a given ndparams dict with defaults.
1866 @type ndparams: dict
1867 @param ndparams: the dict to fill
1869 @return: a copy of the passed in ndparams with missing keys filled
1870 from the cluster defaults
1873 return FillDict(self.ndparams, ndparams)
1875 def SimpleFillIPolicy(self, ipolicy):
1876 """ Fill instance policy dict with defaults.
1879 @param ipolicy: the dict to fill
1881 @return: a copy of passed ipolicy with missing keys filled from
1882 the cluster defaults
1885 return FillIPolicy(self.ipolicy, ipolicy)
1888 class BlockDevStatus(ConfigObject):
1889 """Config object representing the status of a block device."""
1901 class ImportExportStatus(ConfigObject):
1902 """Config object representing the status of an import or export."""
1908 "progress_throughput",
1916 class ImportExportOptions(ConfigObject):
1917 """Options for import/export daemon
1919 @ivar key_name: X509 key name (None for cluster certificate)
1920 @ivar ca_pem: Remote peer CA in PEM format (None for cluster certificate)
1921 @ivar compress: Compression method (one of L{constants.IEC_ALL})
1922 @ivar magic: Used to ensure the connection goes to the right disk
1923 @ivar ipv6: Whether to use IPv6
1924 @ivar connect_timeout: Number of seconds for establishing connection
1937 class ConfdRequest(ConfigObject):
1938 """Object holding a confd request.
1940 @ivar protocol: confd protocol version
1941 @ivar type: confd query type
1942 @ivar query: query request
1943 @ivar rsalt: requested reply salt
1954 class ConfdReply(ConfigObject):
1955 """Object holding a confd reply.
1957 @ivar protocol: confd protocol version
1958 @ivar status: reply status code (ok, error)
1959 @ivar answer: confd query reply
1960 @ivar serial: configuration serial number
1971 class QueryFieldDefinition(ConfigObject):
1972 """Object holding a query field definition.
1974 @ivar name: Field name
1975 @ivar title: Human-readable title
1976 @ivar kind: Field type
1977 @ivar doc: Human-readable description
1988 class _QueryResponseBase(ConfigObject):
1994 """Custom function for serializing.
1997 mydict = super(_QueryResponseBase, self).ToDict()
1998 mydict["fields"] = outils.ContainerToDicts(mydict["fields"])
2002 def FromDict(cls, val):
2003 """Custom function for de-serializing.
2006 obj = super(_QueryResponseBase, cls).FromDict(val)
2008 outils.ContainerFromDicts(obj.fields, list, QueryFieldDefinition)
2012 class QueryResponse(_QueryResponseBase):
2013 """Object holding the response to a query.
2015 @ivar fields: List of L{QueryFieldDefinition} objects
2016 @ivar data: Requested data
2024 class QueryFieldsRequest(ConfigObject):
2025 """Object holding a request for querying available fields.
2034 class QueryFieldsResponse(_QueryResponseBase):
2035 """Object holding the response to a query for fields.
2037 @ivar fields: List of L{QueryFieldDefinition} objects
2043 class MigrationStatus(ConfigObject):
2044 """Object holding the status of a migration.
2054 class InstanceConsole(ConfigObject):
2055 """Object describing how to access the console of an instance.
2070 """Validates contents of this object.
2073 assert self.kind in constants.CONS_ALL, "Unknown console type"
2074 assert self.instance, "Missing instance name"
2075 assert self.message or self.kind in [constants.CONS_SSH,
2076 constants.CONS_SPICE,
2078 assert self.host or self.kind == constants.CONS_MESSAGE
2079 assert self.port or self.kind in [constants.CONS_MESSAGE,
2081 assert self.user or self.kind in [constants.CONS_MESSAGE,
2082 constants.CONS_SPICE,
2084 assert self.command or self.kind in [constants.CONS_MESSAGE,
2085 constants.CONS_SPICE,
2087 assert self.display or self.kind in [constants.CONS_MESSAGE,
2088 constants.CONS_SPICE,
2093 class Network(TaggableObject):
2094 """Object representing a network definition for ganeti.
2107 ] + _TIMESTAMPS + _UUID
2109 def HooksDict(self, prefix=""):
2110 """Export a dictionary used by hooks with a network's information.
2112 @type prefix: String
2113 @param prefix: Prefix to prepend to the dict entries
2117 "%sNETWORK_NAME" % prefix: self.name,
2118 "%sNETWORK_UUID" % prefix: self.uuid,
2119 "%sNETWORK_TAGS" % prefix: " ".join(self.GetTags()),
2122 result["%sNETWORK_SUBNET" % prefix] = self.network
2124 result["%sNETWORK_GATEWAY" % prefix] = self.gateway
2126 result["%sNETWORK_SUBNET6" % prefix] = self.network6
2128 result["%sNETWORK_GATEWAY6" % prefix] = self.gateway6
2130 result["%sNETWORK_MAC_PREFIX" % prefix] = self.mac_prefix
2135 def FromDict(cls, val):
2136 """Custom function for networks.
2138 Remove deprecated network_type and family.
2141 if "network_type" in val:
2142 del val["network_type"]
2145 obj = super(Network, cls).FromDict(val)
2149 class SerializableConfigParser(ConfigParser.SafeConfigParser):
2150 """Simple wrapper over ConfigParse that allows serialization.
2152 This class is basically ConfigParser.SafeConfigParser with two
2153 additional methods that allow it to serialize/unserialize to/from a
2158 """Dump this instance and return the string representation."""
2161 return buf.getvalue()
2164 def Loads(cls, data):
2165 """Load data from a string."""
2166 buf = StringIO(data)
2172 class LvmPvInfo(ConfigObject):
2173 """Information about an LVM physical volume (PV).
2176 @ivar name: name of the PV
2177 @type vg_name: string
2178 @ivar vg_name: name of the volume group containing the PV
2180 @ivar size: size of the PV in MiB
2182 @ivar free: free space in the PV, in MiB
2183 @type attributes: string
2184 @ivar attributes: PV attributes
2185 @type lv_list: list of strings
2186 @ivar lv_list: names of the LVs hosted on the PV
2198 """Is this PV empty?
2201 return self.size <= (self.free + 1)
2203 def IsAllocatable(self):
2204 """Is this PV allocatable?
2207 return ("a" in self.attributes)