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=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)
129 def _MatchNameComponentIgnoreCase(short_name, names):
130 """Wrapper around L{utils.text.MatchNameComponent}.
133 return utils.MatchNameComponent(short_name, names, case_sensitive=False)
137 """The interface to the cluster configuration.
139 @ivar _temporary_lvs: reservation manager for temporary LVs
140 @ivar _all_rms: a list of all temporary reservation managers
143 def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts,
144 accept_foreign=False):
146 self._lock = _config_lock
147 self._config_data = None
148 self._offline = offline
150 self._cfg_file = constants.CLUSTER_CONF_FILE
152 self._cfg_file = cfg_file
153 self._getents = _getents
154 self._temporary_ids = TemporaryReservationManager()
155 self._temporary_drbds = {}
156 self._temporary_macs = TemporaryReservationManager()
157 self._temporary_secrets = TemporaryReservationManager()
158 self._temporary_lvs = TemporaryReservationManager()
159 self._all_rms = [self._temporary_ids, self._temporary_macs,
160 self._temporary_secrets, self._temporary_lvs]
161 # Note: in order to prevent errors when resolving our name in
162 # _DistributeConfig, we compute it here once and reuse it; it's
163 # better to raise an error before starting to modify the config
164 # file than after it was modified
165 self._my_hostname = netutils.Hostname.GetSysName()
166 self._last_cluster_serial = -1
169 self._OpenConfig(accept_foreign)
171 def _GetRpc(self, address_list):
172 """Returns RPC runner for configuration.
175 return rpc.ConfigRunner(self._context, address_list)
177 def SetContext(self, context):
178 """Sets Ganeti context.
181 self._context = context
183 # this method needs to be static, so that we can call it on the class
186 """Check if the cluster is configured.
189 return os.path.exists(constants.CLUSTER_CONF_FILE)
191 def _GenerateOneMAC(self):
192 """Generate one mac address
195 prefix = self._config_data.cluster.mac_prefix
196 byte1 = random.randrange(0, 256)
197 byte2 = random.randrange(0, 256)
198 byte3 = random.randrange(0, 256)
199 mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
202 @locking.ssynchronized(_config_lock, shared=1)
203 def GetNdParams(self, node):
204 """Get the node params populated with cluster defaults.
206 @type node: L{objects.Node}
207 @param node: The node we want to know the params for
208 @return: A dict with the filled in node params
211 nodegroup = self._UnlockedGetNodeGroup(node.group)
212 return self._config_data.cluster.FillND(node, nodegroup)
214 @locking.ssynchronized(_config_lock, shared=1)
215 def GenerateMAC(self, ec_id):
216 """Generate a MAC for an instance.
218 This should check the current instances for duplicates.
221 existing = self._AllMACs()
222 return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
224 @locking.ssynchronized(_config_lock, shared=1)
225 def ReserveMAC(self, mac, ec_id):
226 """Reserve a MAC for an instance.
228 This only checks instances managed by this cluster, it does not
229 check for potential collisions elsewhere.
232 all_macs = self._AllMACs()
234 raise errors.ReservationError("mac already in use")
236 self._temporary_macs.Reserve(ec_id, mac)
238 @locking.ssynchronized(_config_lock, shared=1)
239 def ReserveLV(self, lv_name, ec_id):
240 """Reserve an VG/LV pair for an instance.
242 @type lv_name: string
243 @param lv_name: the logical volume name to reserve
246 all_lvs = self._AllLVs()
247 if lv_name in all_lvs:
248 raise errors.ReservationError("LV already in use")
250 self._temporary_lvs.Reserve(ec_id, lv_name)
252 @locking.ssynchronized(_config_lock, shared=1)
253 def GenerateDRBDSecret(self, ec_id):
254 """Generate a DRBD secret.
256 This checks the current disks for duplicates.
259 return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
260 utils.GenerateSecret,
264 """Compute the list of all LVs.
268 for instance in self._config_data.instances.values():
269 node_data = instance.MapLVsByNode()
270 for lv_list in node_data.values():
271 lvnames.update(lv_list)
274 def _AllIDs(self, include_temporary):
275 """Compute the list of all UUIDs and names we have.
277 @type include_temporary: boolean
278 @param include_temporary: whether to include the _temporary_ids set
280 @return: a set of IDs
284 if include_temporary:
285 existing.update(self._temporary_ids.GetReserved())
286 existing.update(self._AllLVs())
287 existing.update(self._config_data.instances.keys())
288 existing.update(self._config_data.nodes.keys())
289 existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
292 def _GenerateUniqueID(self, ec_id):
293 """Generate an unique UUID.
295 This checks the current node, instances and disk names for
299 @return: the unique id
302 existing = self._AllIDs(include_temporary=False)
303 return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
305 @locking.ssynchronized(_config_lock, shared=1)
306 def GenerateUniqueID(self, ec_id):
307 """Generate an unique ID.
309 This is just a wrapper over the unlocked version.
312 @param ec_id: unique id for the job to reserve the id to
315 return self._GenerateUniqueID(ec_id)
318 """Return all MACs present in the config.
321 @return: the list of all MACs
325 for instance in self._config_data.instances.values():
326 for nic in instance.nics:
327 result.append(nic.mac)
331 def _AllDRBDSecrets(self):
332 """Return all DRBD secrets present in the config.
335 @return: the list of all DRBD secrets
338 def helper(disk, result):
339 """Recursively gather secrets from this disk."""
340 if disk.dev_type == constants.DT_DRBD8:
341 result.append(disk.logical_id[5])
343 for child in disk.children:
344 helper(child, result)
347 for instance in self._config_data.instances.values():
348 for disk in instance.disks:
353 def _CheckDiskIDs(self, disk, l_ids, p_ids):
354 """Compute duplicate disk IDs
356 @type disk: L{objects.Disk}
357 @param disk: the disk at which to start searching
359 @param l_ids: list of current logical ids
361 @param p_ids: list of current physical ids
363 @return: a list of error messages
367 if disk.logical_id is not None:
368 if disk.logical_id in l_ids:
369 result.append("duplicate logical id %s" % str(disk.logical_id))
371 l_ids.append(disk.logical_id)
372 if disk.physical_id is not None:
373 if disk.physical_id in p_ids:
374 result.append("duplicate physical id %s" % str(disk.physical_id))
376 p_ids.append(disk.physical_id)
379 for child in disk.children:
380 result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
383 def _UnlockedVerifyConfig(self):
387 @return: a list of error messages; a non-empty list signifies
391 # pylint: disable=R0914
395 data = self._config_data
396 cluster = data.cluster
400 # global cluster checks
401 if not cluster.enabled_hypervisors:
402 result.append("enabled hypervisors list doesn't have any entries")
403 invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
405 result.append("enabled hypervisors contains invalid entries: %s" %
407 missing_hvp = (set(cluster.enabled_hypervisors) -
408 set(cluster.hvparams.keys()))
410 result.append("hypervisor parameters missing for the enabled"
411 " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
413 if cluster.master_node not in data.nodes:
414 result.append("cluster has invalid primary node '%s'" %
417 def _helper(owner, attr, value, template):
419 utils.ForceDictType(value, template)
420 except errors.GenericError, err:
421 result.append("%s has invalid %s: %s" % (owner, attr, err))
423 def _helper_nic(owner, params):
425 objects.NIC.CheckParameterSyntax(params)
426 except errors.ConfigurationError, err:
427 result.append("%s has invalid nicparams: %s" % (owner, err))
429 def _helper_ipolicy(owner, params):
431 objects.InstancePolicy.CheckParameterSyntax(params)
432 except errors.ConfigurationError, err:
433 result.append("%s has invalid instance policy: %s" % (owner, err))
435 def _helper_ispecs(owner, params):
436 for key, value in params.iteritems():
437 fullkey = "ipolicy/" + key
438 _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
440 # check cluster parameters
441 _helper("cluster", "beparams", cluster.SimpleFillBE({}),
442 constants.BES_PARAMETER_TYPES)
443 _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
444 constants.NICS_PARAMETER_TYPES)
445 _helper_nic("cluster", cluster.SimpleFillNIC({}))
446 _helper("cluster", "ndparams", cluster.SimpleFillND({}),
447 constants.NDS_PARAMETER_TYPES)
448 _helper_ipolicy("cluster", cluster.SimpleFillIPolicy({}))
449 _helper_ispecs("cluster", cluster.SimpleFillIPolicy({}))
451 # per-instance checks
452 for instance_name in data.instances:
453 instance = data.instances[instance_name]
454 if instance.name != instance_name:
455 result.append("instance '%s' is indexed by wrong name '%s'" %
456 (instance.name, instance_name))
457 if instance.primary_node not in data.nodes:
458 result.append("instance '%s' has invalid primary node '%s'" %
459 (instance_name, instance.primary_node))
460 for snode in instance.secondary_nodes:
461 if snode not in data.nodes:
462 result.append("instance '%s' has invalid secondary node '%s'" %
463 (instance_name, snode))
464 for idx, nic in enumerate(instance.nics):
465 if nic.mac in seen_macs:
466 result.append("instance '%s' has NIC %d mac %s duplicate" %
467 (instance_name, idx, nic.mac))
469 seen_macs.append(nic.mac)
471 filled = cluster.SimpleFillNIC(nic.nicparams)
472 owner = "instance %s nic %d" % (instance.name, idx)
473 _helper(owner, "nicparams",
474 filled, constants.NICS_PARAMETER_TYPES)
475 _helper_nic(owner, filled)
478 if instance.beparams:
479 _helper("instance %s" % instance.name, "beparams",
480 cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
482 # gather the drbd ports for duplicate checks
483 for dsk in instance.disks:
484 if dsk.dev_type in constants.LDS_DRBD:
485 tcp_port = dsk.logical_id[2]
486 if tcp_port not in ports:
488 ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
489 # gather network port reservation
490 net_port = getattr(instance, "network_port", None)
491 if net_port is not None:
492 if net_port not in ports:
494 ports[net_port].append((instance.name, "network port"))
496 # instance disk verify
497 for idx, disk in enumerate(instance.disks):
498 result.extend(["instance '%s' disk %d error: %s" %
499 (instance.name, idx, msg) for msg in disk.Verify()])
500 result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
502 # cluster-wide pool of free ports
503 for free_port in cluster.tcpudp_port_pool:
504 if free_port not in ports:
505 ports[free_port] = []
506 ports[free_port].append(("cluster", "port marked as free"))
508 # compute tcp/udp duplicate ports
514 txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
515 result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
517 # highest used tcp port check
519 if keys[-1] > cluster.highest_used_port:
520 result.append("Highest used port mismatch, saved %s, computed %s" %
521 (cluster.highest_used_port, keys[-1]))
523 if not data.nodes[cluster.master_node].master_candidate:
524 result.append("Master node is not a master candidate")
526 # master candidate checks
527 mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
529 result.append("Not enough master candidates: actual %d, target %d" %
533 for node_name, node in data.nodes.items():
534 if node.name != node_name:
535 result.append("Node '%s' is indexed by wrong name '%s'" %
536 (node.name, node_name))
537 if [node.master_candidate, node.drained, node.offline].count(True) > 1:
538 result.append("Node %s state is invalid: master_candidate=%s,"
539 " drain=%s, offline=%s" %
540 (node.name, node.master_candidate, node.drained,
542 if node.group not in data.nodegroups:
543 result.append("Node '%s' has invalid group '%s'" %
544 (node.name, node.group))
546 _helper("node %s" % node.name, "ndparams",
547 cluster.FillND(node, data.nodegroups[node.group]),
548 constants.NDS_PARAMETER_TYPES)
551 nodegroups_names = set()
552 for nodegroup_uuid in data.nodegroups:
553 nodegroup = data.nodegroups[nodegroup_uuid]
554 if nodegroup.uuid != nodegroup_uuid:
555 result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
556 % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
557 if utils.UUID_RE.match(nodegroup.name.lower()):
558 result.append("node group '%s' (uuid: '%s') has uuid-like name" %
559 (nodegroup.name, nodegroup.uuid))
560 if nodegroup.name in nodegroups_names:
561 result.append("duplicate node group name '%s'" % nodegroup.name)
563 nodegroups_names.add(nodegroup.name)
564 if nodegroup.ndparams:
565 _helper("group %s" % nodegroup.name, "ndparams",
566 cluster.SimpleFillND(nodegroup.ndparams),
567 constants.NDS_PARAMETER_TYPES)
570 _, duplicates = self._UnlockedComputeDRBDMap()
571 for node, minor, instance_a, instance_b in duplicates:
572 result.append("DRBD minor %d on node %s is assigned twice to instances"
573 " %s and %s" % (minor, node, instance_a, instance_b))
576 default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
579 def _AddIpAddress(ip, name):
580 ips.setdefault(ip, []).append(name)
582 _AddIpAddress(cluster.master_ip, "cluster_ip")
584 for node in data.nodes.values():
585 _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
586 if node.secondary_ip != node.primary_ip:
587 _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
589 for instance in data.instances.values():
590 for idx, nic in enumerate(instance.nics):
594 nicparams = objects.FillDict(default_nicparams, nic.nicparams)
595 nic_mode = nicparams[constants.NIC_MODE]
596 nic_link = nicparams[constants.NIC_LINK]
598 if nic_mode == constants.NIC_MODE_BRIDGED:
599 link = "bridge:%s" % nic_link
600 elif nic_mode == constants.NIC_MODE_ROUTED:
601 link = "route:%s" % nic_link
603 raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
605 _AddIpAddress("%s/%s" % (link, nic.ip),
606 "instance:%s/nic:%d" % (instance.name, idx))
608 for ip, owners in ips.items():
610 result.append("IP address %s is used by multiple owners: %s" %
611 (ip, utils.CommaJoin(owners)))
615 @locking.ssynchronized(_config_lock, shared=1)
616 def VerifyConfig(self):
619 This is just a wrapper over L{_UnlockedVerifyConfig}.
622 @return: a list of error messages; a non-empty list signifies
626 return self._UnlockedVerifyConfig()
628 def _UnlockedSetDiskID(self, disk, node_name):
629 """Convert the unique ID to the ID needed on the target nodes.
631 This is used only for drbd, which needs ip/port configuration.
633 The routine descends down and updates its children also, because
634 this helps when the only the top device is passed to the remote
637 This function is for internal use, when the config lock is already held.
641 for child in disk.children:
642 self._UnlockedSetDiskID(child, node_name)
644 if disk.logical_id is None and disk.physical_id is not None:
646 if disk.dev_type == constants.LD_DRBD8:
647 pnode, snode, port, pminor, sminor, secret = disk.logical_id
648 if node_name not in (pnode, snode):
649 raise errors.ConfigurationError("DRBD device not knowing node %s" %
651 pnode_info = self._UnlockedGetNodeInfo(pnode)
652 snode_info = self._UnlockedGetNodeInfo(snode)
653 if pnode_info is None or snode_info is None:
654 raise errors.ConfigurationError("Can't find primary or secondary node"
655 " for %s" % str(disk))
656 p_data = (pnode_info.secondary_ip, port)
657 s_data = (snode_info.secondary_ip, port)
658 if pnode == node_name:
659 disk.physical_id = p_data + s_data + (pminor, secret)
660 else: # it must be secondary, we tested above
661 disk.physical_id = s_data + p_data + (sminor, secret)
663 disk.physical_id = disk.logical_id
666 @locking.ssynchronized(_config_lock)
667 def SetDiskID(self, disk, node_name):
668 """Convert the unique ID to the ID needed on the target nodes.
670 This is used only for drbd, which needs ip/port configuration.
672 The routine descends down and updates its children also, because
673 this helps when the only the top device is passed to the remote
677 return self._UnlockedSetDiskID(disk, node_name)
679 @locking.ssynchronized(_config_lock)
680 def AddTcpUdpPort(self, port):
681 """Adds a new port to the available port pool.
684 if not isinstance(port, int):
685 raise errors.ProgrammerError("Invalid type passed for port")
687 self._config_data.cluster.tcpudp_port_pool.add(port)
690 @locking.ssynchronized(_config_lock, shared=1)
691 def GetPortList(self):
692 """Returns a copy of the current port list.
695 return self._config_data.cluster.tcpudp_port_pool.copy()
697 @locking.ssynchronized(_config_lock)
698 def AllocatePort(self):
701 The port will be taken from the available port pool or from the
702 default port range (and in this case we increase
706 # If there are TCP/IP ports configured, we use them first.
707 if self._config_data.cluster.tcpudp_port_pool:
708 port = self._config_data.cluster.tcpudp_port_pool.pop()
710 port = self._config_data.cluster.highest_used_port + 1
711 if port >= constants.LAST_DRBD_PORT:
712 raise errors.ConfigurationError("The highest used port is greater"
713 " than %s. Aborting." %
714 constants.LAST_DRBD_PORT)
715 self._config_data.cluster.highest_used_port = port
720 def _UnlockedComputeDRBDMap(self):
721 """Compute the used DRBD minor/nodes.
724 @return: dictionary of node_name: dict of minor: instance_name;
725 the returned dict will have all the nodes in it (even if with
726 an empty list), and a list of duplicates; if the duplicates
727 list is not empty, the configuration is corrupted and its caller
728 should raise an exception
731 def _AppendUsedPorts(instance_name, disk, used):
733 if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
734 node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
735 for node, port in ((node_a, minor_a), (node_b, minor_b)):
736 assert node in used, ("Node '%s' of instance '%s' not found"
737 " in node list" % (node, instance_name))
738 if port in used[node]:
739 duplicates.append((node, port, instance_name, used[node][port]))
741 used[node][port] = instance_name
743 for child in disk.children:
744 duplicates.extend(_AppendUsedPorts(instance_name, child, used))
748 my_dict = dict((node, {}) for node in self._config_data.nodes)
749 for instance in self._config_data.instances.itervalues():
750 for disk in instance.disks:
751 duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
752 for (node, minor), instance in self._temporary_drbds.iteritems():
753 if minor in my_dict[node] and my_dict[node][minor] != instance:
754 duplicates.append((node, minor, instance, my_dict[node][minor]))
756 my_dict[node][minor] = instance
757 return my_dict, duplicates
759 @locking.ssynchronized(_config_lock)
760 def ComputeDRBDMap(self):
761 """Compute the used DRBD minor/nodes.
763 This is just a wrapper over L{_UnlockedComputeDRBDMap}.
765 @return: dictionary of node_name: dict of minor: instance_name;
766 the returned dict will have all the nodes in it (even if with
770 d_map, duplicates = self._UnlockedComputeDRBDMap()
772 raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
776 @locking.ssynchronized(_config_lock)
777 def AllocateDRBDMinor(self, nodes, instance):
778 """Allocate a drbd minor.
780 The free minor will be automatically computed from the existing
781 devices. A node can be given multiple times in order to allocate
782 multiple minors. The result is the list of minors, in the same
783 order as the passed nodes.
785 @type instance: string
786 @param instance: the instance for which we allocate minors
789 assert isinstance(instance, basestring), \
790 "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
792 d_map, duplicates = self._UnlockedComputeDRBDMap()
794 raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
800 # no minors used, we can start at 0
803 self._temporary_drbds[(nname, 0)] = instance
807 ffree = utils.FirstFree(keys)
809 # return the next minor
810 # TODO: implement high-limit check
814 # double-check minor against current instances
815 assert minor not in d_map[nname], \
816 ("Attempt to reuse allocated DRBD minor %d on node %s,"
817 " already allocated to instance %s" %
818 (minor, nname, d_map[nname][minor]))
819 ndata[minor] = instance
820 # double-check minor against reservation
821 r_key = (nname, minor)
822 assert r_key not in self._temporary_drbds, \
823 ("Attempt to reuse reserved DRBD minor %d on node %s,"
824 " reserved for instance %s" %
825 (minor, nname, self._temporary_drbds[r_key]))
826 self._temporary_drbds[r_key] = instance
828 logging.debug("Request to allocate drbd minors, input: %s, returning %s",
832 def _UnlockedReleaseDRBDMinors(self, instance):
833 """Release temporary drbd minors allocated for a given instance.
835 @type instance: string
836 @param instance: the instance for which temporary minors should be
840 assert isinstance(instance, basestring), \
841 "Invalid argument passed to ReleaseDRBDMinors"
842 for key, name in self._temporary_drbds.items():
844 del self._temporary_drbds[key]
846 @locking.ssynchronized(_config_lock)
847 def ReleaseDRBDMinors(self, instance):
848 """Release temporary drbd minors allocated for a given instance.
850 This should be called on the error paths, on the success paths
851 it's automatically called by the ConfigWriter add and update
854 This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
856 @type instance: string
857 @param instance: the instance for which temporary minors should be
861 self._UnlockedReleaseDRBDMinors(instance)
863 @locking.ssynchronized(_config_lock, shared=1)
864 def GetConfigVersion(self):
865 """Get the configuration version.
867 @return: Config version
870 return self._config_data.version
872 @locking.ssynchronized(_config_lock, shared=1)
873 def GetClusterName(self):
876 @return: Cluster name
879 return self._config_data.cluster.cluster_name
881 @locking.ssynchronized(_config_lock, shared=1)
882 def GetMasterNode(self):
883 """Get the hostname of the master node for this cluster.
885 @return: Master hostname
888 return self._config_data.cluster.master_node
890 @locking.ssynchronized(_config_lock, shared=1)
891 def GetMasterIP(self):
892 """Get the IP of the master node for this cluster.
897 return self._config_data.cluster.master_ip
899 @locking.ssynchronized(_config_lock, shared=1)
900 def GetMasterNetdev(self):
901 """Get the master network device for this cluster.
904 return self._config_data.cluster.master_netdev
906 @locking.ssynchronized(_config_lock, shared=1)
907 def GetMasterNetmask(self):
908 """Get the netmask of the master node for this cluster.
911 return self._config_data.cluster.master_netmask
913 @locking.ssynchronized(_config_lock, shared=1)
914 def GetUseExternalMipScript(self):
915 """Get flag representing whether to use the external master IP setup script.
918 return self._config_data.cluster.use_external_mip_script
920 @locking.ssynchronized(_config_lock, shared=1)
921 def GetFileStorageDir(self):
922 """Get the file storage dir for this cluster.
925 return self._config_data.cluster.file_storage_dir
927 @locking.ssynchronized(_config_lock, shared=1)
928 def GetSharedFileStorageDir(self):
929 """Get the shared file storage dir for this cluster.
932 return self._config_data.cluster.shared_file_storage_dir
934 @locking.ssynchronized(_config_lock, shared=1)
935 def GetHypervisorType(self):
936 """Get the hypervisor type for this cluster.
939 return self._config_data.cluster.enabled_hypervisors[0]
941 @locking.ssynchronized(_config_lock, shared=1)
942 def GetHostKey(self):
943 """Return the rsa hostkey from the config.
946 @return: the rsa hostkey
949 return self._config_data.cluster.rsahostkeypub
951 @locking.ssynchronized(_config_lock, shared=1)
952 def GetDefaultIAllocator(self):
953 """Get the default instance allocator for this cluster.
956 return self._config_data.cluster.default_iallocator
958 @locking.ssynchronized(_config_lock, shared=1)
959 def GetPrimaryIPFamily(self):
960 """Get cluster primary ip family.
962 @return: primary ip family
965 return self._config_data.cluster.primary_ip_family
967 @locking.ssynchronized(_config_lock, shared=1)
968 def GetMasterNetworkParameters(self):
969 """Get network parameters of the master node.
971 @rtype: L{object.MasterNetworkParameters}
972 @return: network parameters of the master node
975 cluster = self._config_data.cluster
976 result = objects.MasterNetworkParameters(name=cluster.master_node,
977 ip=cluster.master_ip,
978 netmask=cluster.master_netmask,
979 netdev=cluster.master_netdev,
980 ip_family=cluster.primary_ip_family)
984 @locking.ssynchronized(_config_lock)
985 def AddNodeGroup(self, group, ec_id, check_uuid=True):
986 """Add a node group to the configuration.
988 This method calls group.UpgradeConfig() to fill any missing attributes
989 according to their default values.
991 @type group: L{objects.NodeGroup}
992 @param group: the NodeGroup object to add
994 @param ec_id: unique id for the job to use when creating a missing UUID
995 @type check_uuid: bool
996 @param check_uuid: add an UUID to the group if it doesn't have one or, if
997 it does, ensure that it does not exist in the
998 configuration already
1001 self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1004 def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1005 """Add a node group to the configuration.
1008 logging.info("Adding node group %s to configuration", group.name)
1010 # Some code might need to add a node group with a pre-populated UUID
1011 # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1012 # the "does this UUID" exist already check.
1014 self._EnsureUUID(group, ec_id)
1017 existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1018 except errors.OpPrereqError:
1021 raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1022 " node group (UUID: %s)" %
1023 (group.name, existing_uuid),
1024 errors.ECODE_EXISTS)
1027 group.ctime = group.mtime = time.time()
1028 group.UpgradeConfig()
1030 self._config_data.nodegroups[group.uuid] = group
1031 self._config_data.cluster.serial_no += 1
1033 @locking.ssynchronized(_config_lock)
1034 def RemoveNodeGroup(self, group_uuid):
1035 """Remove a node group from the configuration.
1037 @type group_uuid: string
1038 @param group_uuid: the UUID of the node group to remove
1041 logging.info("Removing node group %s from configuration", group_uuid)
1043 if group_uuid not in self._config_data.nodegroups:
1044 raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1046 assert len(self._config_data.nodegroups) != 1, \
1047 "Group '%s' is the only group, cannot be removed" % group_uuid
1049 del self._config_data.nodegroups[group_uuid]
1050 self._config_data.cluster.serial_no += 1
1053 def _UnlockedLookupNodeGroup(self, target):
1054 """Lookup a node group's UUID.
1056 @type target: string or None
1057 @param target: group name or UUID or None to look for the default
1059 @return: nodegroup UUID
1060 @raises errors.OpPrereqError: when the target group cannot be found
1064 if len(self._config_data.nodegroups) != 1:
1065 raise errors.OpPrereqError("More than one node group exists. Target"
1066 " group must be specified explicitely.")
1068 return self._config_data.nodegroups.keys()[0]
1069 if target in self._config_data.nodegroups:
1071 for nodegroup in self._config_data.nodegroups.values():
1072 if nodegroup.name == target:
1073 return nodegroup.uuid
1074 raise errors.OpPrereqError("Node group '%s' not found" % target,
1077 @locking.ssynchronized(_config_lock, shared=1)
1078 def LookupNodeGroup(self, target):
1079 """Lookup a node group's UUID.
1081 This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1083 @type target: string or None
1084 @param target: group name or UUID or None to look for the default
1086 @return: nodegroup UUID
1089 return self._UnlockedLookupNodeGroup(target)
1091 def _UnlockedGetNodeGroup(self, uuid):
1092 """Lookup a node group.
1095 @param uuid: group UUID
1096 @rtype: L{objects.NodeGroup} or None
1097 @return: nodegroup object, or None if not found
1100 if uuid not in self._config_data.nodegroups:
1103 return self._config_data.nodegroups[uuid]
1105 @locking.ssynchronized(_config_lock, shared=1)
1106 def GetNodeGroup(self, uuid):
1107 """Lookup a node group.
1110 @param uuid: group UUID
1111 @rtype: L{objects.NodeGroup} or None
1112 @return: nodegroup object, or None if not found
1115 return self._UnlockedGetNodeGroup(uuid)
1117 @locking.ssynchronized(_config_lock, shared=1)
1118 def GetAllNodeGroupsInfo(self):
1119 """Get the configuration of all node groups.
1122 return dict(self._config_data.nodegroups)
1124 @locking.ssynchronized(_config_lock, shared=1)
1125 def GetNodeGroupList(self):
1126 """Get a list of node groups.
1129 return self._config_data.nodegroups.keys()
1131 @locking.ssynchronized(_config_lock, shared=1)
1132 def GetNodeGroupMembersByNodes(self, nodes):
1133 """Get nodes which are member in the same nodegroups as the given nodes.
1136 ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1137 return frozenset(member_name
1138 for node_name in nodes
1140 self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1142 @locking.ssynchronized(_config_lock)
1143 def AddInstance(self, instance, ec_id):
1144 """Add an instance to the config.
1146 This should be used after creating a new instance.
1148 @type instance: L{objects.Instance}
1149 @param instance: the instance object
1152 if not isinstance(instance, objects.Instance):
1153 raise errors.ProgrammerError("Invalid type passed to AddInstance")
1155 if instance.disk_template != constants.DT_DISKLESS:
1156 all_lvs = instance.MapLVsByNode()
1157 logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1159 all_macs = self._AllMACs()
1160 for nic in instance.nics:
1161 if nic.mac in all_macs:
1162 raise errors.ConfigurationError("Cannot add instance %s:"
1163 " MAC address '%s' already in use." %
1164 (instance.name, nic.mac))
1166 self._EnsureUUID(instance, ec_id)
1168 instance.serial_no = 1
1169 instance.ctime = instance.mtime = time.time()
1170 self._config_data.instances[instance.name] = instance
1171 self._config_data.cluster.serial_no += 1
1172 self._UnlockedReleaseDRBDMinors(instance.name)
1175 def _EnsureUUID(self, item, ec_id):
1176 """Ensures a given object has a valid UUID.
1178 @param item: the instance or node to be checked
1179 @param ec_id: the execution context id for the uuid reservation
1183 item.uuid = self._GenerateUniqueID(ec_id)
1184 elif item.uuid in self._AllIDs(include_temporary=True):
1185 raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1186 " in use" % (item.name, item.uuid))
1188 def _SetInstanceStatus(self, instance_name, status):
1189 """Set the instance's status to a given value.
1192 assert status in constants.ADMINST_ALL, \
1193 "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1195 if instance_name not in self._config_data.instances:
1196 raise errors.ConfigurationError("Unknown instance '%s'" %
1198 instance = self._config_data.instances[instance_name]
1199 if instance.admin_state != status:
1200 instance.admin_state = status
1201 instance.serial_no += 1
1202 instance.mtime = time.time()
1205 @locking.ssynchronized(_config_lock)
1206 def MarkInstanceUp(self, instance_name):
1207 """Mark the instance status to up in the config.
1210 self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1212 @locking.ssynchronized(_config_lock)
1213 def MarkInstanceOffline(self, instance_name):
1214 """Mark the instance status to down in the config.
1217 self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1219 @locking.ssynchronized(_config_lock)
1220 def RemoveInstance(self, instance_name):
1221 """Remove the instance from the configuration.
1224 if instance_name not in self._config_data.instances:
1225 raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1227 # If a network port has been allocated to the instance,
1228 # return it to the pool of free ports.
1229 inst = self._config_data.instances[instance_name]
1230 network_port = getattr(inst, "network_port", None)
1231 if network_port is not None:
1232 self._config_data.cluster.tcpudp_port_pool.add(network_port)
1234 del self._config_data.instances[instance_name]
1235 self._config_data.cluster.serial_no += 1
1238 @locking.ssynchronized(_config_lock)
1239 def RenameInstance(self, old_name, new_name):
1240 """Rename an instance.
1242 This needs to be done in ConfigWriter and not by RemoveInstance
1243 combined with AddInstance as only we can guarantee an atomic
1247 if old_name not in self._config_data.instances:
1248 raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1249 inst = self._config_data.instances[old_name]
1250 del self._config_data.instances[old_name]
1251 inst.name = new_name
1253 for disk in inst.disks:
1254 if disk.dev_type == constants.LD_FILE:
1255 # rename the file paths in logical and physical id
1256 file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1257 disk_fname = "disk%s" % disk.iv_name.split("/")[1]
1258 disk.physical_id = disk.logical_id = (disk.logical_id[0],
1259 utils.PathJoin(file_storage_dir,
1263 # Force update of ssconf files
1264 self._config_data.cluster.serial_no += 1
1266 self._config_data.instances[inst.name] = inst
1269 @locking.ssynchronized(_config_lock)
1270 def MarkInstanceDown(self, instance_name):
1271 """Mark the status of an instance to down in the configuration.
1274 self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1276 def _UnlockedGetInstanceList(self):
1277 """Get the list of instances.
1279 This function is for internal use, when the config lock is already held.
1282 return self._config_data.instances.keys()
1284 @locking.ssynchronized(_config_lock, shared=1)
1285 def GetInstanceList(self):
1286 """Get the list of instances.
1288 @return: array of instances, ex. ['instance2.example.com',
1289 'instance1.example.com']
1292 return self._UnlockedGetInstanceList()
1294 def ExpandInstanceName(self, short_name):
1295 """Attempt to expand an incomplete instance name.
1298 # Locking is done in L{ConfigWriter.GetInstanceList}
1299 return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1301 def _UnlockedGetInstanceInfo(self, instance_name):
1302 """Returns information about an instance.
1304 This function is for internal use, when the config lock is already held.
1307 if instance_name not in self._config_data.instances:
1310 return self._config_data.instances[instance_name]
1312 @locking.ssynchronized(_config_lock, shared=1)
1313 def GetInstanceInfo(self, instance_name):
1314 """Returns information about an instance.
1316 It takes the information from the configuration file. Other information of
1317 an instance are taken from the live systems.
1319 @param instance_name: name of the instance, e.g.
1320 I{instance1.example.com}
1322 @rtype: L{objects.Instance}
1323 @return: the instance object
1326 return self._UnlockedGetInstanceInfo(instance_name)
1328 @locking.ssynchronized(_config_lock, shared=1)
1329 def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1330 """Returns set of node group UUIDs for instance's nodes.
1335 instance = self._UnlockedGetInstanceInfo(instance_name)
1337 raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1340 nodes = [instance.primary_node]
1342 nodes = instance.all_nodes
1344 return frozenset(self._UnlockedGetNodeInfo(node_name).group
1345 for node_name in nodes)
1347 @locking.ssynchronized(_config_lock, shared=1)
1348 def GetMultiInstanceInfo(self, instances):
1349 """Get the configuration of multiple instances.
1351 @param instances: list of instance names
1353 @return: list of tuples (instance, instance_info), where
1354 instance_info is what would GetInstanceInfo return for the
1355 node, while keeping the original order
1358 return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1360 @locking.ssynchronized(_config_lock, shared=1)
1361 def GetAllInstancesInfo(self):
1362 """Get the configuration of all instances.
1365 @return: dict of (instance, instance_info), where instance_info is what
1366 would GetInstanceInfo return for the node
1369 my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1370 for instance in self._UnlockedGetInstanceList()])
1373 @locking.ssynchronized(_config_lock, shared=1)
1374 def GetInstancesInfoByFilter(self, filter_fn):
1375 """Get instance configuration with a filter.
1377 @type filter_fn: callable
1378 @param filter_fn: Filter function receiving instance object as parameter,
1379 returning boolean. Important: this function is called while the
1380 configuration locks is held. It must not do any complex work or call
1381 functions potentially leading to a deadlock. Ideally it doesn't call any
1382 other functions and just compares instance attributes.
1385 return dict((name, inst)
1386 for (name, inst) in self._config_data.instances.items()
1389 @locking.ssynchronized(_config_lock)
1390 def AddNode(self, node, ec_id):
1391 """Add a node to the configuration.
1393 @type node: L{objects.Node}
1394 @param node: a Node instance
1397 logging.info("Adding node %s to configuration", node.name)
1399 self._EnsureUUID(node, ec_id)
1402 node.ctime = node.mtime = time.time()
1403 self._UnlockedAddNodeToGroup(node.name, node.group)
1404 self._config_data.nodes[node.name] = node
1405 self._config_data.cluster.serial_no += 1
1408 @locking.ssynchronized(_config_lock)
1409 def RemoveNode(self, node_name):
1410 """Remove a node from the configuration.
1413 logging.info("Removing node %s from configuration", node_name)
1415 if node_name not in self._config_data.nodes:
1416 raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1418 self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1419 del self._config_data.nodes[node_name]
1420 self._config_data.cluster.serial_no += 1
1423 def ExpandNodeName(self, short_name):
1424 """Attempt to expand an incomplete node name.
1427 # Locking is done in L{ConfigWriter.GetNodeList}
1428 return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1430 def _UnlockedGetNodeInfo(self, node_name):
1431 """Get the configuration of a node, as stored in the config.
1433 This function is for internal use, when the config lock is already
1436 @param node_name: the node name, e.g. I{node1.example.com}
1438 @rtype: L{objects.Node}
1439 @return: the node object
1442 if node_name not in self._config_data.nodes:
1445 return self._config_data.nodes[node_name]
1447 @locking.ssynchronized(_config_lock, shared=1)
1448 def GetNodeInfo(self, node_name):
1449 """Get the configuration of a node, as stored in the config.
1451 This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1453 @param node_name: the node name, e.g. I{node1.example.com}
1455 @rtype: L{objects.Node}
1456 @return: the node object
1459 return self._UnlockedGetNodeInfo(node_name)
1461 @locking.ssynchronized(_config_lock, shared=1)
1462 def GetNodeInstances(self, node_name):
1463 """Get the instances of a node, as stored in the config.
1465 @param node_name: the node name, e.g. I{node1.example.com}
1467 @rtype: (list, list)
1468 @return: a tuple with two lists: the primary and the secondary instances
1473 for inst in self._config_data.instances.values():
1474 if inst.primary_node == node_name:
1475 pri.append(inst.name)
1476 if node_name in inst.secondary_nodes:
1477 sec.append(inst.name)
1480 @locking.ssynchronized(_config_lock, shared=1)
1481 def GetNodeGroupInstances(self, uuid, primary_only=False):
1482 """Get the instances of a node group.
1484 @param uuid: Node group UUID
1485 @param primary_only: Whether to only consider primary nodes
1487 @return: List of instance names in node group
1491 nodes_fn = lambda inst: [inst.primary_node]
1493 nodes_fn = lambda inst: inst.all_nodes
1495 return frozenset(inst.name
1496 for inst in self._config_data.instances.values()
1497 for node_name in nodes_fn(inst)
1498 if self._UnlockedGetNodeInfo(node_name).group == uuid)
1500 def _UnlockedGetNodeList(self):
1501 """Return the list of nodes which are in the configuration.
1503 This function is for internal use, when the config lock is already
1509 return self._config_data.nodes.keys()
1511 @locking.ssynchronized(_config_lock, shared=1)
1512 def GetNodeList(self):
1513 """Return the list of nodes which are in the configuration.
1516 return self._UnlockedGetNodeList()
1518 def _UnlockedGetOnlineNodeList(self):
1519 """Return the list of nodes which are online.
1522 all_nodes = [self._UnlockedGetNodeInfo(node)
1523 for node in self._UnlockedGetNodeList()]
1524 return [node.name for node in all_nodes if not node.offline]
1526 @locking.ssynchronized(_config_lock, shared=1)
1527 def GetOnlineNodeList(self):
1528 """Return the list of nodes which are online.
1531 return self._UnlockedGetOnlineNodeList()
1533 @locking.ssynchronized(_config_lock, shared=1)
1534 def GetVmCapableNodeList(self):
1535 """Return the list of nodes which are not vm capable.
1538 all_nodes = [self._UnlockedGetNodeInfo(node)
1539 for node in self._UnlockedGetNodeList()]
1540 return [node.name for node in all_nodes if node.vm_capable]
1542 @locking.ssynchronized(_config_lock, shared=1)
1543 def GetNonVmCapableNodeList(self):
1544 """Return the list of nodes which are not vm capable.
1547 all_nodes = [self._UnlockedGetNodeInfo(node)
1548 for node in self._UnlockedGetNodeList()]
1549 return [node.name for node in all_nodes if not node.vm_capable]
1551 @locking.ssynchronized(_config_lock, shared=1)
1552 def GetMultiNodeInfo(self, nodes):
1553 """Get the configuration of multiple nodes.
1555 @param nodes: list of node names
1557 @return: list of tuples of (node, node_info), where node_info is
1558 what would GetNodeInfo return for the node, in the original
1562 return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1564 @locking.ssynchronized(_config_lock, shared=1)
1565 def GetAllNodesInfo(self):
1566 """Get the configuration of all nodes.
1569 @return: dict of (node, node_info), where node_info is what
1570 would GetNodeInfo return for the node
1573 return self._UnlockedGetAllNodesInfo()
1575 def _UnlockedGetAllNodesInfo(self):
1576 """Gets configuration of all nodes.
1578 @note: See L{GetAllNodesInfo}
1581 return dict([(node, self._UnlockedGetNodeInfo(node))
1582 for node in self._UnlockedGetNodeList()])
1584 @locking.ssynchronized(_config_lock, shared=1)
1585 def GetNodeGroupsFromNodes(self, nodes):
1586 """Returns groups for a list of nodes.
1588 @type nodes: list of string
1589 @param nodes: List of node names
1593 return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1595 def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1596 """Get the number of current and maximum desired and possible candidates.
1598 @type exceptions: list
1599 @param exceptions: if passed, list of nodes that should be ignored
1601 @return: tuple of (current, desired and possible, possible)
1604 mc_now = mc_should = mc_max = 0
1605 for node in self._config_data.nodes.values():
1606 if exceptions and node.name in exceptions:
1608 if not (node.offline or node.drained) and node.master_capable:
1610 if node.master_candidate:
1612 mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1613 return (mc_now, mc_should, mc_max)
1615 @locking.ssynchronized(_config_lock, shared=1)
1616 def GetMasterCandidateStats(self, exceptions=None):
1617 """Get the number of current and maximum possible candidates.
1619 This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1621 @type exceptions: list
1622 @param exceptions: if passed, list of nodes that should be ignored
1624 @return: tuple of (current, max)
1627 return self._UnlockedGetMasterCandidateStats(exceptions)
1629 @locking.ssynchronized(_config_lock)
1630 def MaintainCandidatePool(self, exceptions):
1631 """Try to grow the candidate pool to the desired size.
1633 @type exceptions: list
1634 @param exceptions: if passed, list of nodes that should be ignored
1636 @return: list with the adjusted nodes (L{objects.Node} instances)
1639 mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1642 node_list = self._config_data.nodes.keys()
1643 random.shuffle(node_list)
1644 for name in node_list:
1645 if mc_now >= mc_max:
1647 node = self._config_data.nodes[name]
1648 if (node.master_candidate or node.offline or node.drained or
1649 node.name in exceptions or not node.master_capable):
1651 mod_list.append(node)
1652 node.master_candidate = True
1655 if mc_now != mc_max:
1656 # this should not happen
1657 logging.warning("Warning: MaintainCandidatePool didn't manage to"
1658 " fill the candidate pool (%d/%d)", mc_now, mc_max)
1660 self._config_data.cluster.serial_no += 1
1665 def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1666 """Add a given node to the specified group.
1669 if nodegroup_uuid not in self._config_data.nodegroups:
1670 # This can happen if a node group gets deleted between its lookup and
1671 # when we're adding the first node to it, since we don't keep a lock in
1672 # the meantime. It's ok though, as we'll fail cleanly if the node group
1673 # is not found anymore.
1674 raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1675 if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1676 self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1678 def _UnlockedRemoveNodeFromGroup(self, node):
1679 """Remove a given node from its group.
1682 nodegroup = node.group
1683 if nodegroup not in self._config_data.nodegroups:
1684 logging.warning("Warning: node '%s' has unknown node group '%s'"
1685 " (while being removed from it)", node.name, nodegroup)
1686 nodegroup_obj = self._config_data.nodegroups[nodegroup]
1687 if node.name not in nodegroup_obj.members:
1688 logging.warning("Warning: node '%s' not a member of its node group '%s'"
1689 " (while being removed from it)", node.name, nodegroup)
1691 nodegroup_obj.members.remove(node.name)
1693 @locking.ssynchronized(_config_lock)
1694 def AssignGroupNodes(self, mods):
1695 """Changes the group of a number of nodes.
1697 @type mods: list of tuples; (node name, new group UUID)
1698 @param mods: Node membership modifications
1701 groups = self._config_data.nodegroups
1702 nodes = self._config_data.nodes
1706 # Try to resolve names/UUIDs first
1707 for (node_name, new_group_uuid) in mods:
1709 node = nodes[node_name]
1711 raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1713 if node.group == new_group_uuid:
1714 # Node is being assigned to its current group
1715 logging.debug("Node '%s' was assigned to its current group (%s)",
1716 node_name, node.group)
1719 # Try to find current group of node
1721 old_group = groups[node.group]
1723 raise errors.ConfigurationError("Unable to find old group '%s'" %
1726 # Try to find new group for node
1728 new_group = groups[new_group_uuid]
1730 raise errors.ConfigurationError("Unable to find new group '%s'" %
1733 assert node.name in old_group.members, \
1734 ("Inconsistent configuration: node '%s' not listed in members for its"
1735 " old group '%s'" % (node.name, old_group.uuid))
1736 assert node.name not in new_group.members, \
1737 ("Inconsistent configuration: node '%s' already listed in members for"
1738 " its new group '%s'" % (node.name, new_group.uuid))
1740 resmod.append((node, old_group, new_group))
1743 for (node, old_group, new_group) in resmod:
1744 assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
1745 "Assigning to current group is not possible"
1747 node.group = new_group.uuid
1749 # Update members of involved groups
1750 if node.name in old_group.members:
1751 old_group.members.remove(node.name)
1752 if node.name not in new_group.members:
1753 new_group.members.append(node.name)
1755 # Update timestamps and serials (only once per node/group object)
1757 for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
1761 # Force ssconf update
1762 self._config_data.cluster.serial_no += 1
1766 def _BumpSerialNo(self):
1767 """Bump up the serial number of the config.
1770 self._config_data.serial_no += 1
1771 self._config_data.mtime = time.time()
1773 def _AllUUIDObjects(self):
1774 """Returns all objects with uuid attributes.
1777 return (self._config_data.instances.values() +
1778 self._config_data.nodes.values() +
1779 self._config_data.nodegroups.values() +
1780 [self._config_data.cluster])
1782 def _OpenConfig(self, accept_foreign):
1783 """Read the config data from disk.
1786 raw_data = utils.ReadFile(self._cfg_file)
1789 data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1790 except Exception, err:
1791 raise errors.ConfigurationError(err)
1793 # Make sure the configuration has the right version
1794 _ValidateConfig(data)
1796 if (not hasattr(data, 'cluster') or
1797 not hasattr(data.cluster, 'rsahostkeypub')):
1798 raise errors.ConfigurationError("Incomplete configuration"
1799 " (missing cluster.rsahostkeypub)")
1801 if data.cluster.master_node != self._my_hostname and not accept_foreign:
1802 msg = ("The configuration denotes node %s as master, while my"
1803 " hostname is %s; opening a foreign configuration is only"
1804 " possible in accept_foreign mode" %
1805 (data.cluster.master_node, self._my_hostname))
1806 raise errors.ConfigurationError(msg)
1808 # Upgrade configuration if needed
1809 data.UpgradeConfig()
1811 self._config_data = data
1812 # reset the last serial as -1 so that the next write will cause
1814 self._last_cluster_serial = -1
1816 # And finally run our (custom) config upgrade sequence
1817 self._UpgradeConfig()
1819 self._cfg_id = utils.GetFileID(path=self._cfg_file)
1821 def _UpgradeConfig(self):
1822 """Run upgrade steps that cannot be done purely in the objects.
1824 This is because some data elements need uniqueness across the
1825 whole configuration, etc.
1827 @warning: this function will call L{_WriteConfig()}, but also
1828 L{DropECReservations} so it needs to be called only from a
1829 "safe" place (the constructor). If one wanted to call it with
1830 the lock held, a DropECReservationUnlocked would need to be
1831 created first, to avoid causing deadlock.
1835 for item in self._AllUUIDObjects():
1836 if item.uuid is None:
1837 item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1839 if not self._config_data.nodegroups:
1840 default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
1841 default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
1843 self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
1845 for node in self._config_data.nodes.values():
1847 node.group = self.LookupNodeGroup(None)
1849 # This is technically *not* an upgrade, but needs to be done both when
1850 # nodegroups are being added, and upon normally loading the config,
1851 # because the members list of a node group is discarded upon
1852 # serializing/deserializing the object.
1853 self._UnlockedAddNodeToGroup(node.name, node.group)
1856 # This is ok even if it acquires the internal lock, as _UpgradeConfig is
1857 # only called at config init time, without the lock held
1858 self.DropECReservations(_UPGRADE_CONFIG_JID)
1860 def _DistributeConfig(self, feedback_fn):
1861 """Distribute the configuration to the other nodes.
1863 Currently, this only copies the configuration file. In the future,
1864 it could be used to encapsulate the 2/3-phase update mechanism.
1874 myhostname = self._my_hostname
1875 # we can skip checking whether _UnlockedGetNodeInfo returns None
1876 # since the node list comes from _UnlocketGetNodeList, and we are
1877 # called with the lock held, so no modifications should take place
1879 for node_name in self._UnlockedGetNodeList():
1880 if node_name == myhostname:
1882 node_info = self._UnlockedGetNodeInfo(node_name)
1883 if not node_info.master_candidate:
1885 node_list.append(node_info.name)
1886 addr_list.append(node_info.primary_ip)
1888 # TODO: Use dedicated resolver talking to config writer for name resolution
1890 self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
1891 for to_node, to_result in result.items():
1892 msg = to_result.fail_msg
1894 msg = ("Copy of file %s to node %s failed: %s" %
1895 (self._cfg_file, to_node, msg))
1905 def _WriteConfig(self, destination=None, feedback_fn=None):
1906 """Write the configuration data to persistent storage.
1909 assert feedback_fn is None or callable(feedback_fn)
1911 # Warn on config errors, but don't abort the save - the
1912 # configuration has already been modified, and we can't revert;
1913 # the best we can do is to warn the user and save as is, leaving
1914 # recovery to the user
1915 config_errors = self._UnlockedVerifyConfig()
1917 errmsg = ("Configuration data is not consistent: %s" %
1918 (utils.CommaJoin(config_errors)))
1919 logging.critical(errmsg)
1923 if destination is None:
1924 destination = self._cfg_file
1925 self._BumpSerialNo()
1926 txt = serializer.Dump(self._config_data.ToDict())
1928 getents = self._getents()
1930 fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
1931 close=False, gid=getents.confd_gid, mode=0640)
1932 except errors.LockError:
1933 raise errors.ConfigurationError("The configuration file has been"
1934 " modified since the last write, cannot"
1937 self._cfg_id = utils.GetFileID(fd=fd)
1941 self.write_count += 1
1943 # and redistribute the config file to master candidates
1944 self._DistributeConfig(feedback_fn)
1946 # Write ssconf files on all nodes (including locally)
1947 if self._last_cluster_serial < self._config_data.cluster.serial_no:
1948 if not self._offline:
1949 result = self._GetRpc(None).call_write_ssconf_files(
1950 self._UnlockedGetOnlineNodeList(),
1951 self._UnlockedGetSsconfValues())
1953 for nname, nresu in result.items():
1954 msg = nresu.fail_msg
1956 errmsg = ("Error while uploading ssconf files to"
1957 " node %s: %s" % (nname, msg))
1958 logging.warning(errmsg)
1963 self._last_cluster_serial = self._config_data.cluster.serial_no
1965 def _UnlockedGetSsconfValues(self):
1966 """Return the values needed by ssconf.
1969 @return: a dictionary with keys the ssconf names and values their
1974 instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1975 node_names = utils.NiceSort(self._UnlockedGetNodeList())
1976 node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1977 node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
1978 for ninfo in node_info]
1979 node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
1980 for ninfo in node_info]
1982 instance_data = fn(instance_names)
1983 off_data = fn(node.name for node in node_info if node.offline)
1984 on_data = fn(node.name for node in node_info if not node.offline)
1985 mc_data = fn(node.name for node in node_info if node.master_candidate)
1986 mc_ips_data = fn(node.primary_ip for node in node_info
1987 if node.master_candidate)
1988 node_data = fn(node_names)
1989 node_pri_ips_data = fn(node_pri_ips)
1990 node_snd_ips_data = fn(node_snd_ips)
1992 cluster = self._config_data.cluster
1993 cluster_tags = fn(cluster.GetTags())
1995 hypervisor_list = fn(cluster.enabled_hypervisors)
1997 uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
1999 nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2000 self._config_data.nodegroups.values()]
2001 nodegroups_data = fn(utils.NiceSort(nodegroups))
2004 constants.SS_CLUSTER_NAME: cluster.cluster_name,
2005 constants.SS_CLUSTER_TAGS: cluster_tags,
2006 constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2007 constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2008 constants.SS_MASTER_CANDIDATES: mc_data,
2009 constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2010 constants.SS_MASTER_IP: cluster.master_ip,
2011 constants.SS_MASTER_NETDEV: cluster.master_netdev,
2012 constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2013 constants.SS_MASTER_NODE: cluster.master_node,
2014 constants.SS_NODE_LIST: node_data,
2015 constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2016 constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2017 constants.SS_OFFLINE_NODES: off_data,
2018 constants.SS_ONLINE_NODES: on_data,
2019 constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2020 constants.SS_INSTANCE_LIST: instance_data,
2021 constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2022 constants.SS_HYPERVISOR_LIST: hypervisor_list,
2023 constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2024 constants.SS_UID_POOL: uid_pool,
2025 constants.SS_NODEGROUPS: nodegroups_data,
2027 bad_values = [(k, v) for k, v in ssconf_values.items()
2028 if not isinstance(v, (str, basestring))]
2030 err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2031 raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2032 " values: %s" % err)
2033 return ssconf_values
2035 @locking.ssynchronized(_config_lock, shared=1)
2036 def GetSsconfValues(self):
2037 """Wrapper using lock around _UnlockedGetSsconf().
2040 return self._UnlockedGetSsconfValues()
2042 @locking.ssynchronized(_config_lock, shared=1)
2043 def GetVGName(self):
2044 """Return the volume group name.
2047 return self._config_data.cluster.volume_group_name
2049 @locking.ssynchronized(_config_lock)
2050 def SetVGName(self, vg_name):
2051 """Set the volume group name.
2054 self._config_data.cluster.volume_group_name = vg_name
2055 self._config_data.cluster.serial_no += 1
2058 @locking.ssynchronized(_config_lock, shared=1)
2059 def GetDRBDHelper(self):
2060 """Return DRBD usermode helper.
2063 return self._config_data.cluster.drbd_usermode_helper
2065 @locking.ssynchronized(_config_lock)
2066 def SetDRBDHelper(self, drbd_helper):
2067 """Set DRBD usermode helper.
2070 self._config_data.cluster.drbd_usermode_helper = drbd_helper
2071 self._config_data.cluster.serial_no += 1
2074 @locking.ssynchronized(_config_lock, shared=1)
2075 def GetMACPrefix(self):
2076 """Return the mac prefix.
2079 return self._config_data.cluster.mac_prefix
2081 @locking.ssynchronized(_config_lock, shared=1)
2082 def GetClusterInfo(self):
2083 """Returns information about the cluster
2085 @rtype: L{objects.Cluster}
2086 @return: the cluster object
2089 return self._config_data.cluster
2091 @locking.ssynchronized(_config_lock, shared=1)
2092 def HasAnyDiskOfType(self, dev_type):
2093 """Check if in there is at disk of the given type in the configuration.
2096 return self._config_data.HasAnyDiskOfType(dev_type)
2098 @locking.ssynchronized(_config_lock)
2099 def Update(self, target, feedback_fn):
2100 """Notify function to be called after updates.
2102 This function must be called when an object (as returned by
2103 GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2104 caller wants the modifications saved to the backing store. Note
2105 that all modified objects will be saved, but the target argument
2106 is the one the caller wants to ensure that it's saved.
2108 @param target: an instance of either L{objects.Cluster},
2109 L{objects.Node} or L{objects.Instance} which is existing in
2111 @param feedback_fn: Callable feedback function
2114 if self._config_data is None:
2115 raise errors.ProgrammerError("Configuration file not read,"
2117 update_serial = False
2118 if isinstance(target, objects.Cluster):
2119 test = target == self._config_data.cluster
2120 elif isinstance(target, objects.Node):
2121 test = target in self._config_data.nodes.values()
2122 update_serial = True
2123 elif isinstance(target, objects.Instance):
2124 test = target in self._config_data.instances.values()
2125 elif isinstance(target, objects.NodeGroup):
2126 test = target in self._config_data.nodegroups.values()
2128 raise errors.ProgrammerError("Invalid object type (%s) passed to"
2129 " ConfigWriter.Update" % type(target))
2131 raise errors.ConfigurationError("Configuration updated since object"
2132 " has been read or unknown object")
2133 target.serial_no += 1
2134 target.mtime = now = time.time()
2137 # for node updates, we need to increase the cluster serial too
2138 self._config_data.cluster.serial_no += 1
2139 self._config_data.cluster.mtime = now
2141 if isinstance(target, objects.Instance):
2142 self._UnlockedReleaseDRBDMinors(target.name)
2144 self._WriteConfig(feedback_fn=feedback_fn)
2146 @locking.ssynchronized(_config_lock)
2147 def DropECReservations(self, ec_id):
2148 """Drop per-execution-context reservations
2151 for rm in self._all_rms:
2152 rm.DropECReservations(ec_id)