4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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 """Configuration management for Ganeti
24 This module provides the interface to the Ganeti cluster configuration.
26 The configuration data is stored on every node but is updated on the master
27 only. After each update, the master distributes the data to the other nodes.
29 Currently, the data storage format is JSON. YAML was slow and consuming too
34 # pylint: disable-msg=R0904
35 # R0904: Too many public methods
43 from ganeti import errors
44 from ganeti import locking
45 from ganeti import utils
46 from ganeti import constants
47 from ganeti import rpc
48 from ganeti import objects
49 from ganeti import serializer
50 from ganeti import uidpool
51 from ganeti import netutils
52 from ganeti import runtime
55 _config_lock = locking.SharedLock("ConfigWriter")
57 # job id used for resource management at config upgrade time
58 _UPGRADE_CONFIG_JID = "jid-cfg-upgrade"
61 def _ValidateConfig(data):
62 """Verifies that a configuration objects looks valid.
64 This only verifies the version of the configuration.
66 @raise errors.ConfigurationError: if the version differs from what
70 if data.version != constants.CONFIG_VERSION:
71 raise errors.ConfigVersionMismatch(constants.CONFIG_VERSION, data.version)
74 class TemporaryReservationManager:
75 """A temporary resource reservation manager.
77 This is used to reserve resources in a job, before using them, making sure
78 other jobs cannot get them in the meantime.
82 self._ec_reserved = {}
84 def Reserved(self, resource):
85 for holder_reserved in self._ec_reserved.values():
86 if resource in holder_reserved:
90 def Reserve(self, ec_id, resource):
91 if self.Reserved(resource):
92 raise errors.ReservationError("Duplicate reservation for resource '%s'"
94 if ec_id not in self._ec_reserved:
95 self._ec_reserved[ec_id] = set([resource])
97 self._ec_reserved[ec_id].add(resource)
99 def DropECReservations(self, ec_id):
100 if ec_id in self._ec_reserved:
101 del self._ec_reserved[ec_id]
103 def GetReserved(self):
105 for holder_reserved in self._ec_reserved.values():
106 all_reserved.update(holder_reserved)
109 def Generate(self, existing, generate_one_fn, ec_id):
110 """Generate a new resource of this type
113 assert callable(generate_one_fn)
115 all_elems = self.GetReserved()
116 all_elems.update(existing)
119 new_resource = generate_one_fn()
120 if new_resource is not None and new_resource not in all_elems:
123 raise errors.ConfigurationError("Not able generate new resource"
124 " (last tried: %s)" % new_resource)
125 self.Reserve(ec_id, new_resource)
130 """The interface to the cluster configuration.
132 @ivar _temporary_lvs: reservation manager for temporary LVs
133 @ivar _all_rms: a list of all temporary reservation managers
136 def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts,
137 accept_foreign=False):
139 self._lock = _config_lock
140 self._config_data = None
141 self._offline = offline
143 self._cfg_file = constants.CLUSTER_CONF_FILE
145 self._cfg_file = cfg_file
146 self._getents = _getents
147 self._temporary_ids = TemporaryReservationManager()
148 self._temporary_drbds = {}
149 self._temporary_macs = TemporaryReservationManager()
150 self._temporary_secrets = TemporaryReservationManager()
151 self._temporary_lvs = TemporaryReservationManager()
152 self._all_rms = [self._temporary_ids, self._temporary_macs,
153 self._temporary_secrets, self._temporary_lvs]
154 # Note: in order to prevent errors when resolving our name in
155 # _DistributeConfig, we compute it here once and reuse it; it's
156 # better to raise an error before starting to modify the config
157 # file than after it was modified
158 self._my_hostname = netutils.Hostname.GetSysName()
159 self._last_cluster_serial = -1
161 self._OpenConfig(accept_foreign)
163 # this method needs to be static, so that we can call it on the class
166 """Check if the cluster is configured.
169 return os.path.exists(constants.CLUSTER_CONF_FILE)
171 def _GenerateOneMAC(self):
172 """Generate one mac address
175 prefix = self._config_data.cluster.mac_prefix
176 byte1 = random.randrange(0, 256)
177 byte2 = random.randrange(0, 256)
178 byte3 = random.randrange(0, 256)
179 mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
182 @locking.ssynchronized(_config_lock, shared=1)
183 def GetNdParams(self, node):
184 """Get the node params populated with cluster defaults.
186 @type node: L{object.Node}
187 @param node: The node we want to know the params for
188 @return: A dict with the filled in node params
191 nodegroup = self._UnlockedGetNodeGroup(node.group)
192 return self._config_data.cluster.FillND(node, nodegroup)
194 @locking.ssynchronized(_config_lock, shared=1)
195 def GenerateMAC(self, ec_id):
196 """Generate a MAC for an instance.
198 This should check the current instances for duplicates.
201 existing = self._AllMACs()
202 return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
204 @locking.ssynchronized(_config_lock, shared=1)
205 def ReserveMAC(self, mac, ec_id):
206 """Reserve a MAC for an instance.
208 This only checks instances managed by this cluster, it does not
209 check for potential collisions elsewhere.
212 all_macs = self._AllMACs()
214 raise errors.ReservationError("mac already in use")
216 self._temporary_macs.Reserve(ec_id, mac)
218 @locking.ssynchronized(_config_lock, shared=1)
219 def ReserveLV(self, lv_name, ec_id):
220 """Reserve an VG/LV pair for an instance.
222 @type lv_name: string
223 @param lv_name: the logical volume name to reserve
226 all_lvs = self._AllLVs()
227 if lv_name in all_lvs:
228 raise errors.ReservationError("LV already in use")
230 self._temporary_lvs.Reserve(ec_id, lv_name)
232 @locking.ssynchronized(_config_lock, shared=1)
233 def GenerateDRBDSecret(self, ec_id):
234 """Generate a DRBD secret.
236 This checks the current disks for duplicates.
239 return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
240 utils.GenerateSecret,
244 """Compute the list of all LVs.
248 for instance in self._config_data.instances.values():
249 node_data = instance.MapLVsByNode()
250 for lv_list in node_data.values():
251 lvnames.update(lv_list)
254 def _AllIDs(self, include_temporary):
255 """Compute the list of all UUIDs and names we have.
257 @type include_temporary: boolean
258 @param include_temporary: whether to include the _temporary_ids set
260 @return: a set of IDs
264 if include_temporary:
265 existing.update(self._temporary_ids.GetReserved())
266 existing.update(self._AllLVs())
267 existing.update(self._config_data.instances.keys())
268 existing.update(self._config_data.nodes.keys())
269 existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
272 def _GenerateUniqueID(self, ec_id):
273 """Generate an unique UUID.
275 This checks the current node, instances and disk names for
279 @return: the unique id
282 existing = self._AllIDs(include_temporary=False)
283 return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
285 @locking.ssynchronized(_config_lock, shared=1)
286 def GenerateUniqueID(self, ec_id):
287 """Generate an unique ID.
289 This is just a wrapper over the unlocked version.
292 @param ec_id: unique id for the job to reserve the id to
295 return self._GenerateUniqueID(ec_id)
298 """Return all MACs present in the config.
301 @return: the list of all MACs
305 for instance in self._config_data.instances.values():
306 for nic in instance.nics:
307 result.append(nic.mac)
311 def _AllDRBDSecrets(self):
312 """Return all DRBD secrets present in the config.
315 @return: the list of all DRBD secrets
318 def helper(disk, result):
319 """Recursively gather secrets from this disk."""
320 if disk.dev_type == constants.DT_DRBD8:
321 result.append(disk.logical_id[5])
323 for child in disk.children:
324 helper(child, result)
327 for instance in self._config_data.instances.values():
328 for disk in instance.disks:
333 def _CheckDiskIDs(self, disk, l_ids, p_ids):
334 """Compute duplicate disk IDs
336 @type disk: L{objects.Disk}
337 @param disk: the disk at which to start searching
339 @param l_ids: list of current logical ids
341 @param p_ids: list of current physical ids
343 @return: a list of error messages
347 if disk.logical_id is not None:
348 if disk.logical_id in l_ids:
349 result.append("duplicate logical id %s" % str(disk.logical_id))
351 l_ids.append(disk.logical_id)
352 if disk.physical_id is not None:
353 if disk.physical_id in p_ids:
354 result.append("duplicate physical id %s" % str(disk.physical_id))
356 p_ids.append(disk.physical_id)
359 for child in disk.children:
360 result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
363 def _UnlockedVerifyConfig(self):
367 @return: a list of error messages; a non-empty list signifies
371 # pylint: disable-msg=R0914
375 data = self._config_data
376 cluster = data.cluster
380 # global cluster checks
381 if not cluster.enabled_hypervisors:
382 result.append("enabled hypervisors list doesn't have any entries")
383 invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
385 result.append("enabled hypervisors contains invalid entries: %s" %
387 missing_hvp = (set(cluster.enabled_hypervisors) -
388 set(cluster.hvparams.keys()))
390 result.append("hypervisor parameters missing for the enabled"
391 " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
393 if cluster.master_node not in data.nodes:
394 result.append("cluster has invalid primary node '%s'" %
397 def _helper(owner, attr, value, template):
399 utils.ForceDictType(value, template)
400 except errors.GenericError, err:
401 result.append("%s has invalid %s: %s" % (owner, attr, err))
403 def _helper_nic(owner, params):
405 objects.NIC.CheckParameterSyntax(params)
406 except errors.ConfigurationError, err:
407 result.append("%s has invalid nicparams: %s" % (owner, err))
409 # check cluster parameters
410 _helper("cluster", "beparams", cluster.SimpleFillBE({}),
411 constants.BES_PARAMETER_TYPES)
412 _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
413 constants.NICS_PARAMETER_TYPES)
414 _helper_nic("cluster", cluster.SimpleFillNIC({}))
415 _helper("cluster", "ndparams", cluster.SimpleFillND({}),
416 constants.NDS_PARAMETER_TYPES)
418 # per-instance checks
419 for instance_name in data.instances:
420 instance = data.instances[instance_name]
421 if instance.name != instance_name:
422 result.append("instance '%s' is indexed by wrong name '%s'" %
423 (instance.name, instance_name))
424 if instance.primary_node not in data.nodes:
425 result.append("instance '%s' has invalid primary node '%s'" %
426 (instance_name, instance.primary_node))
427 for snode in instance.secondary_nodes:
428 if snode not in data.nodes:
429 result.append("instance '%s' has invalid secondary node '%s'" %
430 (instance_name, snode))
431 for idx, nic in enumerate(instance.nics):
432 if nic.mac in seen_macs:
433 result.append("instance '%s' has NIC %d mac %s duplicate" %
434 (instance_name, idx, nic.mac))
436 seen_macs.append(nic.mac)
438 filled = cluster.SimpleFillNIC(nic.nicparams)
439 owner = "instance %s nic %d" % (instance.name, idx)
440 _helper(owner, "nicparams",
441 filled, constants.NICS_PARAMETER_TYPES)
442 _helper_nic(owner, filled)
445 if instance.beparams:
446 _helper("instance %s" % instance.name, "beparams",
447 cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
449 # gather the drbd ports for duplicate checks
450 for dsk in instance.disks:
451 if dsk.dev_type in constants.LDS_DRBD:
452 tcp_port = dsk.logical_id[2]
453 if tcp_port not in ports:
455 ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
456 # gather network port reservation
457 net_port = getattr(instance, "network_port", None)
458 if net_port is not None:
459 if net_port not in ports:
461 ports[net_port].append((instance.name, "network port"))
463 # instance disk verify
464 for idx, disk in enumerate(instance.disks):
465 result.extend(["instance '%s' disk %d error: %s" %
466 (instance.name, idx, msg) for msg in disk.Verify()])
467 result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
469 # cluster-wide pool of free ports
470 for free_port in cluster.tcpudp_port_pool:
471 if free_port not in ports:
472 ports[free_port] = []
473 ports[free_port].append(("cluster", "port marked as free"))
475 # compute tcp/udp duplicate ports
481 txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
482 result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
484 # highest used tcp port check
486 if keys[-1] > cluster.highest_used_port:
487 result.append("Highest used port mismatch, saved %s, computed %s" %
488 (cluster.highest_used_port, keys[-1]))
490 if not data.nodes[cluster.master_node].master_candidate:
491 result.append("Master node is not a master candidate")
493 # master candidate checks
494 mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
496 result.append("Not enough master candidates: actual %d, target %d" %
500 for node_name, node in data.nodes.items():
501 if node.name != node_name:
502 result.append("Node '%s' is indexed by wrong name '%s'" %
503 (node.name, node_name))
504 if [node.master_candidate, node.drained, node.offline].count(True) > 1:
505 result.append("Node %s state is invalid: master_candidate=%s,"
506 " drain=%s, offline=%s" %
507 (node.name, node.master_candidate, node.drained,
509 if node.group not in data.nodegroups:
510 result.append("Node '%s' has invalid group '%s'" %
511 (node.name, node.group))
513 _helper("node %s" % node.name, "ndparams",
514 cluster.FillND(node, data.nodegroups[node.group]),
515 constants.NDS_PARAMETER_TYPES)
518 nodegroups_names = set()
519 for nodegroup_uuid in data.nodegroups:
520 nodegroup = data.nodegroups[nodegroup_uuid]
521 if nodegroup.uuid != nodegroup_uuid:
522 result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
523 % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
524 if utils.UUID_RE.match(nodegroup.name.lower()):
525 result.append("node group '%s' (uuid: '%s') has uuid-like name" %
526 (nodegroup.name, nodegroup.uuid))
527 if nodegroup.name in nodegroups_names:
528 result.append("duplicate node group name '%s'" % nodegroup.name)
530 nodegroups_names.add(nodegroup.name)
531 if nodegroup.ndparams:
532 _helper("group %s" % nodegroup.name, "ndparams",
533 cluster.SimpleFillND(nodegroup.ndparams),
534 constants.NDS_PARAMETER_TYPES)
538 _, duplicates = self._UnlockedComputeDRBDMap()
539 for node, minor, instance_a, instance_b in duplicates:
540 result.append("DRBD minor %d on node %s is assigned twice to instances"
541 " %s and %s" % (minor, node, instance_a, instance_b))
544 default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
547 def _AddIpAddress(ip, name):
548 ips.setdefault(ip, []).append(name)
550 _AddIpAddress(cluster.master_ip, "cluster_ip")
552 for node in data.nodes.values():
553 _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
554 if node.secondary_ip != node.primary_ip:
555 _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
557 for instance in data.instances.values():
558 for idx, nic in enumerate(instance.nics):
562 nicparams = objects.FillDict(default_nicparams, nic.nicparams)
563 nic_mode = nicparams[constants.NIC_MODE]
564 nic_link = nicparams[constants.NIC_LINK]
566 if nic_mode == constants.NIC_MODE_BRIDGED:
567 link = "bridge:%s" % nic_link
568 elif nic_mode == constants.NIC_MODE_ROUTED:
569 link = "route:%s" % nic_link
571 raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
573 _AddIpAddress("%s/%s" % (link, nic.ip),
574 "instance:%s/nic:%d" % (instance.name, idx))
576 for ip, owners in ips.items():
578 result.append("IP address %s is used by multiple owners: %s" %
579 (ip, utils.CommaJoin(owners)))
583 @locking.ssynchronized(_config_lock, shared=1)
584 def VerifyConfig(self):
587 This is just a wrapper over L{_UnlockedVerifyConfig}.
590 @return: a list of error messages; a non-empty list signifies
594 return self._UnlockedVerifyConfig()
596 def _UnlockedSetDiskID(self, disk, node_name):
597 """Convert the unique ID to the ID needed on the target nodes.
599 This is used only for drbd, which needs ip/port configuration.
601 The routine descends down and updates its children also, because
602 this helps when the only the top device is passed to the remote
605 This function is for internal use, when the config lock is already held.
609 for child in disk.children:
610 self._UnlockedSetDiskID(child, node_name)
612 if disk.logical_id is None and disk.physical_id is not None:
614 if disk.dev_type == constants.LD_DRBD8:
615 pnode, snode, port, pminor, sminor, secret = disk.logical_id
616 if node_name not in (pnode, snode):
617 raise errors.ConfigurationError("DRBD device not knowing node %s" %
619 pnode_info = self._UnlockedGetNodeInfo(pnode)
620 snode_info = self._UnlockedGetNodeInfo(snode)
621 if pnode_info is None or snode_info is None:
622 raise errors.ConfigurationError("Can't find primary or secondary node"
623 " for %s" % str(disk))
624 p_data = (pnode_info.secondary_ip, port)
625 s_data = (snode_info.secondary_ip, port)
626 if pnode == node_name:
627 disk.physical_id = p_data + s_data + (pminor, secret)
628 else: # it must be secondary, we tested above
629 disk.physical_id = s_data + p_data + (sminor, secret)
631 disk.physical_id = disk.logical_id
634 @locking.ssynchronized(_config_lock)
635 def SetDiskID(self, disk, node_name):
636 """Convert the unique ID to the ID needed on the target nodes.
638 This is used only for drbd, which needs ip/port configuration.
640 The routine descends down and updates its children also, because
641 this helps when the only the top device is passed to the remote
645 return self._UnlockedSetDiskID(disk, node_name)
647 @locking.ssynchronized(_config_lock)
648 def AddTcpUdpPort(self, port):
649 """Adds a new port to the available port pool.
652 if not isinstance(port, int):
653 raise errors.ProgrammerError("Invalid type passed for port")
655 self._config_data.cluster.tcpudp_port_pool.add(port)
658 @locking.ssynchronized(_config_lock, shared=1)
659 def GetPortList(self):
660 """Returns a copy of the current port list.
663 return self._config_data.cluster.tcpudp_port_pool.copy()
665 @locking.ssynchronized(_config_lock)
666 def AllocatePort(self):
669 The port will be taken from the available port pool or from the
670 default port range (and in this case we increase
674 # If there are TCP/IP ports configured, we use them first.
675 if self._config_data.cluster.tcpudp_port_pool:
676 port = self._config_data.cluster.tcpudp_port_pool.pop()
678 port = self._config_data.cluster.highest_used_port + 1
679 if port >= constants.LAST_DRBD_PORT:
680 raise errors.ConfigurationError("The highest used port is greater"
681 " than %s. Aborting." %
682 constants.LAST_DRBD_PORT)
683 self._config_data.cluster.highest_used_port = port
688 def _UnlockedComputeDRBDMap(self):
689 """Compute the used DRBD minor/nodes.
692 @return: dictionary of node_name: dict of minor: instance_name;
693 the returned dict will have all the nodes in it (even if with
694 an empty list), and a list of duplicates; if the duplicates
695 list is not empty, the configuration is corrupted and its caller
696 should raise an exception
699 def _AppendUsedPorts(instance_name, disk, used):
701 if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
702 node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
703 for node, port in ((node_a, minor_a), (node_b, minor_b)):
704 assert node in used, ("Node '%s' of instance '%s' not found"
705 " in node list" % (node, instance_name))
706 if port in used[node]:
707 duplicates.append((node, port, instance_name, used[node][port]))
709 used[node][port] = instance_name
711 for child in disk.children:
712 duplicates.extend(_AppendUsedPorts(instance_name, child, used))
716 my_dict = dict((node, {}) for node in self._config_data.nodes)
717 for instance in self._config_data.instances.itervalues():
718 for disk in instance.disks:
719 duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
720 for (node, minor), instance in self._temporary_drbds.iteritems():
721 if minor in my_dict[node] and my_dict[node][minor] != instance:
722 duplicates.append((node, minor, instance, my_dict[node][minor]))
724 my_dict[node][minor] = instance
725 return my_dict, duplicates
727 @locking.ssynchronized(_config_lock)
728 def ComputeDRBDMap(self):
729 """Compute the used DRBD minor/nodes.
731 This is just a wrapper over L{_UnlockedComputeDRBDMap}.
733 @return: dictionary of node_name: dict of minor: instance_name;
734 the returned dict will have all the nodes in it (even if with
738 d_map, duplicates = self._UnlockedComputeDRBDMap()
740 raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
744 @locking.ssynchronized(_config_lock)
745 def AllocateDRBDMinor(self, nodes, instance):
746 """Allocate a drbd minor.
748 The free minor will be automatically computed from the existing
749 devices. A node can be given multiple times in order to allocate
750 multiple minors. The result is the list of minors, in the same
751 order as the passed nodes.
753 @type instance: string
754 @param instance: the instance for which we allocate minors
757 assert isinstance(instance, basestring), \
758 "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
760 d_map, duplicates = self._UnlockedComputeDRBDMap()
762 raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
768 # no minors used, we can start at 0
771 self._temporary_drbds[(nname, 0)] = instance
775 ffree = utils.FirstFree(keys)
777 # return the next minor
778 # TODO: implement high-limit check
782 # double-check minor against current instances
783 assert minor not in d_map[nname], \
784 ("Attempt to reuse allocated DRBD minor %d on node %s,"
785 " already allocated to instance %s" %
786 (minor, nname, d_map[nname][minor]))
787 ndata[minor] = instance
788 # double-check minor against reservation
789 r_key = (nname, minor)
790 assert r_key not in self._temporary_drbds, \
791 ("Attempt to reuse reserved DRBD minor %d on node %s,"
792 " reserved for instance %s" %
793 (minor, nname, self._temporary_drbds[r_key]))
794 self._temporary_drbds[r_key] = instance
796 logging.debug("Request to allocate drbd minors, input: %s, returning %s",
800 def _UnlockedReleaseDRBDMinors(self, instance):
801 """Release temporary drbd minors allocated for a given instance.
803 @type instance: string
804 @param instance: the instance for which temporary minors should be
808 assert isinstance(instance, basestring), \
809 "Invalid argument passed to ReleaseDRBDMinors"
810 for key, name in self._temporary_drbds.items():
812 del self._temporary_drbds[key]
814 @locking.ssynchronized(_config_lock)
815 def ReleaseDRBDMinors(self, instance):
816 """Release temporary drbd minors allocated for a given instance.
818 This should be called on the error paths, on the success paths
819 it's automatically called by the ConfigWriter add and update
822 This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
824 @type instance: string
825 @param instance: the instance for which temporary minors should be
829 self._UnlockedReleaseDRBDMinors(instance)
831 @locking.ssynchronized(_config_lock, shared=1)
832 def GetConfigVersion(self):
833 """Get the configuration version.
835 @return: Config version
838 return self._config_data.version
840 @locking.ssynchronized(_config_lock, shared=1)
841 def GetClusterName(self):
844 @return: Cluster name
847 return self._config_data.cluster.cluster_name
849 @locking.ssynchronized(_config_lock, shared=1)
850 def GetMasterNode(self):
851 """Get the hostname of the master node for this cluster.
853 @return: Master hostname
856 return self._config_data.cluster.master_node
858 @locking.ssynchronized(_config_lock, shared=1)
859 def GetMasterIP(self):
860 """Get the IP of the master node for this cluster.
865 return self._config_data.cluster.master_ip
867 @locking.ssynchronized(_config_lock, shared=1)
868 def GetMasterNetdev(self):
869 """Get the master network device for this cluster.
872 return self._config_data.cluster.master_netdev
874 @locking.ssynchronized(_config_lock, shared=1)
875 def GetFileStorageDir(self):
876 """Get the file storage dir for this cluster.
879 return self._config_data.cluster.file_storage_dir
881 @locking.ssynchronized(_config_lock, shared=1)
882 def GetHypervisorType(self):
883 """Get the hypervisor type for this cluster.
886 return self._config_data.cluster.enabled_hypervisors[0]
888 @locking.ssynchronized(_config_lock, shared=1)
889 def GetHostKey(self):
890 """Return the rsa hostkey from the config.
893 @return: the rsa hostkey
896 return self._config_data.cluster.rsahostkeypub
898 @locking.ssynchronized(_config_lock, shared=1)
899 def GetDefaultIAllocator(self):
900 """Get the default instance allocator for this cluster.
903 return self._config_data.cluster.default_iallocator
905 @locking.ssynchronized(_config_lock, shared=1)
906 def GetPrimaryIPFamily(self):
907 """Get cluster primary ip family.
909 @return: primary ip family
912 return self._config_data.cluster.primary_ip_family
914 @locking.ssynchronized(_config_lock)
915 def AddNodeGroup(self, group, ec_id, check_uuid=True):
916 """Add a node group to the configuration.
918 This method calls group.UpgradeConfig() to fill any missing attributes
919 according to their default values.
921 @type group: L{objects.NodeGroup}
922 @param group: the NodeGroup object to add
924 @param ec_id: unique id for the job to use when creating a missing UUID
925 @type check_uuid: bool
926 @param check_uuid: add an UUID to the group if it doesn't have one or, if
927 it does, ensure that it does not exist in the
928 configuration already
931 self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
934 def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
935 """Add a node group to the configuration.
938 logging.info("Adding node group %s to configuration", group.name)
940 # Some code might need to add a node group with a pre-populated UUID
941 # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
942 # the "does this UUID" exist already check.
944 self._EnsureUUID(group, ec_id)
947 existing_uuid = self._UnlockedLookupNodeGroup(group.name)
948 except errors.OpPrereqError:
951 raise errors.OpPrereqError("Desired group name '%s' already exists as a"
952 " node group (UUID: %s)" %
953 (group.name, existing_uuid),
957 group.ctime = group.mtime = time.time()
958 group.UpgradeConfig()
960 self._config_data.nodegroups[group.uuid] = group
961 self._config_data.cluster.serial_no += 1
963 @locking.ssynchronized(_config_lock)
964 def RemoveNodeGroup(self, group_uuid):
965 """Remove a node group from the configuration.
967 @type group_uuid: string
968 @param group_uuid: the UUID of the node group to remove
971 logging.info("Removing node group %s from configuration", group_uuid)
973 if group_uuid not in self._config_data.nodegroups:
974 raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
976 assert len(self._config_data.nodegroups) != 1, \
977 "Group '%s' is the only group, cannot be removed" % group_uuid
979 del self._config_data.nodegroups[group_uuid]
980 self._config_data.cluster.serial_no += 1
983 def _UnlockedLookupNodeGroup(self, target):
984 """Lookup a node group's UUID.
986 @type target: string or None
987 @param target: group name or UUID or None to look for the default
989 @return: nodegroup UUID
990 @raises errors.OpPrereqError: when the target group cannot be found
994 if len(self._config_data.nodegroups) != 1:
995 raise errors.OpPrereqError("More than one node group exists. Target"
996 " group must be specified explicitely.")
998 return self._config_data.nodegroups.keys()[0]
999 if target in self._config_data.nodegroups:
1001 for nodegroup in self._config_data.nodegroups.values():
1002 if nodegroup.name == target:
1003 return nodegroup.uuid
1004 raise errors.OpPrereqError("Node group '%s' not found" % target,
1007 @locking.ssynchronized(_config_lock, shared=1)
1008 def LookupNodeGroup(self, target):
1009 """Lookup a node group's UUID.
1011 This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1013 @type target: string or None
1014 @param target: group name or UUID or None to look for the default
1016 @return: nodegroup UUID
1019 return self._UnlockedLookupNodeGroup(target)
1021 def _UnlockedGetNodeGroup(self, uuid):
1022 """Lookup a node group.
1025 @param uuid: group UUID
1026 @rtype: L{objects.NodeGroup} or None
1027 @return: nodegroup object, or None if not found
1030 if uuid not in self._config_data.nodegroups:
1033 return self._config_data.nodegroups[uuid]
1035 @locking.ssynchronized(_config_lock, shared=1)
1036 def GetNodeGroup(self, uuid):
1037 """Lookup a node group.
1040 @param uuid: group UUID
1041 @rtype: L{objects.NodeGroup} or None
1042 @return: nodegroup object, or None if not found
1045 return self._UnlockedGetNodeGroup(uuid)
1047 @locking.ssynchronized(_config_lock, shared=1)
1048 def GetAllNodeGroupsInfo(self):
1049 """Get the configuration of all node groups.
1052 return dict(self._config_data.nodegroups)
1054 @locking.ssynchronized(_config_lock, shared=1)
1055 def GetNodeGroupList(self):
1056 """Get a list of node groups.
1059 return self._config_data.nodegroups.keys()
1061 @locking.ssynchronized(_config_lock)
1062 def AddInstance(self, instance, ec_id):
1063 """Add an instance to the config.
1065 This should be used after creating a new instance.
1067 @type instance: L{objects.Instance}
1068 @param instance: the instance object
1071 if not isinstance(instance, objects.Instance):
1072 raise errors.ProgrammerError("Invalid type passed to AddInstance")
1074 if instance.disk_template != constants.DT_DISKLESS:
1075 all_lvs = instance.MapLVsByNode()
1076 logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1078 all_macs = self._AllMACs()
1079 for nic in instance.nics:
1080 if nic.mac in all_macs:
1081 raise errors.ConfigurationError("Cannot add instance %s:"
1082 " MAC address '%s' already in use." %
1083 (instance.name, nic.mac))
1085 self._EnsureUUID(instance, ec_id)
1087 instance.serial_no = 1
1088 instance.ctime = instance.mtime = time.time()
1089 self._config_data.instances[instance.name] = instance
1090 self._config_data.cluster.serial_no += 1
1091 self._UnlockedReleaseDRBDMinors(instance.name)
1094 def _EnsureUUID(self, item, ec_id):
1095 """Ensures a given object has a valid UUID.
1097 @param item: the instance or node to be checked
1098 @param ec_id: the execution context id for the uuid reservation
1102 item.uuid = self._GenerateUniqueID(ec_id)
1103 elif item.uuid in self._AllIDs(include_temporary=True):
1104 raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1105 " in use" % (item.name, item.uuid))
1107 def _SetInstanceStatus(self, instance_name, status):
1108 """Set the instance's status to a given value.
1111 assert isinstance(status, bool), \
1112 "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1114 if instance_name not in self._config_data.instances:
1115 raise errors.ConfigurationError("Unknown instance '%s'" %
1117 instance = self._config_data.instances[instance_name]
1118 if instance.admin_up != status:
1119 instance.admin_up = status
1120 instance.serial_no += 1
1121 instance.mtime = time.time()
1124 @locking.ssynchronized(_config_lock)
1125 def MarkInstanceUp(self, instance_name):
1126 """Mark the instance status to up in the config.
1129 self._SetInstanceStatus(instance_name, True)
1131 @locking.ssynchronized(_config_lock)
1132 def RemoveInstance(self, instance_name):
1133 """Remove the instance from the configuration.
1136 if instance_name not in self._config_data.instances:
1137 raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1139 # If a network port has been allocated to the instance,
1140 # return it to the pool of free ports.
1141 inst = self._config_data.instances[instance_name]
1142 network_port = getattr(inst, "network_port", None)
1143 if network_port is not None:
1144 self._config_data.cluster.tcpudp_port_pool.add(network_port)
1146 del self._config_data.instances[instance_name]
1147 self._config_data.cluster.serial_no += 1
1150 @locking.ssynchronized(_config_lock)
1151 def RenameInstance(self, old_name, new_name):
1152 """Rename an instance.
1154 This needs to be done in ConfigWriter and not by RemoveInstance
1155 combined with AddInstance as only we can guarantee an atomic
1159 if old_name not in self._config_data.instances:
1160 raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1161 inst = self._config_data.instances[old_name]
1162 del self._config_data.instances[old_name]
1163 inst.name = new_name
1165 for disk in inst.disks:
1166 if disk.dev_type == constants.LD_FILE:
1167 # rename the file paths in logical and physical id
1168 file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1169 disk_fname = "disk%s" % disk.iv_name.split("/")[1]
1170 disk.physical_id = disk.logical_id = (disk.logical_id[0],
1171 utils.PathJoin(file_storage_dir,
1175 # Force update of ssconf files
1176 self._config_data.cluster.serial_no += 1
1178 self._config_data.instances[inst.name] = inst
1181 @locking.ssynchronized(_config_lock)
1182 def MarkInstanceDown(self, instance_name):
1183 """Mark the status of an instance to down in the configuration.
1186 self._SetInstanceStatus(instance_name, False)
1188 def _UnlockedGetInstanceList(self):
1189 """Get the list of instances.
1191 This function is for internal use, when the config lock is already held.
1194 return self._config_data.instances.keys()
1196 @locking.ssynchronized(_config_lock, shared=1)
1197 def GetInstanceList(self):
1198 """Get the list of instances.
1200 @return: array of instances, ex. ['instance2.example.com',
1201 'instance1.example.com']
1204 return self._UnlockedGetInstanceList()
1206 @locking.ssynchronized(_config_lock, shared=1)
1207 def ExpandInstanceName(self, short_name):
1208 """Attempt to expand an incomplete instance name.
1211 return utils.MatchNameComponent(short_name,
1212 self._config_data.instances.keys(),
1213 case_sensitive=False)
1215 def _UnlockedGetInstanceInfo(self, instance_name):
1216 """Returns information about an instance.
1218 This function is for internal use, when the config lock is already held.
1221 if instance_name not in self._config_data.instances:
1224 return self._config_data.instances[instance_name]
1226 @locking.ssynchronized(_config_lock, shared=1)
1227 def GetInstanceInfo(self, instance_name):
1228 """Returns information about an instance.
1230 It takes the information from the configuration file. Other information of
1231 an instance are taken from the live systems.
1233 @param instance_name: name of the instance, e.g.
1234 I{instance1.example.com}
1236 @rtype: L{objects.Instance}
1237 @return: the instance object
1240 return self._UnlockedGetInstanceInfo(instance_name)
1242 @locking.ssynchronized(_config_lock, shared=1)
1243 def GetAllInstancesInfo(self):
1244 """Get the configuration of all instances.
1247 @return: dict of (instance, instance_info), where instance_info is what
1248 would GetInstanceInfo return for the node
1251 my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1252 for instance in self._UnlockedGetInstanceList()])
1255 @locking.ssynchronized(_config_lock)
1256 def AddNode(self, node, ec_id):
1257 """Add a node to the configuration.
1259 @type node: L{objects.Node}
1260 @param node: a Node instance
1263 logging.info("Adding node %s to configuration", node.name)
1265 self._EnsureUUID(node, ec_id)
1268 node.ctime = node.mtime = time.time()
1269 self._UnlockedAddNodeToGroup(node.name, node.group)
1270 self._config_data.nodes[node.name] = node
1271 self._config_data.cluster.serial_no += 1
1274 @locking.ssynchronized(_config_lock)
1275 def RemoveNode(self, node_name):
1276 """Remove a node from the configuration.
1279 logging.info("Removing node %s from configuration", node_name)
1281 if node_name not in self._config_data.nodes:
1282 raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1284 self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1285 del self._config_data.nodes[node_name]
1286 self._config_data.cluster.serial_no += 1
1289 @locking.ssynchronized(_config_lock, shared=1)
1290 def ExpandNodeName(self, short_name):
1291 """Attempt to expand an incomplete instance name.
1294 return utils.MatchNameComponent(short_name,
1295 self._config_data.nodes.keys(),
1296 case_sensitive=False)
1298 def _UnlockedGetNodeInfo(self, node_name):
1299 """Get the configuration of a node, as stored in the config.
1301 This function is for internal use, when the config lock is already
1304 @param node_name: the node name, e.g. I{node1.example.com}
1306 @rtype: L{objects.Node}
1307 @return: the node object
1310 if node_name not in self._config_data.nodes:
1313 return self._config_data.nodes[node_name]
1315 @locking.ssynchronized(_config_lock, shared=1)
1316 def GetNodeInfo(self, node_name):
1317 """Get the configuration of a node, as stored in the config.
1319 This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1321 @param node_name: the node name, e.g. I{node1.example.com}
1323 @rtype: L{objects.Node}
1324 @return: the node object
1327 return self._UnlockedGetNodeInfo(node_name)
1329 @locking.ssynchronized(_config_lock, shared=1)
1330 def GetNodeInstances(self, node_name):
1331 """Get the instances of a node, as stored in the config.
1333 @param node_name: the node name, e.g. I{node1.example.com}
1335 @rtype: (list, list)
1336 @return: a tuple with two lists: the primary and the secondary instances
1341 for inst in self._config_data.instances.values():
1342 if inst.primary_node == node_name:
1343 pri.append(inst.name)
1344 if node_name in inst.secondary_nodes:
1345 sec.append(inst.name)
1348 def _UnlockedGetNodeList(self):
1349 """Return the list of nodes which are in the configuration.
1351 This function is for internal use, when the config lock is already
1357 return self._config_data.nodes.keys()
1359 @locking.ssynchronized(_config_lock, shared=1)
1360 def GetNodeList(self):
1361 """Return the list of nodes which are in the configuration.
1364 return self._UnlockedGetNodeList()
1366 def _UnlockedGetOnlineNodeList(self):
1367 """Return the list of nodes which are online.
1370 all_nodes = [self._UnlockedGetNodeInfo(node)
1371 for node in self._UnlockedGetNodeList()]
1372 return [node.name for node in all_nodes if not node.offline]
1374 @locking.ssynchronized(_config_lock, shared=1)
1375 def GetOnlineNodeList(self):
1376 """Return the list of nodes which are online.
1379 return self._UnlockedGetOnlineNodeList()
1381 @locking.ssynchronized(_config_lock, shared=1)
1382 def GetVmCapableNodeList(self):
1383 """Return the list of nodes which are not vm capable.
1386 all_nodes = [self._UnlockedGetNodeInfo(node)
1387 for node in self._UnlockedGetNodeList()]
1388 return [node.name for node in all_nodes if node.vm_capable]
1390 @locking.ssynchronized(_config_lock, shared=1)
1391 def GetNonVmCapableNodeList(self):
1392 """Return the list of nodes which are not vm capable.
1395 all_nodes = [self._UnlockedGetNodeInfo(node)
1396 for node in self._UnlockedGetNodeList()]
1397 return [node.name for node in all_nodes if not node.vm_capable]
1399 @locking.ssynchronized(_config_lock, shared=1)
1400 def GetAllNodesInfo(self):
1401 """Get the configuration of all nodes.
1404 @return: dict of (node, node_info), where node_info is what
1405 would GetNodeInfo return for the node
1408 my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
1409 for node in self._UnlockedGetNodeList()])
1412 @locking.ssynchronized(_config_lock, shared=1)
1413 def GetNodeGroupsFromNodes(self, nodes):
1414 """Returns groups for a list of nodes.
1416 @type nodes: list of string
1417 @param nodes: List of node names
1421 return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1423 def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1424 """Get the number of current and maximum desired and possible candidates.
1426 @type exceptions: list
1427 @param exceptions: if passed, list of nodes that should be ignored
1429 @return: tuple of (current, desired and possible, possible)
1432 mc_now = mc_should = mc_max = 0
1433 for node in self._config_data.nodes.values():
1434 if exceptions and node.name in exceptions:
1436 if not (node.offline or node.drained) and node.master_capable:
1438 if node.master_candidate:
1440 mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1441 return (mc_now, mc_should, mc_max)
1443 @locking.ssynchronized(_config_lock, shared=1)
1444 def GetMasterCandidateStats(self, exceptions=None):
1445 """Get the number of current and maximum possible candidates.
1447 This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1449 @type exceptions: list
1450 @param exceptions: if passed, list of nodes that should be ignored
1452 @return: tuple of (current, max)
1455 return self._UnlockedGetMasterCandidateStats(exceptions)
1457 @locking.ssynchronized(_config_lock)
1458 def MaintainCandidatePool(self, exceptions):
1459 """Try to grow the candidate pool to the desired size.
1461 @type exceptions: list
1462 @param exceptions: if passed, list of nodes that should be ignored
1464 @return: list with the adjusted nodes (L{objects.Node} instances)
1467 mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1470 node_list = self._config_data.nodes.keys()
1471 random.shuffle(node_list)
1472 for name in node_list:
1473 if mc_now >= mc_max:
1475 node = self._config_data.nodes[name]
1476 if (node.master_candidate or node.offline or node.drained or
1477 node.name in exceptions or not node.master_capable):
1479 mod_list.append(node)
1480 node.master_candidate = True
1483 if mc_now != mc_max:
1484 # this should not happen
1485 logging.warning("Warning: MaintainCandidatePool didn't manage to"
1486 " fill the candidate pool (%d/%d)", mc_now, mc_max)
1488 self._config_data.cluster.serial_no += 1
1493 def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1494 """Add a given node to the specified group.
1497 if nodegroup_uuid not in self._config_data.nodegroups:
1498 # This can happen if a node group gets deleted between its lookup and
1499 # when we're adding the first node to it, since we don't keep a lock in
1500 # the meantime. It's ok though, as we'll fail cleanly if the node group
1501 # is not found anymore.
1502 raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1503 if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1504 self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1506 def _UnlockedRemoveNodeFromGroup(self, node):
1507 """Remove a given node from its group.
1510 nodegroup = node.group
1511 if nodegroup not in self._config_data.nodegroups:
1512 logging.warning("Warning: node '%s' has unknown node group '%s'"
1513 " (while being removed from it)", node.name, nodegroup)
1514 nodegroup_obj = self._config_data.nodegroups[nodegroup]
1515 if node.name not in nodegroup_obj.members:
1516 logging.warning("Warning: node '%s' not a member of its node group '%s'"
1517 " (while being removed from it)", node.name, nodegroup)
1519 nodegroup_obj.members.remove(node.name)
1521 @locking.ssynchronized(_config_lock)
1522 def AssignGroupNodes(self, mods):
1523 """Changes the group of a number of nodes.
1525 @type mods: list of tuples; (node name, new group UUID)
1526 @param mods: Node membership modifications
1529 groups = self._config_data.nodegroups
1530 nodes = self._config_data.nodes
1534 # Try to resolve names/UUIDs first
1535 for (node_name, new_group_uuid) in mods:
1537 node = nodes[node_name]
1539 raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1541 if node.group == new_group_uuid:
1542 # Node is being assigned to its current group
1543 logging.debug("Node '%s' was assigned to its current group (%s)",
1544 node_name, node.group)
1547 # Try to find current group of node
1549 old_group = groups[node.group]
1551 raise errors.ConfigurationError("Unable to find old group '%s'" %
1554 # Try to find new group for node
1556 new_group = groups[new_group_uuid]
1558 raise errors.ConfigurationError("Unable to find new group '%s'" %
1561 assert node.name in old_group.members, \
1562 ("Inconsistent configuration: node '%s' not listed in members for its"
1563 " old group '%s'" % (node.name, old_group.uuid))
1564 assert node.name not in new_group.members, \
1565 ("Inconsistent configuration: node '%s' already listed in members for"
1566 " its new group '%s'" % (node.name, new_group.uuid))
1568 resmod.append((node, old_group, new_group))
1571 for (node, old_group, new_group) in resmod:
1572 assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
1573 "Assigning to current group is not possible"
1575 node.group = new_group.uuid
1577 # Update members of involved groups
1578 if node.name in old_group.members:
1579 old_group.members.remove(node.name)
1580 if node.name not in new_group.members:
1581 new_group.members.append(node.name)
1583 # Update timestamps and serials (only once per node/group object)
1585 for obj in frozenset(itertools.chain(*resmod)): # pylint: disable-msg=W0142
1589 # Force ssconf update
1590 self._config_data.cluster.serial_no += 1
1594 def _BumpSerialNo(self):
1595 """Bump up the serial number of the config.
1598 self._config_data.serial_no += 1
1599 self._config_data.mtime = time.time()
1601 def _AllUUIDObjects(self):
1602 """Returns all objects with uuid attributes.
1605 return (self._config_data.instances.values() +
1606 self._config_data.nodes.values() +
1607 self._config_data.nodegroups.values() +
1608 [self._config_data.cluster])
1610 def _OpenConfig(self, accept_foreign):
1611 """Read the config data from disk.
1614 raw_data = utils.ReadFile(self._cfg_file)
1617 data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1618 except Exception, err:
1619 raise errors.ConfigurationError(err)
1621 # Make sure the configuration has the right version
1622 _ValidateConfig(data)
1624 if (not hasattr(data, 'cluster') or
1625 not hasattr(data.cluster, 'rsahostkeypub')):
1626 raise errors.ConfigurationError("Incomplete configuration"
1627 " (missing cluster.rsahostkeypub)")
1629 if data.cluster.master_node != self._my_hostname and not accept_foreign:
1630 msg = ("The configuration denotes node %s as master, while my"
1631 " hostname is %s; opening a foreign configuration is only"
1632 " possible in accept_foreign mode" %
1633 (data.cluster.master_node, self._my_hostname))
1634 raise errors.ConfigurationError(msg)
1636 # Upgrade configuration if needed
1637 data.UpgradeConfig()
1639 self._config_data = data
1640 # reset the last serial as -1 so that the next write will cause
1642 self._last_cluster_serial = -1
1644 # And finally run our (custom) config upgrade sequence
1645 self._UpgradeConfig()
1647 self._cfg_id = utils.GetFileID(path=self._cfg_file)
1649 def _UpgradeConfig(self):
1650 """Run upgrade steps that cannot be done purely in the objects.
1652 This is because some data elements need uniqueness across the
1653 whole configuration, etc.
1655 @warning: this function will call L{_WriteConfig()}, but also
1656 L{DropECReservations} so it needs to be called only from a
1657 "safe" place (the constructor). If one wanted to call it with
1658 the lock held, a DropECReservationUnlocked would need to be
1659 created first, to avoid causing deadlock.
1663 for item in self._AllUUIDObjects():
1664 if item.uuid is None:
1665 item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1667 if not self._config_data.nodegroups:
1668 default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
1669 default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
1671 self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
1673 for node in self._config_data.nodes.values():
1675 node.group = self.LookupNodeGroup(None)
1677 # This is technically *not* an upgrade, but needs to be done both when
1678 # nodegroups are being added, and upon normally loading the config,
1679 # because the members list of a node group is discarded upon
1680 # serializing/deserializing the object.
1681 self._UnlockedAddNodeToGroup(node.name, node.group)
1684 # This is ok even if it acquires the internal lock, as _UpgradeConfig is
1685 # only called at config init time, without the lock held
1686 self.DropECReservations(_UPGRADE_CONFIG_JID)
1688 def _DistributeConfig(self, feedback_fn):
1689 """Distribute the configuration to the other nodes.
1691 Currently, this only copies the configuration file. In the future,
1692 it could be used to encapsulate the 2/3-phase update mechanism.
1702 myhostname = self._my_hostname
1703 # we can skip checking whether _UnlockedGetNodeInfo returns None
1704 # since the node list comes from _UnlocketGetNodeList, and we are
1705 # called with the lock held, so no modifications should take place
1707 for node_name in self._UnlockedGetNodeList():
1708 if node_name == myhostname:
1710 node_info = self._UnlockedGetNodeInfo(node_name)
1711 if not node_info.master_candidate:
1713 node_list.append(node_info.name)
1714 addr_list.append(node_info.primary_ip)
1716 result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
1717 address_list=addr_list)
1718 for to_node, to_result in result.items():
1719 msg = to_result.fail_msg
1721 msg = ("Copy of file %s to node %s failed: %s" %
1722 (self._cfg_file, to_node, msg))
1732 def _WriteConfig(self, destination=None, feedback_fn=None):
1733 """Write the configuration data to persistent storage.
1736 assert feedback_fn is None or callable(feedback_fn)
1738 # Warn on config errors, but don't abort the save - the
1739 # configuration has already been modified, and we can't revert;
1740 # the best we can do is to warn the user and save as is, leaving
1741 # recovery to the user
1742 config_errors = self._UnlockedVerifyConfig()
1744 errmsg = ("Configuration data is not consistent: %s" %
1745 (utils.CommaJoin(config_errors)))
1746 logging.critical(errmsg)
1750 if destination is None:
1751 destination = self._cfg_file
1752 self._BumpSerialNo()
1753 txt = serializer.Dump(self._config_data.ToDict())
1755 getents = self._getents()
1757 fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
1758 close=False, gid=getents.confd_gid, mode=0640)
1759 except errors.LockError:
1760 raise errors.ConfigurationError("The configuration file has been"
1761 " modified since the last write, cannot"
1764 self._cfg_id = utils.GetFileID(fd=fd)
1768 self.write_count += 1
1770 # and redistribute the config file to master candidates
1771 self._DistributeConfig(feedback_fn)
1773 # Write ssconf files on all nodes (including locally)
1774 if self._last_cluster_serial < self._config_data.cluster.serial_no:
1775 if not self._offline:
1776 result = rpc.RpcRunner.call_write_ssconf_files(
1777 self._UnlockedGetOnlineNodeList(),
1778 self._UnlockedGetSsconfValues())
1780 for nname, nresu in result.items():
1781 msg = nresu.fail_msg
1783 errmsg = ("Error while uploading ssconf files to"
1784 " node %s: %s" % (nname, msg))
1785 logging.warning(errmsg)
1790 self._last_cluster_serial = self._config_data.cluster.serial_no
1792 def _UnlockedGetSsconfValues(self):
1793 """Return the values needed by ssconf.
1796 @return: a dictionary with keys the ssconf names and values their
1801 instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1802 node_names = utils.NiceSort(self._UnlockedGetNodeList())
1803 node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1804 node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
1805 for ninfo in node_info]
1806 node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
1807 for ninfo in node_info]
1809 instance_data = fn(instance_names)
1810 off_data = fn(node.name for node in node_info if node.offline)
1811 on_data = fn(node.name for node in node_info if not node.offline)
1812 mc_data = fn(node.name for node in node_info if node.master_candidate)
1813 mc_ips_data = fn(node.primary_ip for node in node_info
1814 if node.master_candidate)
1815 node_data = fn(node_names)
1816 node_pri_ips_data = fn(node_pri_ips)
1817 node_snd_ips_data = fn(node_snd_ips)
1819 cluster = self._config_data.cluster
1820 cluster_tags = fn(cluster.GetTags())
1822 hypervisor_list = fn(cluster.enabled_hypervisors)
1824 uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
1826 nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
1827 self._config_data.nodegroups.values()]
1828 nodegroups_data = fn(utils.NiceSort(nodegroups))
1831 constants.SS_CLUSTER_NAME: cluster.cluster_name,
1832 constants.SS_CLUSTER_TAGS: cluster_tags,
1833 constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1834 constants.SS_MASTER_CANDIDATES: mc_data,
1835 constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
1836 constants.SS_MASTER_IP: cluster.master_ip,
1837 constants.SS_MASTER_NETDEV: cluster.master_netdev,
1838 constants.SS_MASTER_NODE: cluster.master_node,
1839 constants.SS_NODE_LIST: node_data,
1840 constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
1841 constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
1842 constants.SS_OFFLINE_NODES: off_data,
1843 constants.SS_ONLINE_NODES: on_data,
1844 constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
1845 constants.SS_INSTANCE_LIST: instance_data,
1846 constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1847 constants.SS_HYPERVISOR_LIST: hypervisor_list,
1848 constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
1849 constants.SS_UID_POOL: uid_pool,
1850 constants.SS_NODEGROUPS: nodegroups_data,
1853 @locking.ssynchronized(_config_lock, shared=1)
1854 def GetSsconfValues(self):
1855 """Wrapper using lock around _UnlockedGetSsconf().
1858 return self._UnlockedGetSsconfValues()
1860 @locking.ssynchronized(_config_lock, shared=1)
1861 def GetVGName(self):
1862 """Return the volume group name.
1865 return self._config_data.cluster.volume_group_name
1867 @locking.ssynchronized(_config_lock)
1868 def SetVGName(self, vg_name):
1869 """Set the volume group name.
1872 self._config_data.cluster.volume_group_name = vg_name
1873 self._config_data.cluster.serial_no += 1
1876 @locking.ssynchronized(_config_lock, shared=1)
1877 def GetDRBDHelper(self):
1878 """Return DRBD usermode helper.
1881 return self._config_data.cluster.drbd_usermode_helper
1883 @locking.ssynchronized(_config_lock)
1884 def SetDRBDHelper(self, drbd_helper):
1885 """Set DRBD usermode helper.
1888 self._config_data.cluster.drbd_usermode_helper = drbd_helper
1889 self._config_data.cluster.serial_no += 1
1892 @locking.ssynchronized(_config_lock, shared=1)
1893 def GetMACPrefix(self):
1894 """Return the mac prefix.
1897 return self._config_data.cluster.mac_prefix
1899 @locking.ssynchronized(_config_lock, shared=1)
1900 def GetClusterInfo(self):
1901 """Returns information about the cluster
1903 @rtype: L{objects.Cluster}
1904 @return: the cluster object
1907 return self._config_data.cluster
1909 @locking.ssynchronized(_config_lock, shared=1)
1910 def HasAnyDiskOfType(self, dev_type):
1911 """Check if in there is at disk of the given type in the configuration.
1914 return self._config_data.HasAnyDiskOfType(dev_type)
1916 @locking.ssynchronized(_config_lock)
1917 def Update(self, target, feedback_fn):
1918 """Notify function to be called after updates.
1920 This function must be called when an object (as returned by
1921 GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
1922 caller wants the modifications saved to the backing store. Note
1923 that all modified objects will be saved, but the target argument
1924 is the one the caller wants to ensure that it's saved.
1926 @param target: an instance of either L{objects.Cluster},
1927 L{objects.Node} or L{objects.Instance} which is existing in
1929 @param feedback_fn: Callable feedback function
1932 if self._config_data is None:
1933 raise errors.ProgrammerError("Configuration file not read,"
1935 update_serial = False
1936 if isinstance(target, objects.Cluster):
1937 test = target == self._config_data.cluster
1938 elif isinstance(target, objects.Node):
1939 test = target in self._config_data.nodes.values()
1940 update_serial = True
1941 elif isinstance(target, objects.Instance):
1942 test = target in self._config_data.instances.values()
1943 elif isinstance(target, objects.NodeGroup):
1944 test = target in self._config_data.nodegroups.values()
1946 raise errors.ProgrammerError("Invalid object type (%s) passed to"
1947 " ConfigWriter.Update" % type(target))
1949 raise errors.ConfigurationError("Configuration updated since object"
1950 " has been read or unknown object")
1951 target.serial_no += 1
1952 target.mtime = now = time.time()
1955 # for node updates, we need to increase the cluster serial too
1956 self._config_data.cluster.serial_no += 1
1957 self._config_data.cluster.mtime = now
1959 if isinstance(target, objects.Instance):
1960 self._UnlockedReleaseDRBDMinors(target.name)
1962 self._WriteConfig(feedback_fn=feedback_fn)
1964 @locking.ssynchronized(_config_lock)
1965 def DropECReservations(self, ec_id):
1966 """Drop per-execution-context reservations
1969 for rm in self._all_rms:
1970 rm.DropECReservations(ec_id)