4 # Copyright (C) 2006, 2007, 2008, 2009, 2010 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
42 from ganeti import errors
43 from ganeti import locking
44 from ganeti import utils
45 from ganeti import constants
46 from ganeti import rpc
47 from ganeti import objects
48 from ganeti import serializer
49 from ganeti import uidpool
50 from ganeti import netutils
51 from ganeti import runtime
54 _config_lock = locking.SharedLock("ConfigWriter")
56 # job id used for resource management at config upgrade time
57 _UPGRADE_CONFIG_JID = "jid-cfg-upgrade"
60 def _ValidateConfig(data):
61 """Verifies that a configuration objects looks valid.
63 This only verifies the version of the configuration.
65 @raise errors.ConfigurationError: if the version differs from what
69 if data.version != constants.CONFIG_VERSION:
70 raise errors.ConfigVersionMismatch(constants.CONFIG_VERSION, data.version)
73 class TemporaryReservationManager:
74 """A temporary resource reservation manager.
76 This is used to reserve resources in a job, before using them, making sure
77 other jobs cannot get them in the meantime.
81 self._ec_reserved = {}
83 def Reserved(self, resource):
84 for holder_reserved in self._ec_reserved.items():
85 if resource in holder_reserved:
89 def Reserve(self, ec_id, resource):
90 if self.Reserved(resource):
91 raise errors.ReservationError("Duplicate reservation for resource: %s." %
93 if ec_id not in self._ec_reserved:
94 self._ec_reserved[ec_id] = set([resource])
96 self._ec_reserved[ec_id].add(resource)
98 def DropECReservations(self, ec_id):
99 if ec_id in self._ec_reserved:
100 del self._ec_reserved[ec_id]
102 def GetReserved(self):
104 for holder_reserved in self._ec_reserved.values():
105 all_reserved.update(holder_reserved)
108 def Generate(self, existing, generate_one_fn, ec_id):
109 """Generate a new resource of this type
112 assert callable(generate_one_fn)
114 all_elems = self.GetReserved()
115 all_elems.update(existing)
118 new_resource = generate_one_fn()
119 if new_resource is not None and new_resource not in all_elems:
122 raise errors.ConfigurationError("Not able generate new resource"
123 " (last tried: %s)" % new_resource)
124 self.Reserve(ec_id, new_resource)
129 """The interface to the cluster configuration.
131 @ivar _temporary_lvs: reservation manager for temporary LVs
132 @ivar _all_rms: a list of all temporary reservation managers
135 def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts,
136 accept_foreign=False):
138 self._lock = _config_lock
139 self._config_data = None
140 self._offline = offline
142 self._cfg_file = constants.CLUSTER_CONF_FILE
144 self._cfg_file = cfg_file
145 self._getents = _getents
146 self._temporary_ids = TemporaryReservationManager()
147 self._temporary_drbds = {}
148 self._temporary_macs = TemporaryReservationManager()
149 self._temporary_secrets = TemporaryReservationManager()
150 self._temporary_lvs = TemporaryReservationManager()
151 self._all_rms = [self._temporary_ids, self._temporary_macs,
152 self._temporary_secrets, self._temporary_lvs]
153 # Note: in order to prevent errors when resolving our name in
154 # _DistributeConfig, we compute it here once and reuse it; it's
155 # better to raise an error before starting to modify the config
156 # file than after it was modified
157 self._my_hostname = netutils.Hostname.GetSysName()
158 self._last_cluster_serial = -1
160 self._OpenConfig(accept_foreign)
162 # this method needs to be static, so that we can call it on the class
165 """Check if the cluster is configured.
168 return os.path.exists(constants.CLUSTER_CONF_FILE)
170 def _GenerateOneMAC(self):
171 """Generate one mac address
174 prefix = self._config_data.cluster.mac_prefix
175 byte1 = random.randrange(0, 256)
176 byte2 = random.randrange(0, 256)
177 byte3 = random.randrange(0, 256)
178 mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
181 @locking.ssynchronized(_config_lock, shared=1)
182 def GenerateMAC(self, ec_id):
183 """Generate a MAC for an instance.
185 This should check the current instances for duplicates.
188 existing = self._AllMACs()
189 return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
191 @locking.ssynchronized(_config_lock, shared=1)
192 def ReserveMAC(self, mac, ec_id):
193 """Reserve a MAC for an instance.
195 This only checks instances managed by this cluster, it does not
196 check for potential collisions elsewhere.
199 all_macs = self._AllMACs()
201 raise errors.ReservationError("mac already in use")
203 self._temporary_macs.Reserve(mac, ec_id)
205 @locking.ssynchronized(_config_lock, shared=1)
206 def ReserveLV(self, lv_name, ec_id):
207 """Reserve an VG/LV pair for an instance.
209 @type lv_name: string
210 @param lv_name: the logical volume name to reserve
213 all_lvs = self._AllLVs()
214 if lv_name in all_lvs:
215 raise errors.ReservationError("LV already in use")
217 self._temporary_lvs.Reserve(lv_name, ec_id)
219 @locking.ssynchronized(_config_lock, shared=1)
220 def GenerateDRBDSecret(self, ec_id):
221 """Generate a DRBD secret.
223 This checks the current disks for duplicates.
226 return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
227 utils.GenerateSecret,
231 """Compute the list of all LVs.
235 for instance in self._config_data.instances.values():
236 node_data = instance.MapLVsByNode()
237 for lv_list in node_data.values():
238 lvnames.update(lv_list)
241 def _AllIDs(self, include_temporary):
242 """Compute the list of all UUIDs and names we have.
244 @type include_temporary: boolean
245 @param include_temporary: whether to include the _temporary_ids set
247 @return: a set of IDs
251 if include_temporary:
252 existing.update(self._temporary_ids.GetReserved())
253 existing.update(self._AllLVs())
254 existing.update(self._config_data.instances.keys())
255 existing.update(self._config_data.nodes.keys())
256 existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
259 def _GenerateUniqueID(self, ec_id):
260 """Generate an unique UUID.
262 This checks the current node, instances and disk names for
266 @return: the unique id
269 existing = self._AllIDs(include_temporary=False)
270 return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
272 @locking.ssynchronized(_config_lock, shared=1)
273 def GenerateUniqueID(self, ec_id):
274 """Generate an unique ID.
276 This is just a wrapper over the unlocked version.
279 @param ec_id: unique id for the job to reserve the id to
282 return self._GenerateUniqueID(ec_id)
285 """Return all MACs present in the config.
288 @return: the list of all MACs
292 for instance in self._config_data.instances.values():
293 for nic in instance.nics:
294 result.append(nic.mac)
298 def _AllDRBDSecrets(self):
299 """Return all DRBD secrets present in the config.
302 @return: the list of all DRBD secrets
305 def helper(disk, result):
306 """Recursively gather secrets from this disk."""
307 if disk.dev_type == constants.DT_DRBD8:
308 result.append(disk.logical_id[5])
310 for child in disk.children:
311 helper(child, result)
314 for instance in self._config_data.instances.values():
315 for disk in instance.disks:
320 def _CheckDiskIDs(self, disk, l_ids, p_ids):
321 """Compute duplicate disk IDs
323 @type disk: L{objects.Disk}
324 @param disk: the disk at which to start searching
326 @param l_ids: list of current logical ids
328 @param p_ids: list of current physical ids
330 @return: a list of error messages
334 if disk.logical_id is not None:
335 if disk.logical_id in l_ids:
336 result.append("duplicate logical id %s" % str(disk.logical_id))
338 l_ids.append(disk.logical_id)
339 if disk.physical_id is not None:
340 if disk.physical_id in p_ids:
341 result.append("duplicate physical id %s" % str(disk.physical_id))
343 p_ids.append(disk.physical_id)
346 for child in disk.children:
347 result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
350 def _UnlockedVerifyConfig(self):
354 @return: a list of error messages; a non-empty list signifies
361 data = self._config_data
365 # global cluster checks
366 if not data.cluster.enabled_hypervisors:
367 result.append("enabled hypervisors list doesn't have any entries")
368 invalid_hvs = set(data.cluster.enabled_hypervisors) - constants.HYPER_TYPES
370 result.append("enabled hypervisors contains invalid entries: %s" %
372 missing_hvp = (set(data.cluster.enabled_hypervisors) -
373 set(data.cluster.hvparams.keys()))
375 result.append("hypervisor parameters missing for the enabled"
376 " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
378 if data.cluster.master_node not in data.nodes:
379 result.append("cluster has invalid primary node '%s'" %
380 data.cluster.master_node)
382 # per-instance checks
383 for instance_name in data.instances:
384 instance = data.instances[instance_name]
385 if instance.name != instance_name:
386 result.append("instance '%s' is indexed by wrong name '%s'" %
387 (instance.name, instance_name))
388 if instance.primary_node not in data.nodes:
389 result.append("instance '%s' has invalid primary node '%s'" %
390 (instance_name, instance.primary_node))
391 for snode in instance.secondary_nodes:
392 if snode not in data.nodes:
393 result.append("instance '%s' has invalid secondary node '%s'" %
394 (instance_name, snode))
395 for idx, nic in enumerate(instance.nics):
396 if nic.mac in seen_macs:
397 result.append("instance '%s' has NIC %d mac %s duplicate" %
398 (instance_name, idx, nic.mac))
400 seen_macs.append(nic.mac)
402 # gather the drbd ports for duplicate checks
403 for dsk in instance.disks:
404 if dsk.dev_type in constants.LDS_DRBD:
405 tcp_port = dsk.logical_id[2]
406 if tcp_port not in ports:
408 ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
409 # gather network port reservation
410 net_port = getattr(instance, "network_port", None)
411 if net_port is not None:
412 if net_port not in ports:
414 ports[net_port].append((instance.name, "network port"))
416 # instance disk verify
417 for idx, disk in enumerate(instance.disks):
418 result.extend(["instance '%s' disk %d error: %s" %
419 (instance.name, idx, msg) for msg in disk.Verify()])
420 result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
422 # cluster-wide pool of free ports
423 for free_port in data.cluster.tcpudp_port_pool:
424 if free_port not in ports:
425 ports[free_port] = []
426 ports[free_port].append(("cluster", "port marked as free"))
428 # compute tcp/udp duplicate ports
434 txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
435 result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
437 # highest used tcp port check
439 if keys[-1] > data.cluster.highest_used_port:
440 result.append("Highest used port mismatch, saved %s, computed %s" %
441 (data.cluster.highest_used_port, keys[-1]))
443 if not data.nodes[data.cluster.master_node].master_candidate:
444 result.append("Master node is not a master candidate")
446 # master candidate checks
447 mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
449 result.append("Not enough master candidates: actual %d, target %d" %
453 for node_name, node in data.nodes.items():
454 if node.name != node_name:
455 result.append("Node '%s' is indexed by wrong name '%s'" %
456 (node.name, node_name))
457 if [node.master_candidate, node.drained, node.offline].count(True) > 1:
458 result.append("Node %s state is invalid: master_candidate=%s,"
459 " drain=%s, offline=%s" %
460 (node.name, node.master_candidate, node.drained,
464 nodegroups_names = set()
465 for nodegroup_uuid in data.nodegroups:
466 nodegroup = data.nodegroups[nodegroup_uuid]
467 if nodegroup.uuid != nodegroup_uuid:
468 result.append("nodegroup '%s' (uuid: '%s') indexed by wrong uuid '%s'"
469 % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
470 if utils.UUID_RE.match(nodegroup.name.lower()):
471 result.append("nodegroup '%s' (uuid: '%s') has uuid-like name" %
472 (nodegroup.name, nodegroup.uuid))
473 if nodegroup.name in nodegroups_names:
474 result.append("duplicate nodegroup name '%s'" % nodegroup.name)
476 nodegroups_names.add(nodegroup.name)
479 _, duplicates = self._UnlockedComputeDRBDMap()
480 for node, minor, instance_a, instance_b in duplicates:
481 result.append("DRBD minor %d on node %s is assigned twice to instances"
482 " %s and %s" % (minor, node, instance_a, instance_b))
485 default_nicparams = data.cluster.nicparams[constants.PP_DEFAULT]
488 def _AddIpAddress(ip, name):
489 ips.setdefault(ip, []).append(name)
491 _AddIpAddress(data.cluster.master_ip, "cluster_ip")
493 for node in data.nodes.values():
494 _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
495 if node.secondary_ip != node.primary_ip:
496 _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
498 for instance in data.instances.values():
499 for idx, nic in enumerate(instance.nics):
503 nicparams = objects.FillDict(default_nicparams, nic.nicparams)
504 nic_mode = nicparams[constants.NIC_MODE]
505 nic_link = nicparams[constants.NIC_LINK]
507 if nic_mode == constants.NIC_MODE_BRIDGED:
508 link = "bridge:%s" % nic_link
509 elif nic_mode == constants.NIC_MODE_ROUTED:
510 link = "route:%s" % nic_link
512 raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
514 _AddIpAddress("%s/%s" % (link, nic.ip),
515 "instance:%s/nic:%d" % (instance.name, idx))
517 for ip, owners in ips.items():
519 result.append("IP address %s is used by multiple owners: %s" %
520 (ip, utils.CommaJoin(owners)))
524 @locking.ssynchronized(_config_lock, shared=1)
525 def VerifyConfig(self):
528 This is just a wrapper over L{_UnlockedVerifyConfig}.
531 @return: a list of error messages; a non-empty list signifies
535 return self._UnlockedVerifyConfig()
537 def _UnlockedSetDiskID(self, disk, node_name):
538 """Convert the unique ID to the ID needed on the target nodes.
540 This is used only for drbd, which needs ip/port configuration.
542 The routine descends down and updates its children also, because
543 this helps when the only the top device is passed to the remote
546 This function is for internal use, when the config lock is already held.
550 for child in disk.children:
551 self._UnlockedSetDiskID(child, node_name)
553 if disk.logical_id is None and disk.physical_id is not None:
555 if disk.dev_type == constants.LD_DRBD8:
556 pnode, snode, port, pminor, sminor, secret = disk.logical_id
557 if node_name not in (pnode, snode):
558 raise errors.ConfigurationError("DRBD device not knowing node %s" %
560 pnode_info = self._UnlockedGetNodeInfo(pnode)
561 snode_info = self._UnlockedGetNodeInfo(snode)
562 if pnode_info is None or snode_info is None:
563 raise errors.ConfigurationError("Can't find primary or secondary node"
564 " for %s" % str(disk))
565 p_data = (pnode_info.secondary_ip, port)
566 s_data = (snode_info.secondary_ip, port)
567 if pnode == node_name:
568 disk.physical_id = p_data + s_data + (pminor, secret)
569 else: # it must be secondary, we tested above
570 disk.physical_id = s_data + p_data + (sminor, secret)
572 disk.physical_id = disk.logical_id
575 @locking.ssynchronized(_config_lock)
576 def SetDiskID(self, disk, node_name):
577 """Convert the unique ID to the ID needed on the target nodes.
579 This is used only for drbd, which needs ip/port configuration.
581 The routine descends down and updates its children also, because
582 this helps when the only the top device is passed to the remote
586 return self._UnlockedSetDiskID(disk, node_name)
588 @locking.ssynchronized(_config_lock)
589 def AddTcpUdpPort(self, port):
590 """Adds a new port to the available port pool.
593 if not isinstance(port, int):
594 raise errors.ProgrammerError("Invalid type passed for port")
596 self._config_data.cluster.tcpudp_port_pool.add(port)
599 @locking.ssynchronized(_config_lock, shared=1)
600 def GetPortList(self):
601 """Returns a copy of the current port list.
604 return self._config_data.cluster.tcpudp_port_pool.copy()
606 @locking.ssynchronized(_config_lock)
607 def AllocatePort(self):
610 The port will be taken from the available port pool or from the
611 default port range (and in this case we increase
615 # If there are TCP/IP ports configured, we use them first.
616 if self._config_data.cluster.tcpudp_port_pool:
617 port = self._config_data.cluster.tcpudp_port_pool.pop()
619 port = self._config_data.cluster.highest_used_port + 1
620 if port >= constants.LAST_DRBD_PORT:
621 raise errors.ConfigurationError("The highest used port is greater"
622 " than %s. Aborting." %
623 constants.LAST_DRBD_PORT)
624 self._config_data.cluster.highest_used_port = port
629 def _UnlockedComputeDRBDMap(self):
630 """Compute the used DRBD minor/nodes.
633 @return: dictionary of node_name: dict of minor: instance_name;
634 the returned dict will have all the nodes in it (even if with
635 an empty list), and a list of duplicates; if the duplicates
636 list is not empty, the configuration is corrupted and its caller
637 should raise an exception
640 def _AppendUsedPorts(instance_name, disk, used):
642 if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
643 node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
644 for node, port in ((node_a, minor_a), (node_b, minor_b)):
645 assert node in used, ("Node '%s' of instance '%s' not found"
646 " in node list" % (node, instance_name))
647 if port in used[node]:
648 duplicates.append((node, port, instance_name, used[node][port]))
650 used[node][port] = instance_name
652 for child in disk.children:
653 duplicates.extend(_AppendUsedPorts(instance_name, child, used))
657 my_dict = dict((node, {}) for node in self._config_data.nodes)
658 for instance in self._config_data.instances.itervalues():
659 for disk in instance.disks:
660 duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
661 for (node, minor), instance in self._temporary_drbds.iteritems():
662 if minor in my_dict[node] and my_dict[node][minor] != instance:
663 duplicates.append((node, minor, instance, my_dict[node][minor]))
665 my_dict[node][minor] = instance
666 return my_dict, duplicates
668 @locking.ssynchronized(_config_lock)
669 def ComputeDRBDMap(self):
670 """Compute the used DRBD minor/nodes.
672 This is just a wrapper over L{_UnlockedComputeDRBDMap}.
674 @return: dictionary of node_name: dict of minor: instance_name;
675 the returned dict will have all the nodes in it (even if with
679 d_map, duplicates = self._UnlockedComputeDRBDMap()
681 raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
685 @locking.ssynchronized(_config_lock)
686 def AllocateDRBDMinor(self, nodes, instance):
687 """Allocate a drbd minor.
689 The free minor will be automatically computed from the existing
690 devices. A node can be given multiple times in order to allocate
691 multiple minors. The result is the list of minors, in the same
692 order as the passed nodes.
694 @type instance: string
695 @param instance: the instance for which we allocate minors
698 assert isinstance(instance, basestring), \
699 "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
701 d_map, duplicates = self._UnlockedComputeDRBDMap()
703 raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
709 # no minors used, we can start at 0
712 self._temporary_drbds[(nname, 0)] = instance
716 ffree = utils.FirstFree(keys)
718 # return the next minor
719 # TODO: implement high-limit check
723 # double-check minor against current instances
724 assert minor not in d_map[nname], \
725 ("Attempt to reuse allocated DRBD minor %d on node %s,"
726 " already allocated to instance %s" %
727 (minor, nname, d_map[nname][minor]))
728 ndata[minor] = instance
729 # double-check minor against reservation
730 r_key = (nname, minor)
731 assert r_key not in self._temporary_drbds, \
732 ("Attempt to reuse reserved DRBD minor %d on node %s,"
733 " reserved for instance %s" %
734 (minor, nname, self._temporary_drbds[r_key]))
735 self._temporary_drbds[r_key] = instance
737 logging.debug("Request to allocate drbd minors, input: %s, returning %s",
741 def _UnlockedReleaseDRBDMinors(self, instance):
742 """Release temporary drbd minors allocated for a given instance.
744 @type instance: string
745 @param instance: the instance for which temporary minors should be
749 assert isinstance(instance, basestring), \
750 "Invalid argument passed to ReleaseDRBDMinors"
751 for key, name in self._temporary_drbds.items():
753 del self._temporary_drbds[key]
755 @locking.ssynchronized(_config_lock)
756 def ReleaseDRBDMinors(self, instance):
757 """Release temporary drbd minors allocated for a given instance.
759 This should be called on the error paths, on the success paths
760 it's automatically called by the ConfigWriter add and update
763 This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
765 @type instance: string
766 @param instance: the instance for which temporary minors should be
770 self._UnlockedReleaseDRBDMinors(instance)
772 @locking.ssynchronized(_config_lock, shared=1)
773 def GetConfigVersion(self):
774 """Get the configuration version.
776 @return: Config version
779 return self._config_data.version
781 @locking.ssynchronized(_config_lock, shared=1)
782 def GetClusterName(self):
785 @return: Cluster name
788 return self._config_data.cluster.cluster_name
790 @locking.ssynchronized(_config_lock, shared=1)
791 def GetMasterNode(self):
792 """Get the hostname of the master node for this cluster.
794 @return: Master hostname
797 return self._config_data.cluster.master_node
799 @locking.ssynchronized(_config_lock, shared=1)
800 def GetMasterIP(self):
801 """Get the IP of the master node for this cluster.
806 return self._config_data.cluster.master_ip
808 @locking.ssynchronized(_config_lock, shared=1)
809 def GetMasterNetdev(self):
810 """Get the master network device for this cluster.
813 return self._config_data.cluster.master_netdev
815 @locking.ssynchronized(_config_lock, shared=1)
816 def GetFileStorageDir(self):
817 """Get the file storage dir for this cluster.
820 return self._config_data.cluster.file_storage_dir
822 @locking.ssynchronized(_config_lock, shared=1)
823 def GetHypervisorType(self):
824 """Get the hypervisor type for this cluster.
827 return self._config_data.cluster.enabled_hypervisors[0]
829 @locking.ssynchronized(_config_lock, shared=1)
830 def GetHostKey(self):
831 """Return the rsa hostkey from the config.
834 @return: the rsa hostkey
837 return self._config_data.cluster.rsahostkeypub
839 @locking.ssynchronized(_config_lock, shared=1)
840 def GetDefaultIAllocator(self):
841 """Get the default instance allocator for this cluster.
844 return self._config_data.cluster.default_iallocator
846 @locking.ssynchronized(_config_lock, shared=1)
847 def GetPrimaryIPFamily(self):
848 """Get cluster primary ip family.
850 @return: primary ip family
853 return self._config_data.cluster.primary_ip_family
855 @locking.ssynchronized(_config_lock, shared=1)
856 def LookupNodeGroup(self, target):
857 """Lookup a node group.
859 @type target: string or None
860 @param target: group name or uuid or None to look for the default
862 @return: nodegroup uuid
863 @raises errors.OpPrereqError: when the target group cannot be found
867 if len(self._config_data.nodegroups) != 1:
868 raise errors.OpPrereqError("More than one nodegroup exists. Target"
869 " group must be specified explicitely.")
871 return self._config_data.nodegroups.keys()[0]
872 if target in self._config_data.nodegroups:
874 for nodegroup in self._config_data.nodegroups.values():
875 if nodegroup.name == target:
876 return nodegroup.uuid
877 raise errors.OpPrereqError("Nodegroup '%s' not found", target)
879 @locking.ssynchronized(_config_lock, shared=1)
880 def GetAllNodeGroupsInfo(self):
881 """Get the configuration of all node groups.
884 return dict(self._config_data.nodegroups)
886 @locking.ssynchronized(_config_lock, shared=1)
887 def GetNodeGroupList(self):
888 """Get a list of node groups.
891 return self._config_data.nodegroups.keys()
893 @locking.ssynchronized(_config_lock)
894 def AddInstance(self, instance, ec_id):
895 """Add an instance to the config.
897 This should be used after creating a new instance.
899 @type instance: L{objects.Instance}
900 @param instance: the instance object
903 if not isinstance(instance, objects.Instance):
904 raise errors.ProgrammerError("Invalid type passed to AddInstance")
906 if instance.disk_template != constants.DT_DISKLESS:
907 all_lvs = instance.MapLVsByNode()
908 logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
910 all_macs = self._AllMACs()
911 for nic in instance.nics:
912 if nic.mac in all_macs:
913 raise errors.ConfigurationError("Cannot add instance %s:"
914 " MAC address '%s' already in use." %
915 (instance.name, nic.mac))
917 self._EnsureUUID(instance, ec_id)
919 instance.serial_no = 1
920 instance.ctime = instance.mtime = time.time()
921 self._config_data.instances[instance.name] = instance
922 self._config_data.cluster.serial_no += 1
923 self._UnlockedReleaseDRBDMinors(instance.name)
926 def _EnsureUUID(self, item, ec_id):
927 """Ensures a given object has a valid UUID.
929 @param item: the instance or node to be checked
930 @param ec_id: the execution context id for the uuid reservation
934 item.uuid = self._GenerateUniqueID(ec_id)
935 elif item.uuid in self._AllIDs(include_temporary=True):
936 raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
937 " in use" % (item.name, item.uuid))
939 def _SetInstanceStatus(self, instance_name, status):
940 """Set the instance's status to a given value.
943 assert isinstance(status, bool), \
944 "Invalid status '%s' passed to SetInstanceStatus" % (status,)
946 if instance_name not in self._config_data.instances:
947 raise errors.ConfigurationError("Unknown instance '%s'" %
949 instance = self._config_data.instances[instance_name]
950 if instance.admin_up != status:
951 instance.admin_up = status
952 instance.serial_no += 1
953 instance.mtime = time.time()
956 @locking.ssynchronized(_config_lock)
957 def MarkInstanceUp(self, instance_name):
958 """Mark the instance status to up in the config.
961 self._SetInstanceStatus(instance_name, True)
963 @locking.ssynchronized(_config_lock)
964 def RemoveInstance(self, instance_name):
965 """Remove the instance from the configuration.
968 if instance_name not in self._config_data.instances:
969 raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
970 del self._config_data.instances[instance_name]
971 self._config_data.cluster.serial_no += 1
974 @locking.ssynchronized(_config_lock)
975 def RenameInstance(self, old_name, new_name):
976 """Rename an instance.
978 This needs to be done in ConfigWriter and not by RemoveInstance
979 combined with AddInstance as only we can guarantee an atomic
983 if old_name not in self._config_data.instances:
984 raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
985 inst = self._config_data.instances[old_name]
986 del self._config_data.instances[old_name]
989 for disk in inst.disks:
990 if disk.dev_type == constants.LD_FILE:
991 # rename the file paths in logical and physical id
992 file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
993 disk.physical_id = disk.logical_id = (disk.logical_id[0],
994 utils.PathJoin(file_storage_dir,
998 self._config_data.instances[inst.name] = inst
1001 @locking.ssynchronized(_config_lock)
1002 def MarkInstanceDown(self, instance_name):
1003 """Mark the status of an instance to down in the configuration.
1006 self._SetInstanceStatus(instance_name, False)
1008 def _UnlockedGetInstanceList(self):
1009 """Get the list of instances.
1011 This function is for internal use, when the config lock is already held.
1014 return self._config_data.instances.keys()
1016 @locking.ssynchronized(_config_lock, shared=1)
1017 def GetInstanceList(self):
1018 """Get the list of instances.
1020 @return: array of instances, ex. ['instance2.example.com',
1021 'instance1.example.com']
1024 return self._UnlockedGetInstanceList()
1026 @locking.ssynchronized(_config_lock, shared=1)
1027 def ExpandInstanceName(self, short_name):
1028 """Attempt to expand an incomplete instance name.
1031 return utils.MatchNameComponent(short_name,
1032 self._config_data.instances.keys(),
1033 case_sensitive=False)
1035 def _UnlockedGetInstanceInfo(self, instance_name):
1036 """Returns information about an instance.
1038 This function is for internal use, when the config lock is already held.
1041 if instance_name not in self._config_data.instances:
1044 return self._config_data.instances[instance_name]
1046 @locking.ssynchronized(_config_lock, shared=1)
1047 def GetInstanceInfo(self, instance_name):
1048 """Returns information about an instance.
1050 It takes the information from the configuration file. Other information of
1051 an instance are taken from the live systems.
1053 @param instance_name: name of the instance, e.g.
1054 I{instance1.example.com}
1056 @rtype: L{objects.Instance}
1057 @return: the instance object
1060 return self._UnlockedGetInstanceInfo(instance_name)
1062 @locking.ssynchronized(_config_lock, shared=1)
1063 def GetAllInstancesInfo(self):
1064 """Get the configuration of all instances.
1067 @return: dict of (instance, instance_info), where instance_info is what
1068 would GetInstanceInfo return for the node
1071 my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1072 for instance in self._UnlockedGetInstanceList()])
1075 @locking.ssynchronized(_config_lock)
1076 def AddNode(self, node, ec_id):
1077 """Add a node to the configuration.
1079 @type node: L{objects.Node}
1080 @param node: a Node instance
1083 logging.info("Adding node %s to configuration", node.name)
1085 self._EnsureUUID(node, ec_id)
1088 node.ctime = node.mtime = time.time()
1089 self._UnlockedAddNodeToGroup(node.name, node.group)
1090 self._config_data.nodes[node.name] = node
1091 self._config_data.cluster.serial_no += 1
1094 @locking.ssynchronized(_config_lock)
1095 def RemoveNode(self, node_name):
1096 """Remove a node from the configuration.
1099 logging.info("Removing node %s from configuration", node_name)
1101 if node_name not in self._config_data.nodes:
1102 raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1104 self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1105 del self._config_data.nodes[node_name]
1106 self._config_data.cluster.serial_no += 1
1109 @locking.ssynchronized(_config_lock, shared=1)
1110 def ExpandNodeName(self, short_name):
1111 """Attempt to expand an incomplete instance name.
1114 return utils.MatchNameComponent(short_name,
1115 self._config_data.nodes.keys(),
1116 case_sensitive=False)
1118 def _UnlockedGetNodeInfo(self, node_name):
1119 """Get the configuration of a node, as stored in the config.
1121 This function is for internal use, when the config lock is already
1124 @param node_name: the node name, e.g. I{node1.example.com}
1126 @rtype: L{objects.Node}
1127 @return: the node object
1130 if node_name not in self._config_data.nodes:
1133 return self._config_data.nodes[node_name]
1135 @locking.ssynchronized(_config_lock, shared=1)
1136 def GetNodeInfo(self, node_name):
1137 """Get the configuration of a node, as stored in the config.
1139 This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1141 @param node_name: the node name, e.g. I{node1.example.com}
1143 @rtype: L{objects.Node}
1144 @return: the node object
1147 return self._UnlockedGetNodeInfo(node_name)
1149 @locking.ssynchronized(_config_lock, shared=1)
1150 def GetNodeInstances(self, node_name):
1151 """Get the instances of a node, as stored in the config.
1153 @param node_name: the node name, e.g. I{node1.example.com}
1155 @rtype: (list, list)
1156 @return: a tuple with two lists: the primary and the secondary instances
1161 for inst in self._config_data.instances.values():
1162 if inst.primary_node == node_name:
1163 pri.append(inst.name)
1164 if node_name in inst.secondary_nodes:
1165 sec.append(inst.name)
1168 def _UnlockedGetNodeList(self):
1169 """Return the list of nodes which are in the configuration.
1171 This function is for internal use, when the config lock is already
1177 return self._config_data.nodes.keys()
1179 @locking.ssynchronized(_config_lock, shared=1)
1180 def GetNodeList(self):
1181 """Return the list of nodes which are in the configuration.
1184 return self._UnlockedGetNodeList()
1186 def _UnlockedGetOnlineNodeList(self):
1187 """Return the list of nodes which are online.
1190 all_nodes = [self._UnlockedGetNodeInfo(node)
1191 for node in self._UnlockedGetNodeList()]
1192 return [node.name for node in all_nodes if not node.offline]
1194 @locking.ssynchronized(_config_lock, shared=1)
1195 def GetOnlineNodeList(self):
1196 """Return the list of nodes which are online.
1199 return self._UnlockedGetOnlineNodeList()
1201 @locking.ssynchronized(_config_lock, shared=1)
1202 def GetNonVmCapableNodeList(self):
1203 """Return the list of nodes which are not vm capable.
1206 all_nodes = [self._UnlockedGetNodeInfo(node)
1207 for node in self._UnlockedGetNodeList()]
1208 return [node.name for node in all_nodes if not node.vm_capable]
1210 @locking.ssynchronized(_config_lock, shared=1)
1211 def GetAllNodesInfo(self):
1212 """Get the configuration of all nodes.
1215 @return: dict of (node, node_info), where node_info is what
1216 would GetNodeInfo return for the node
1219 my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
1220 for node in self._UnlockedGetNodeList()])
1223 def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1224 """Get the number of current and maximum desired and possible candidates.
1226 @type exceptions: list
1227 @param exceptions: if passed, list of nodes that should be ignored
1229 @return: tuple of (current, desired and possible, possible)
1232 mc_now = mc_should = mc_max = 0
1233 for node in self._config_data.nodes.values():
1234 if exceptions and node.name in exceptions:
1236 if not (node.offline or node.drained) and node.master_capable:
1238 if node.master_candidate:
1240 mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1241 return (mc_now, mc_should, mc_max)
1243 @locking.ssynchronized(_config_lock, shared=1)
1244 def GetMasterCandidateStats(self, exceptions=None):
1245 """Get the number of current and maximum possible candidates.
1247 This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1249 @type exceptions: list
1250 @param exceptions: if passed, list of nodes that should be ignored
1252 @return: tuple of (current, max)
1255 return self._UnlockedGetMasterCandidateStats(exceptions)
1257 @locking.ssynchronized(_config_lock)
1258 def MaintainCandidatePool(self, exceptions):
1259 """Try to grow the candidate pool to the desired size.
1261 @type exceptions: list
1262 @param exceptions: if passed, list of nodes that should be ignored
1264 @return: list with the adjusted nodes (L{objects.Node} instances)
1267 mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1270 node_list = self._config_data.nodes.keys()
1271 random.shuffle(node_list)
1272 for name in node_list:
1273 if mc_now >= mc_max:
1275 node = self._config_data.nodes[name]
1276 if (node.master_candidate or node.offline or node.drained or
1277 node.name in exceptions or not node.master_capable):
1279 mod_list.append(node)
1280 node.master_candidate = True
1283 if mc_now != mc_max:
1284 # this should not happen
1285 logging.warning("Warning: MaintainCandidatePool didn't manage to"
1286 " fill the candidate pool (%d/%d)", mc_now, mc_max)
1288 self._config_data.cluster.serial_no += 1
1293 def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1294 """Add a given node to the specified group.
1297 if nodegroup_uuid not in self._config_data.nodegroups:
1298 # This can happen if a node group gets deleted between its lookup and
1299 # when we're adding the first node to it, since we don't keep a lock in
1300 # the meantime. It's ok though, as we'll fail cleanly if the node group
1301 # is not found anymore.
1302 raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1303 if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1304 self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1306 def _UnlockedRemoveNodeFromGroup(self, node):
1307 """Remove a given node from its group.
1310 nodegroup = node.group
1311 if nodegroup not in self._config_data.nodegroups:
1312 logging.warning("Warning: node '%s' has unknown node group '%s'"
1313 " (while being removed from it)", node.name, nodegroup)
1314 nodegroup_obj = self._config_data.nodegroups[nodegroup]
1315 if node.name not in nodegroup_obj.members:
1316 logging.warning("Warning: node '%s' not a member of its node group '%s'"
1317 " (while being removed from it)", node.name, nodegroup)
1319 nodegroup_obj.members.remove(node.name)
1321 def _BumpSerialNo(self):
1322 """Bump up the serial number of the config.
1325 self._config_data.serial_no += 1
1326 self._config_data.mtime = time.time()
1328 def _AllUUIDObjects(self):
1329 """Returns all objects with uuid attributes.
1332 return (self._config_data.instances.values() +
1333 self._config_data.nodes.values() +
1334 self._config_data.nodegroups.values() +
1335 [self._config_data.cluster])
1337 def _OpenConfig(self, accept_foreign):
1338 """Read the config data from disk.
1341 raw_data = utils.ReadFile(self._cfg_file)
1344 data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1345 except Exception, err:
1346 raise errors.ConfigurationError(err)
1348 # Make sure the configuration has the right version
1349 _ValidateConfig(data)
1351 if (not hasattr(data, 'cluster') or
1352 not hasattr(data.cluster, 'rsahostkeypub')):
1353 raise errors.ConfigurationError("Incomplete configuration"
1354 " (missing cluster.rsahostkeypub)")
1356 if data.cluster.master_node != self._my_hostname and not accept_foreign:
1357 msg = ("The configuration denotes node %s as master, while my"
1358 " hostname is %s; opening a foreign configuration is only"
1359 " possible in accept_foreign mode" %
1360 (data.cluster.master_node, self._my_hostname))
1361 raise errors.ConfigurationError(msg)
1363 # Upgrade configuration if needed
1364 data.UpgradeConfig()
1366 self._config_data = data
1367 # reset the last serial as -1 so that the next write will cause
1369 self._last_cluster_serial = -1
1371 # And finally run our (custom) config upgrade sequence
1372 self._UpgradeConfig()
1374 self._cfg_id = utils.GetFileID(path=self._cfg_file)
1376 def _UpgradeConfig(self):
1377 """Run upgrade steps that cannot be done purely in the objects.
1379 This is because some data elements need uniqueness across the
1380 whole configuration, etc.
1382 @warning: this function will call L{_WriteConfig()}, but also
1383 L{DropECReservations} so it needs to be called only from a
1384 "safe" place (the constructor). If one wanted to call it with
1385 the lock held, a DropECReservationUnlocked would need to be
1386 created first, to avoid causing deadlock.
1390 for item in self._AllUUIDObjects():
1391 if item.uuid is None:
1392 item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1394 if not self._config_data.nodegroups:
1395 default_nodegroup_uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1396 default_nodegroup = objects.NodeGroup(
1397 uuid=default_nodegroup_uuid,
1401 self._config_data.nodegroups[default_nodegroup_uuid] = default_nodegroup
1403 for node in self._config_data.nodes.values():
1405 node.group = self.LookupNodeGroup(None)
1407 # This is technically *not* an upgrade, but needs to be done both when
1408 # nodegroups are being added, and upon normally loading the config,
1409 # because the members list of a node group is discarded upon
1410 # serializing/deserializing the object.
1411 self._UnlockedAddNodeToGroup(node.name, node.group)
1414 # This is ok even if it acquires the internal lock, as _UpgradeConfig is
1415 # only called at config init time, without the lock held
1416 self.DropECReservations(_UPGRADE_CONFIG_JID)
1418 def _DistributeConfig(self, feedback_fn):
1419 """Distribute the configuration to the other nodes.
1421 Currently, this only copies the configuration file. In the future,
1422 it could be used to encapsulate the 2/3-phase update mechanism.
1432 myhostname = self._my_hostname
1433 # we can skip checking whether _UnlockedGetNodeInfo returns None
1434 # since the node list comes from _UnlocketGetNodeList, and we are
1435 # called with the lock held, so no modifications should take place
1437 for node_name in self._UnlockedGetNodeList():
1438 if node_name == myhostname:
1440 node_info = self._UnlockedGetNodeInfo(node_name)
1441 if not node_info.master_candidate:
1443 node_list.append(node_info.name)
1444 addr_list.append(node_info.primary_ip)
1446 result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
1447 address_list=addr_list)
1448 for to_node, to_result in result.items():
1449 msg = to_result.fail_msg
1451 msg = ("Copy of file %s to node %s failed: %s" %
1452 (self._cfg_file, to_node, msg))
1462 def _WriteConfig(self, destination=None, feedback_fn=None):
1463 """Write the configuration data to persistent storage.
1466 assert feedback_fn is None or callable(feedback_fn)
1468 # Warn on config errors, but don't abort the save - the
1469 # configuration has already been modified, and we can't revert;
1470 # the best we can do is to warn the user and save as is, leaving
1471 # recovery to the user
1472 config_errors = self._UnlockedVerifyConfig()
1474 errmsg = ("Configuration data is not consistent: %s" %
1475 (utils.CommaJoin(config_errors)))
1476 logging.critical(errmsg)
1480 if destination is None:
1481 destination = self._cfg_file
1482 self._BumpSerialNo()
1483 txt = serializer.Dump(self._config_data.ToDict())
1485 getents = self._getents()
1487 fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
1488 close=False, gid=getents.confd_gid, mode=0640)
1489 except errors.LockError:
1490 raise errors.ConfigurationError("The configuration file has been"
1491 " modified since the last write, cannot"
1494 self._cfg_id = utils.GetFileID(fd=fd)
1498 self.write_count += 1
1500 # and redistribute the config file to master candidates
1501 self._DistributeConfig(feedback_fn)
1503 # Write ssconf files on all nodes (including locally)
1504 if self._last_cluster_serial < self._config_data.cluster.serial_no:
1505 if not self._offline:
1506 result = rpc.RpcRunner.call_write_ssconf_files(
1507 self._UnlockedGetOnlineNodeList(),
1508 self._UnlockedGetSsconfValues())
1510 for nname, nresu in result.items():
1511 msg = nresu.fail_msg
1513 errmsg = ("Error while uploading ssconf files to"
1514 " node %s: %s" % (nname, msg))
1515 logging.warning(errmsg)
1520 self._last_cluster_serial = self._config_data.cluster.serial_no
1522 def _UnlockedGetSsconfValues(self):
1523 """Return the values needed by ssconf.
1526 @return: a dictionary with keys the ssconf names and values their
1531 instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1532 node_names = utils.NiceSort(self._UnlockedGetNodeList())
1533 node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1534 node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
1535 for ninfo in node_info]
1536 node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
1537 for ninfo in node_info]
1539 instance_data = fn(instance_names)
1540 off_data = fn(node.name for node in node_info if node.offline)
1541 on_data = fn(node.name for node in node_info if not node.offline)
1542 mc_data = fn(node.name for node in node_info if node.master_candidate)
1543 mc_ips_data = fn(node.primary_ip for node in node_info
1544 if node.master_candidate)
1545 node_data = fn(node_names)
1546 node_pri_ips_data = fn(node_pri_ips)
1547 node_snd_ips_data = fn(node_snd_ips)
1549 cluster = self._config_data.cluster
1550 cluster_tags = fn(cluster.GetTags())
1552 hypervisor_list = fn(cluster.enabled_hypervisors)
1554 uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
1556 nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
1557 self._config_data.nodegroups.values()]
1558 nodegroups_data = fn(utils.NiceSort(nodegroups))
1561 constants.SS_CLUSTER_NAME: cluster.cluster_name,
1562 constants.SS_CLUSTER_TAGS: cluster_tags,
1563 constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1564 constants.SS_MASTER_CANDIDATES: mc_data,
1565 constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
1566 constants.SS_MASTER_IP: cluster.master_ip,
1567 constants.SS_MASTER_NETDEV: cluster.master_netdev,
1568 constants.SS_MASTER_NODE: cluster.master_node,
1569 constants.SS_NODE_LIST: node_data,
1570 constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
1571 constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
1572 constants.SS_OFFLINE_NODES: off_data,
1573 constants.SS_ONLINE_NODES: on_data,
1574 constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
1575 constants.SS_INSTANCE_LIST: instance_data,
1576 constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1577 constants.SS_HYPERVISOR_LIST: hypervisor_list,
1578 constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
1579 constants.SS_UID_POOL: uid_pool,
1580 constants.SS_NODEGROUPS: nodegroups_data,
1583 @locking.ssynchronized(_config_lock, shared=1)
1584 def GetSsconfValues(self):
1585 """Wrapper using lock around _UnlockedGetSsconf().
1588 return self._UnlockedGetSsconfValues()
1590 @locking.ssynchronized(_config_lock, shared=1)
1591 def GetVGName(self):
1592 """Return the volume group name.
1595 return self._config_data.cluster.volume_group_name
1597 @locking.ssynchronized(_config_lock)
1598 def SetVGName(self, vg_name):
1599 """Set the volume group name.
1602 self._config_data.cluster.volume_group_name = vg_name
1603 self._config_data.cluster.serial_no += 1
1606 @locking.ssynchronized(_config_lock, shared=1)
1607 def GetDRBDHelper(self):
1608 """Return DRBD usermode helper.
1611 return self._config_data.cluster.drbd_usermode_helper
1613 @locking.ssynchronized(_config_lock)
1614 def SetDRBDHelper(self, drbd_helper):
1615 """Set DRBD usermode helper.
1618 self._config_data.cluster.drbd_usermode_helper = drbd_helper
1619 self._config_data.cluster.serial_no += 1
1622 @locking.ssynchronized(_config_lock, shared=1)
1623 def GetMACPrefix(self):
1624 """Return the mac prefix.
1627 return self._config_data.cluster.mac_prefix
1629 @locking.ssynchronized(_config_lock, shared=1)
1630 def GetClusterInfo(self):
1631 """Returns information about the cluster
1633 @rtype: L{objects.Cluster}
1634 @return: the cluster object
1637 return self._config_data.cluster
1639 @locking.ssynchronized(_config_lock, shared=1)
1640 def HasAnyDiskOfType(self, dev_type):
1641 """Check if in there is at disk of the given type in the configuration.
1644 return self._config_data.HasAnyDiskOfType(dev_type)
1646 @locking.ssynchronized(_config_lock)
1647 def Update(self, target, feedback_fn):
1648 """Notify function to be called after updates.
1650 This function must be called when an object (as returned by
1651 GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
1652 caller wants the modifications saved to the backing store. Note
1653 that all modified objects will be saved, but the target argument
1654 is the one the caller wants to ensure that it's saved.
1656 @param target: an instance of either L{objects.Cluster},
1657 L{objects.Node} or L{objects.Instance} which is existing in
1659 @param feedback_fn: Callable feedback function
1662 if self._config_data is None:
1663 raise errors.ProgrammerError("Configuration file not read,"
1665 update_serial = False
1666 if isinstance(target, objects.Cluster):
1667 test = target == self._config_data.cluster
1668 elif isinstance(target, objects.Node):
1669 test = target in self._config_data.nodes.values()
1670 update_serial = True
1671 elif isinstance(target, objects.Instance):
1672 test = target in self._config_data.instances.values()
1674 raise errors.ProgrammerError("Invalid object type (%s) passed to"
1675 " ConfigWriter.Update" % type(target))
1677 raise errors.ConfigurationError("Configuration updated since object"
1678 " has been read or unknown object")
1679 target.serial_no += 1
1680 target.mtime = now = time.time()
1683 # for node updates, we need to increase the cluster serial too
1684 self._config_data.cluster.serial_no += 1
1685 self._config_data.cluster.mtime = now
1687 if isinstance(target, objects.Instance):
1688 self._UnlockedReleaseDRBDMinors(target.name)
1690 self._WriteConfig(feedback_fn=feedback_fn)
1692 @locking.ssynchronized(_config_lock)
1693 def DropECReservations(self, ec_id):
1694 """Drop per-execution-context reservations
1697 for rm in self._all_rms:
1698 rm.DropECReservations(ec_id)