Instance policy command line support
[ganeti-local] / lib / config.py
1 #
2 #
3
4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
5 #
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.
10 #
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.
15 #
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
19 # 02110-1301, USA.
20
21
22 """Configuration management for Ganeti
23
24 This module provides the interface to the Ganeti cluster configuration.
25
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.
28
29 Currently, the data storage format is JSON. YAML was slow and consuming too
30 much memory.
31
32 """
33
34 # pylint: disable=R0904
35 # R0904: Too many public methods
36
37 import os
38 import random
39 import logging
40 import time
41 import itertools
42
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
53
54
55 _config_lock = locking.SharedLock("ConfigWriter")
56
57 # job id used for resource management at config upgrade time
58 _UPGRADE_CONFIG_JID = "jid-cfg-upgrade"
59
60
61 def _ValidateConfig(data):
62   """Verifies that a configuration objects looks valid.
63
64   This only verifies the version of the configuration.
65
66   @raise errors.ConfigurationError: if the version differs from what
67       we expect
68
69   """
70   if data.version != constants.CONFIG_VERSION:
71     raise errors.ConfigVersionMismatch(constants.CONFIG_VERSION, data.version)
72
73
74 class TemporaryReservationManager:
75   """A temporary resource reservation manager.
76
77   This is used to reserve resources in a job, before using them, making sure
78   other jobs cannot get them in the meantime.
79
80   """
81   def __init__(self):
82     self._ec_reserved = {}
83
84   def Reserved(self, resource):
85     for holder_reserved in self._ec_reserved.values():
86       if resource in holder_reserved:
87         return True
88     return False
89
90   def Reserve(self, ec_id, resource):
91     if self.Reserved(resource):
92       raise errors.ReservationError("Duplicate reservation for resource '%s'"
93                                     % str(resource))
94     if ec_id not in self._ec_reserved:
95       self._ec_reserved[ec_id] = set([resource])
96     else:
97       self._ec_reserved[ec_id].add(resource)
98
99   def DropECReservations(self, ec_id):
100     if ec_id in self._ec_reserved:
101       del self._ec_reserved[ec_id]
102
103   def GetReserved(self):
104     all_reserved = set()
105     for holder_reserved in self._ec_reserved.values():
106       all_reserved.update(holder_reserved)
107     return all_reserved
108
109   def Generate(self, existing, generate_one_fn, ec_id):
110     """Generate a new resource of this type
111
112     """
113     assert callable(generate_one_fn)
114
115     all_elems = self.GetReserved()
116     all_elems.update(existing)
117     retries = 64
118     while retries > 0:
119       new_resource = generate_one_fn()
120       if new_resource is not None and new_resource not in all_elems:
121         break
122     else:
123       raise errors.ConfigurationError("Not able generate new resource"
124                                       " (last tried: %s)" % new_resource)
125     self.Reserve(ec_id, new_resource)
126     return new_resource
127
128
129 def _MatchNameComponentIgnoreCase(short_name, names):
130   """Wrapper around L{utils.text.MatchNameComponent}.
131
132   """
133   return utils.MatchNameComponent(short_name, names, case_sensitive=False)
134
135
136 class ConfigWriter:
137   """The interface to the cluster configuration.
138
139   @ivar _temporary_lvs: reservation manager for temporary LVs
140   @ivar _all_rms: a list of all temporary reservation managers
141
142   """
143   def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts,
144                accept_foreign=False):
145     self.write_count = 0
146     self._lock = _config_lock
147     self._config_data = None
148     self._offline = offline
149     if cfg_file is None:
150       self._cfg_file = constants.CLUSTER_CONF_FILE
151     else:
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
167     self._cfg_id = None
168     self._context = None
169     self._OpenConfig(accept_foreign)
170
171   def _GetRpc(self, address_list):
172     """Returns RPC runner for configuration.
173
174     """
175     return rpc.ConfigRunner(self._context, address_list)
176
177   def SetContext(self, context):
178     """Sets Ganeti context.
179
180     """
181     self._context = context
182
183   # this method needs to be static, so that we can call it on the class
184   @staticmethod
185   def IsCluster():
186     """Check if the cluster is configured.
187
188     """
189     return os.path.exists(constants.CLUSTER_CONF_FILE)
190
191   def _GenerateOneMAC(self):
192     """Generate one mac address
193
194     """
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)
200     return mac
201
202   @locking.ssynchronized(_config_lock, shared=1)
203   def GetNdParams(self, node):
204     """Get the node params populated with cluster defaults.
205
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
209
210     """
211     nodegroup = self._UnlockedGetNodeGroup(node.group)
212     return self._config_data.cluster.FillND(node, nodegroup)
213
214   @locking.ssynchronized(_config_lock, shared=1)
215   def GenerateMAC(self, ec_id):
216     """Generate a MAC for an instance.
217
218     This should check the current instances for duplicates.
219
220     """
221     existing = self._AllMACs()
222     return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
223
224   @locking.ssynchronized(_config_lock, shared=1)
225   def ReserveMAC(self, mac, ec_id):
226     """Reserve a MAC for an instance.
227
228     This only checks instances managed by this cluster, it does not
229     check for potential collisions elsewhere.
230
231     """
232     all_macs = self._AllMACs()
233     if mac in all_macs:
234       raise errors.ReservationError("mac already in use")
235     else:
236       self._temporary_macs.Reserve(ec_id, mac)
237
238   @locking.ssynchronized(_config_lock, shared=1)
239   def ReserveLV(self, lv_name, ec_id):
240     """Reserve an VG/LV pair for an instance.
241
242     @type lv_name: string
243     @param lv_name: the logical volume name to reserve
244
245     """
246     all_lvs = self._AllLVs()
247     if lv_name in all_lvs:
248       raise errors.ReservationError("LV already in use")
249     else:
250       self._temporary_lvs.Reserve(ec_id, lv_name)
251
252   @locking.ssynchronized(_config_lock, shared=1)
253   def GenerateDRBDSecret(self, ec_id):
254     """Generate a DRBD secret.
255
256     This checks the current disks for duplicates.
257
258     """
259     return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
260                                             utils.GenerateSecret,
261                                             ec_id)
262
263   def _AllLVs(self):
264     """Compute the list of all LVs.
265
266     """
267     lvnames = set()
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)
272     return lvnames
273
274   def _AllIDs(self, include_temporary):
275     """Compute the list of all UUIDs and names we have.
276
277     @type include_temporary: boolean
278     @param include_temporary: whether to include the _temporary_ids set
279     @rtype: set
280     @return: a set of IDs
281
282     """
283     existing = set()
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])
290     return existing
291
292   def _GenerateUniqueID(self, ec_id):
293     """Generate an unique UUID.
294
295     This checks the current node, instances and disk names for
296     duplicates.
297
298     @rtype: string
299     @return: the unique id
300
301     """
302     existing = self._AllIDs(include_temporary=False)
303     return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
304
305   @locking.ssynchronized(_config_lock, shared=1)
306   def GenerateUniqueID(self, ec_id):
307     """Generate an unique ID.
308
309     This is just a wrapper over the unlocked version.
310
311     @type ec_id: string
312     @param ec_id: unique id for the job to reserve the id to
313
314     """
315     return self._GenerateUniqueID(ec_id)
316
317   def _AllMACs(self):
318     """Return all MACs present in the config.
319
320     @rtype: list
321     @return: the list of all MACs
322
323     """
324     result = []
325     for instance in self._config_data.instances.values():
326       for nic in instance.nics:
327         result.append(nic.mac)
328
329     return result
330
331   def _AllDRBDSecrets(self):
332     """Return all DRBD secrets present in the config.
333
334     @rtype: list
335     @return: the list of all DRBD secrets
336
337     """
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])
342       if disk.children:
343         for child in disk.children:
344           helper(child, result)
345
346     result = []
347     for instance in self._config_data.instances.values():
348       for disk in instance.disks:
349         helper(disk, result)
350
351     return result
352
353   def _CheckDiskIDs(self, disk, l_ids, p_ids):
354     """Compute duplicate disk IDs
355
356     @type disk: L{objects.Disk}
357     @param disk: the disk at which to start searching
358     @type l_ids: list
359     @param l_ids: list of current logical ids
360     @type p_ids: list
361     @param p_ids: list of current physical ids
362     @rtype: list
363     @return: a list of error messages
364
365     """
366     result = []
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))
370       else:
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))
375       else:
376         p_ids.append(disk.physical_id)
377
378     if disk.children:
379       for child in disk.children:
380         result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
381     return result
382
383   def _UnlockedVerifyConfig(self):
384     """Verify function.
385
386     @rtype: list
387     @return: a list of error messages; a non-empty list signifies
388         configuration errors
389
390     """
391     # pylint: disable=R0914
392     result = []
393     seen_macs = []
394     ports = {}
395     data = self._config_data
396     cluster = data.cluster
397     seen_lids = []
398     seen_pids = []
399
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
404     if invalid_hvs:
405       result.append("enabled hypervisors contains invalid entries: %s" %
406                     invalid_hvs)
407     missing_hvp = (set(cluster.enabled_hypervisors) -
408                    set(cluster.hvparams.keys()))
409     if missing_hvp:
410       result.append("hypervisor parameters missing for the enabled"
411                     " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
412
413     if cluster.master_node not in data.nodes:
414       result.append("cluster has invalid primary node '%s'" %
415                     cluster.master_node)
416
417     def _helper(owner, attr, value, template):
418       try:
419         utils.ForceDictType(value, template)
420       except errors.GenericError, err:
421         result.append("%s has invalid %s: %s" % (owner, attr, err))
422
423     def _helper_nic(owner, params):
424       try:
425         objects.NIC.CheckParameterSyntax(params)
426       except errors.ConfigurationError, err:
427         result.append("%s has invalid nicparams: %s" % (owner, err))
428
429     def _helper_ipolicy(owner, params):
430       try:
431         objects.InstancePolicy.CheckParameterSyntax(params)
432       except errors.ConfigurationError, err:
433         result.append("%s has invalid instance policy: %s" % (owner, err))
434
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)
439
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({}))
450
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))
468         else:
469           seen_macs.append(nic.mac)
470         if nic.nicparams:
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)
476
477       # parameter checks
478       if instance.beparams:
479         _helper("instance %s" % instance.name, "beparams",
480                 cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
481
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:
487             ports[tcp_port] = []
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:
493           ports[net_port] = []
494         ports[net_port].append((instance.name, "network port"))
495
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))
501
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"))
507
508     # compute tcp/udp duplicate ports
509     keys = ports.keys()
510     keys.sort()
511     for pnum in keys:
512       pdata = ports[pnum]
513       if len(pdata) > 1:
514         txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
515         result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
516
517     # highest used tcp port check
518     if keys:
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]))
522
523     if not data.nodes[cluster.master_node].master_candidate:
524       result.append("Master node is not a master candidate")
525
526     # master candidate checks
527     mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
528     if mc_now < mc_max:
529       result.append("Not enough master candidates: actual %d, target %d" %
530                     (mc_now, mc_max))
531
532     # node checks
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,
541                        node.offline))
542       if node.group not in data.nodegroups:
543         result.append("Node '%s' has invalid group '%s'" %
544                       (node.name, node.group))
545       else:
546         _helper("node %s" % node.name, "ndparams",
547                 cluster.FillND(node, data.nodegroups[node.group]),
548                 constants.NDS_PARAMETER_TYPES)
549
550     # nodegroups checks
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)
562       else:
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)
568
569     # drbd minors check
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))
574
575     # IP checks
576     default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
577     ips = {}
578
579     def _AddIpAddress(ip, name):
580       ips.setdefault(ip, []).append(name)
581
582     _AddIpAddress(cluster.master_ip, "cluster_ip")
583
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)
588
589     for instance in data.instances.values():
590       for idx, nic in enumerate(instance.nics):
591         if nic.ip is None:
592           continue
593
594         nicparams = objects.FillDict(default_nicparams, nic.nicparams)
595         nic_mode = nicparams[constants.NIC_MODE]
596         nic_link = nicparams[constants.NIC_LINK]
597
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
602         else:
603           raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
604
605         _AddIpAddress("%s/%s" % (link, nic.ip),
606                       "instance:%s/nic:%d" % (instance.name, idx))
607
608     for ip, owners in ips.items():
609       if len(owners) > 1:
610         result.append("IP address %s is used by multiple owners: %s" %
611                       (ip, utils.CommaJoin(owners)))
612
613     return result
614
615   @locking.ssynchronized(_config_lock, shared=1)
616   def VerifyConfig(self):
617     """Verify function.
618
619     This is just a wrapper over L{_UnlockedVerifyConfig}.
620
621     @rtype: list
622     @return: a list of error messages; a non-empty list signifies
623         configuration errors
624
625     """
626     return self._UnlockedVerifyConfig()
627
628   def _UnlockedSetDiskID(self, disk, node_name):
629     """Convert the unique ID to the ID needed on the target nodes.
630
631     This is used only for drbd, which needs ip/port configuration.
632
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
635     node.
636
637     This function is for internal use, when the config lock is already held.
638
639     """
640     if disk.children:
641       for child in disk.children:
642         self._UnlockedSetDiskID(child, node_name)
643
644     if disk.logical_id is None and disk.physical_id is not None:
645       return
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" %
650                                         node_name)
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)
662     else:
663       disk.physical_id = disk.logical_id
664     return
665
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.
669
670     This is used only for drbd, which needs ip/port configuration.
671
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
674     node.
675
676     """
677     return self._UnlockedSetDiskID(disk, node_name)
678
679   @locking.ssynchronized(_config_lock)
680   def AddTcpUdpPort(self, port):
681     """Adds a new port to the available port pool.
682
683     """
684     if not isinstance(port, int):
685       raise errors.ProgrammerError("Invalid type passed for port")
686
687     self._config_data.cluster.tcpudp_port_pool.add(port)
688     self._WriteConfig()
689
690   @locking.ssynchronized(_config_lock, shared=1)
691   def GetPortList(self):
692     """Returns a copy of the current port list.
693
694     """
695     return self._config_data.cluster.tcpudp_port_pool.copy()
696
697   @locking.ssynchronized(_config_lock)
698   def AllocatePort(self):
699     """Allocate a port.
700
701     The port will be taken from the available port pool or from the
702     default port range (and in this case we increase
703     highest_used_port).
704
705     """
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()
709     else:
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
716
717     self._WriteConfig()
718     return port
719
720   def _UnlockedComputeDRBDMap(self):
721     """Compute the used DRBD minor/nodes.
722
723     @rtype: (dict, list)
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
729
730     """
731     def _AppendUsedPorts(instance_name, disk, used):
732       duplicates = []
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]))
740           else:
741             used[node][port] = instance_name
742       if disk.children:
743         for child in disk.children:
744           duplicates.extend(_AppendUsedPorts(instance_name, child, used))
745       return duplicates
746
747     duplicates = []
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]))
755       else:
756         my_dict[node][minor] = instance
757     return my_dict, duplicates
758
759   @locking.ssynchronized(_config_lock)
760   def ComputeDRBDMap(self):
761     """Compute the used DRBD minor/nodes.
762
763     This is just a wrapper over L{_UnlockedComputeDRBDMap}.
764
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
767         an empty list).
768
769     """
770     d_map, duplicates = self._UnlockedComputeDRBDMap()
771     if duplicates:
772       raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
773                                       str(duplicates))
774     return d_map
775
776   @locking.ssynchronized(_config_lock)
777   def AllocateDRBDMinor(self, nodes, instance):
778     """Allocate a drbd minor.
779
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.
784
785     @type instance: string
786     @param instance: the instance for which we allocate minors
787
788     """
789     assert isinstance(instance, basestring), \
790            "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
791
792     d_map, duplicates = self._UnlockedComputeDRBDMap()
793     if duplicates:
794       raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
795                                       str(duplicates))
796     result = []
797     for nname in nodes:
798       ndata = d_map[nname]
799       if not ndata:
800         # no minors used, we can start at 0
801         result.append(0)
802         ndata[0] = instance
803         self._temporary_drbds[(nname, 0)] = instance
804         continue
805       keys = ndata.keys()
806       keys.sort()
807       ffree = utils.FirstFree(keys)
808       if ffree is None:
809         # return the next minor
810         # TODO: implement high-limit check
811         minor = keys[-1] + 1
812       else:
813         minor = ffree
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
827       result.append(minor)
828     logging.debug("Request to allocate drbd minors, input: %s, returning %s",
829                   nodes, result)
830     return result
831
832   def _UnlockedReleaseDRBDMinors(self, instance):
833     """Release temporary drbd minors allocated for a given instance.
834
835     @type instance: string
836     @param instance: the instance for which temporary minors should be
837                      released
838
839     """
840     assert isinstance(instance, basestring), \
841            "Invalid argument passed to ReleaseDRBDMinors"
842     for key, name in self._temporary_drbds.items():
843       if name == instance:
844         del self._temporary_drbds[key]
845
846   @locking.ssynchronized(_config_lock)
847   def ReleaseDRBDMinors(self, instance):
848     """Release temporary drbd minors allocated for a given instance.
849
850     This should be called on the error paths, on the success paths
851     it's automatically called by the ConfigWriter add and update
852     functions.
853
854     This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
855
856     @type instance: string
857     @param instance: the instance for which temporary minors should be
858                      released
859
860     """
861     self._UnlockedReleaseDRBDMinors(instance)
862
863   @locking.ssynchronized(_config_lock, shared=1)
864   def GetConfigVersion(self):
865     """Get the configuration version.
866
867     @return: Config version
868
869     """
870     return self._config_data.version
871
872   @locking.ssynchronized(_config_lock, shared=1)
873   def GetClusterName(self):
874     """Get cluster name.
875
876     @return: Cluster name
877
878     """
879     return self._config_data.cluster.cluster_name
880
881   @locking.ssynchronized(_config_lock, shared=1)
882   def GetMasterNode(self):
883     """Get the hostname of the master node for this cluster.
884
885     @return: Master hostname
886
887     """
888     return self._config_data.cluster.master_node
889
890   @locking.ssynchronized(_config_lock, shared=1)
891   def GetMasterIP(self):
892     """Get the IP of the master node for this cluster.
893
894     @return: Master IP
895
896     """
897     return self._config_data.cluster.master_ip
898
899   @locking.ssynchronized(_config_lock, shared=1)
900   def GetMasterNetdev(self):
901     """Get the master network device for this cluster.
902
903     """
904     return self._config_data.cluster.master_netdev
905
906   @locking.ssynchronized(_config_lock, shared=1)
907   def GetMasterNetmask(self):
908     """Get the netmask of the master node for this cluster.
909
910     """
911     return self._config_data.cluster.master_netmask
912
913   @locking.ssynchronized(_config_lock, shared=1)
914   def GetUseExternalMipScript(self):
915     """Get flag representing whether to use the external master IP setup script.
916
917     """
918     return self._config_data.cluster.use_external_mip_script
919
920   @locking.ssynchronized(_config_lock, shared=1)
921   def GetFileStorageDir(self):
922     """Get the file storage dir for this cluster.
923
924     """
925     return self._config_data.cluster.file_storage_dir
926
927   @locking.ssynchronized(_config_lock, shared=1)
928   def GetSharedFileStorageDir(self):
929     """Get the shared file storage dir for this cluster.
930
931     """
932     return self._config_data.cluster.shared_file_storage_dir
933
934   @locking.ssynchronized(_config_lock, shared=1)
935   def GetHypervisorType(self):
936     """Get the hypervisor type for this cluster.
937
938     """
939     return self._config_data.cluster.enabled_hypervisors[0]
940
941   @locking.ssynchronized(_config_lock, shared=1)
942   def GetHostKey(self):
943     """Return the rsa hostkey from the config.
944
945     @rtype: string
946     @return: the rsa hostkey
947
948     """
949     return self._config_data.cluster.rsahostkeypub
950
951   @locking.ssynchronized(_config_lock, shared=1)
952   def GetDefaultIAllocator(self):
953     """Get the default instance allocator for this cluster.
954
955     """
956     return self._config_data.cluster.default_iallocator
957
958   @locking.ssynchronized(_config_lock, shared=1)
959   def GetPrimaryIPFamily(self):
960     """Get cluster primary ip family.
961
962     @return: primary ip family
963
964     """
965     return self._config_data.cluster.primary_ip_family
966
967   @locking.ssynchronized(_config_lock, shared=1)
968   def GetMasterNetworkParameters(self):
969     """Get network parameters of the master node.
970
971     @rtype: L{object.MasterNetworkParameters}
972     @return: network parameters of the master node
973
974     """
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)
981
982     return result
983
984   @locking.ssynchronized(_config_lock)
985   def AddNodeGroup(self, group, ec_id, check_uuid=True):
986     """Add a node group to the configuration.
987
988     This method calls group.UpgradeConfig() to fill any missing attributes
989     according to their default values.
990
991     @type group: L{objects.NodeGroup}
992     @param group: the NodeGroup object to add
993     @type ec_id: string
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
999
1000     """
1001     self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1002     self._WriteConfig()
1003
1004   def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1005     """Add a node group to the configuration.
1006
1007     """
1008     logging.info("Adding node group %s to configuration", group.name)
1009
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.
1013     if check_uuid:
1014       self._EnsureUUID(group, ec_id)
1015
1016     try:
1017       existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1018     except errors.OpPrereqError:
1019       pass
1020     else:
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)
1025
1026     group.serial_no = 1
1027     group.ctime = group.mtime = time.time()
1028     group.UpgradeConfig()
1029
1030     self._config_data.nodegroups[group.uuid] = group
1031     self._config_data.cluster.serial_no += 1
1032
1033   @locking.ssynchronized(_config_lock)
1034   def RemoveNodeGroup(self, group_uuid):
1035     """Remove a node group from the configuration.
1036
1037     @type group_uuid: string
1038     @param group_uuid: the UUID of the node group to remove
1039
1040     """
1041     logging.info("Removing node group %s from configuration", group_uuid)
1042
1043     if group_uuid not in self._config_data.nodegroups:
1044       raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1045
1046     assert len(self._config_data.nodegroups) != 1, \
1047             "Group '%s' is the only group, cannot be removed" % group_uuid
1048
1049     del self._config_data.nodegroups[group_uuid]
1050     self._config_data.cluster.serial_no += 1
1051     self._WriteConfig()
1052
1053   def _UnlockedLookupNodeGroup(self, target):
1054     """Lookup a node group's UUID.
1055
1056     @type target: string or None
1057     @param target: group name or UUID or None to look for the default
1058     @rtype: string
1059     @return: nodegroup UUID
1060     @raises errors.OpPrereqError: when the target group cannot be found
1061
1062     """
1063     if target is None:
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.")
1067       else:
1068         return self._config_data.nodegroups.keys()[0]
1069     if target in self._config_data.nodegroups:
1070       return target
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,
1075                                errors.ECODE_NOENT)
1076
1077   @locking.ssynchronized(_config_lock, shared=1)
1078   def LookupNodeGroup(self, target):
1079     """Lookup a node group's UUID.
1080
1081     This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1082
1083     @type target: string or None
1084     @param target: group name or UUID or None to look for the default
1085     @rtype: string
1086     @return: nodegroup UUID
1087
1088     """
1089     return self._UnlockedLookupNodeGroup(target)
1090
1091   def _UnlockedGetNodeGroup(self, uuid):
1092     """Lookup a node group.
1093
1094     @type uuid: string
1095     @param uuid: group UUID
1096     @rtype: L{objects.NodeGroup} or None
1097     @return: nodegroup object, or None if not found
1098
1099     """
1100     if uuid not in self._config_data.nodegroups:
1101       return None
1102
1103     return self._config_data.nodegroups[uuid]
1104
1105   @locking.ssynchronized(_config_lock, shared=1)
1106   def GetNodeGroup(self, uuid):
1107     """Lookup a node group.
1108
1109     @type uuid: string
1110     @param uuid: group UUID
1111     @rtype: L{objects.NodeGroup} or None
1112     @return: nodegroup object, or None if not found
1113
1114     """
1115     return self._UnlockedGetNodeGroup(uuid)
1116
1117   @locking.ssynchronized(_config_lock, shared=1)
1118   def GetAllNodeGroupsInfo(self):
1119     """Get the configuration of all node groups.
1120
1121     """
1122     return dict(self._config_data.nodegroups)
1123
1124   @locking.ssynchronized(_config_lock, shared=1)
1125   def GetNodeGroupList(self):
1126     """Get a list of node groups.
1127
1128     """
1129     return self._config_data.nodegroups.keys()
1130
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.
1134
1135     """
1136     ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1137     return frozenset(member_name
1138                      for node_name in nodes
1139                      for member_name in
1140                        self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1141
1142   @locking.ssynchronized(_config_lock)
1143   def AddInstance(self, instance, ec_id):
1144     """Add an instance to the config.
1145
1146     This should be used after creating a new instance.
1147
1148     @type instance: L{objects.Instance}
1149     @param instance: the instance object
1150
1151     """
1152     if not isinstance(instance, objects.Instance):
1153       raise errors.ProgrammerError("Invalid type passed to AddInstance")
1154
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)
1158
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))
1165
1166     self._EnsureUUID(instance, ec_id)
1167
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)
1173     self._WriteConfig()
1174
1175   def _EnsureUUID(self, item, ec_id):
1176     """Ensures a given object has a valid UUID.
1177
1178     @param item: the instance or node to be checked
1179     @param ec_id: the execution context id for the uuid reservation
1180
1181     """
1182     if not item.uuid:
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))
1187
1188   def _SetInstanceStatus(self, instance_name, status):
1189     """Set the instance's status to a given value.
1190
1191     """
1192     assert status in constants.ADMINST_ALL, \
1193            "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1194
1195     if instance_name not in self._config_data.instances:
1196       raise errors.ConfigurationError("Unknown instance '%s'" %
1197                                       instance_name)
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()
1203       self._WriteConfig()
1204
1205   @locking.ssynchronized(_config_lock)
1206   def MarkInstanceUp(self, instance_name):
1207     """Mark the instance status to up in the config.
1208
1209     """
1210     self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1211
1212   @locking.ssynchronized(_config_lock)
1213   def MarkInstanceOffline(self, instance_name):
1214     """Mark the instance status to down in the config.
1215
1216     """
1217     self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1218
1219   @locking.ssynchronized(_config_lock)
1220   def RemoveInstance(self, instance_name):
1221     """Remove the instance from the configuration.
1222
1223     """
1224     if instance_name not in self._config_data.instances:
1225       raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1226
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)
1233
1234     del self._config_data.instances[instance_name]
1235     self._config_data.cluster.serial_no += 1
1236     self._WriteConfig()
1237
1238   @locking.ssynchronized(_config_lock)
1239   def RenameInstance(self, old_name, new_name):
1240     """Rename an instance.
1241
1242     This needs to be done in ConfigWriter and not by RemoveInstance
1243     combined with AddInstance as only we can guarantee an atomic
1244     rename.
1245
1246     """
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
1252
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,
1260                                                              inst.name,
1261                                                              disk_fname))
1262
1263     # Force update of ssconf files
1264     self._config_data.cluster.serial_no += 1
1265
1266     self._config_data.instances[inst.name] = inst
1267     self._WriteConfig()
1268
1269   @locking.ssynchronized(_config_lock)
1270   def MarkInstanceDown(self, instance_name):
1271     """Mark the status of an instance to down in the configuration.
1272
1273     """
1274     self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1275
1276   def _UnlockedGetInstanceList(self):
1277     """Get the list of instances.
1278
1279     This function is for internal use, when the config lock is already held.
1280
1281     """
1282     return self._config_data.instances.keys()
1283
1284   @locking.ssynchronized(_config_lock, shared=1)
1285   def GetInstanceList(self):
1286     """Get the list of instances.
1287
1288     @return: array of instances, ex. ['instance2.example.com',
1289         'instance1.example.com']
1290
1291     """
1292     return self._UnlockedGetInstanceList()
1293
1294   def ExpandInstanceName(self, short_name):
1295     """Attempt to expand an incomplete instance name.
1296
1297     """
1298     # Locking is done in L{ConfigWriter.GetInstanceList}
1299     return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1300
1301   def _UnlockedGetInstanceInfo(self, instance_name):
1302     """Returns information about an instance.
1303
1304     This function is for internal use, when the config lock is already held.
1305
1306     """
1307     if instance_name not in self._config_data.instances:
1308       return None
1309
1310     return self._config_data.instances[instance_name]
1311
1312   @locking.ssynchronized(_config_lock, shared=1)
1313   def GetInstanceInfo(self, instance_name):
1314     """Returns information about an instance.
1315
1316     It takes the information from the configuration file. Other information of
1317     an instance are taken from the live systems.
1318
1319     @param instance_name: name of the instance, e.g.
1320         I{instance1.example.com}
1321
1322     @rtype: L{objects.Instance}
1323     @return: the instance object
1324
1325     """
1326     return self._UnlockedGetInstanceInfo(instance_name)
1327
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.
1331
1332     @rtype: frozenset
1333
1334     """
1335     instance = self._UnlockedGetInstanceInfo(instance_name)
1336     if not instance:
1337       raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1338
1339     if primary_only:
1340       nodes = [instance.primary_node]
1341     else:
1342       nodes = instance.all_nodes
1343
1344     return frozenset(self._UnlockedGetNodeInfo(node_name).group
1345                      for node_name in nodes)
1346
1347   @locking.ssynchronized(_config_lock, shared=1)
1348   def GetMultiInstanceInfo(self, instances):
1349     """Get the configuration of multiple instances.
1350
1351     @param instances: list of instance names
1352     @rtype: list
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
1356
1357     """
1358     return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1359
1360   @locking.ssynchronized(_config_lock, shared=1)
1361   def GetAllInstancesInfo(self):
1362     """Get the configuration of all instances.
1363
1364     @rtype: dict
1365     @return: dict of (instance, instance_info), where instance_info is what
1366               would GetInstanceInfo return for the node
1367
1368     """
1369     my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1370                     for instance in self._UnlockedGetInstanceList()])
1371     return my_dict
1372
1373   @locking.ssynchronized(_config_lock, shared=1)
1374   def GetInstancesInfoByFilter(self, filter_fn):
1375     """Get instance configuration with a filter.
1376
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.
1383
1384     """
1385     return dict((name, inst)
1386                 for (name, inst) in self._config_data.instances.items()
1387                 if filter_fn(inst))
1388
1389   @locking.ssynchronized(_config_lock)
1390   def AddNode(self, node, ec_id):
1391     """Add a node to the configuration.
1392
1393     @type node: L{objects.Node}
1394     @param node: a Node instance
1395
1396     """
1397     logging.info("Adding node %s to configuration", node.name)
1398
1399     self._EnsureUUID(node, ec_id)
1400
1401     node.serial_no = 1
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
1406     self._WriteConfig()
1407
1408   @locking.ssynchronized(_config_lock)
1409   def RemoveNode(self, node_name):
1410     """Remove a node from the configuration.
1411
1412     """
1413     logging.info("Removing node %s from configuration", node_name)
1414
1415     if node_name not in self._config_data.nodes:
1416       raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1417
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
1421     self._WriteConfig()
1422
1423   def ExpandNodeName(self, short_name):
1424     """Attempt to expand an incomplete node name.
1425
1426     """
1427     # Locking is done in L{ConfigWriter.GetNodeList}
1428     return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1429
1430   def _UnlockedGetNodeInfo(self, node_name):
1431     """Get the configuration of a node, as stored in the config.
1432
1433     This function is for internal use, when the config lock is already
1434     held.
1435
1436     @param node_name: the node name, e.g. I{node1.example.com}
1437
1438     @rtype: L{objects.Node}
1439     @return: the node object
1440
1441     """
1442     if node_name not in self._config_data.nodes:
1443       return None
1444
1445     return self._config_data.nodes[node_name]
1446
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.
1450
1451     This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1452
1453     @param node_name: the node name, e.g. I{node1.example.com}
1454
1455     @rtype: L{objects.Node}
1456     @return: the node object
1457
1458     """
1459     return self._UnlockedGetNodeInfo(node_name)
1460
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.
1464
1465     @param node_name: the node name, e.g. I{node1.example.com}
1466
1467     @rtype: (list, list)
1468     @return: a tuple with two lists: the primary and the secondary instances
1469
1470     """
1471     pri = []
1472     sec = []
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)
1478     return (pri, sec)
1479
1480   @locking.ssynchronized(_config_lock, shared=1)
1481   def GetNodeGroupInstances(self, uuid, primary_only=False):
1482     """Get the instances of a node group.
1483
1484     @param uuid: Node group UUID
1485     @param primary_only: Whether to only consider primary nodes
1486     @rtype: frozenset
1487     @return: List of instance names in node group
1488
1489     """
1490     if primary_only:
1491       nodes_fn = lambda inst: [inst.primary_node]
1492     else:
1493       nodes_fn = lambda inst: inst.all_nodes
1494
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)
1499
1500   def _UnlockedGetNodeList(self):
1501     """Return the list of nodes which are in the configuration.
1502
1503     This function is for internal use, when the config lock is already
1504     held.
1505
1506     @rtype: list
1507
1508     """
1509     return self._config_data.nodes.keys()
1510
1511   @locking.ssynchronized(_config_lock, shared=1)
1512   def GetNodeList(self):
1513     """Return the list of nodes which are in the configuration.
1514
1515     """
1516     return self._UnlockedGetNodeList()
1517
1518   def _UnlockedGetOnlineNodeList(self):
1519     """Return the list of nodes which are online.
1520
1521     """
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]
1525
1526   @locking.ssynchronized(_config_lock, shared=1)
1527   def GetOnlineNodeList(self):
1528     """Return the list of nodes which are online.
1529
1530     """
1531     return self._UnlockedGetOnlineNodeList()
1532
1533   @locking.ssynchronized(_config_lock, shared=1)
1534   def GetVmCapableNodeList(self):
1535     """Return the list of nodes which are not vm capable.
1536
1537     """
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]
1541
1542   @locking.ssynchronized(_config_lock, shared=1)
1543   def GetNonVmCapableNodeList(self):
1544     """Return the list of nodes which are not vm capable.
1545
1546     """
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]
1550
1551   @locking.ssynchronized(_config_lock, shared=1)
1552   def GetMultiNodeInfo(self, nodes):
1553     """Get the configuration of multiple nodes.
1554
1555     @param nodes: list of node names
1556     @rtype: list
1557     @return: list of tuples of (node, node_info), where node_info is
1558         what would GetNodeInfo return for the node, in the original
1559         order
1560
1561     """
1562     return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1563
1564   @locking.ssynchronized(_config_lock, shared=1)
1565   def GetAllNodesInfo(self):
1566     """Get the configuration of all nodes.
1567
1568     @rtype: dict
1569     @return: dict of (node, node_info), where node_info is what
1570               would GetNodeInfo return for the node
1571
1572     """
1573     return self._UnlockedGetAllNodesInfo()
1574
1575   def _UnlockedGetAllNodesInfo(self):
1576     """Gets configuration of all nodes.
1577
1578     @note: See L{GetAllNodesInfo}
1579
1580     """
1581     return dict([(node, self._UnlockedGetNodeInfo(node))
1582                  for node in self._UnlockedGetNodeList()])
1583
1584   @locking.ssynchronized(_config_lock, shared=1)
1585   def GetNodeGroupsFromNodes(self, nodes):
1586     """Returns groups for a list of nodes.
1587
1588     @type nodes: list of string
1589     @param nodes: List of node names
1590     @rtype: frozenset
1591
1592     """
1593     return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1594
1595   def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1596     """Get the number of current and maximum desired and possible candidates.
1597
1598     @type exceptions: list
1599     @param exceptions: if passed, list of nodes that should be ignored
1600     @rtype: tuple
1601     @return: tuple of (current, desired and possible, possible)
1602
1603     """
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:
1607         continue
1608       if not (node.offline or node.drained) and node.master_capable:
1609         mc_max += 1
1610       if node.master_candidate:
1611         mc_now += 1
1612     mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1613     return (mc_now, mc_should, mc_max)
1614
1615   @locking.ssynchronized(_config_lock, shared=1)
1616   def GetMasterCandidateStats(self, exceptions=None):
1617     """Get the number of current and maximum possible candidates.
1618
1619     This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1620
1621     @type exceptions: list
1622     @param exceptions: if passed, list of nodes that should be ignored
1623     @rtype: tuple
1624     @return: tuple of (current, max)
1625
1626     """
1627     return self._UnlockedGetMasterCandidateStats(exceptions)
1628
1629   @locking.ssynchronized(_config_lock)
1630   def MaintainCandidatePool(self, exceptions):
1631     """Try to grow the candidate pool to the desired size.
1632
1633     @type exceptions: list
1634     @param exceptions: if passed, list of nodes that should be ignored
1635     @rtype: list
1636     @return: list with the adjusted nodes (L{objects.Node} instances)
1637
1638     """
1639     mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1640     mod_list = []
1641     if mc_now < mc_max:
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:
1646           break
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):
1650           continue
1651         mod_list.append(node)
1652         node.master_candidate = True
1653         node.serial_no += 1
1654         mc_now += 1
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)
1659       if mod_list:
1660         self._config_data.cluster.serial_no += 1
1661         self._WriteConfig()
1662
1663     return mod_list
1664
1665   def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1666     """Add a given node to the specified group.
1667
1668     """
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)
1677
1678   def _UnlockedRemoveNodeFromGroup(self, node):
1679     """Remove a given node from its group.
1680
1681     """
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)
1690     else:
1691       nodegroup_obj.members.remove(node.name)
1692
1693   @locking.ssynchronized(_config_lock)
1694   def AssignGroupNodes(self, mods):
1695     """Changes the group of a number of nodes.
1696
1697     @type mods: list of tuples; (node name, new group UUID)
1698     @param mods: Node membership modifications
1699
1700     """
1701     groups = self._config_data.nodegroups
1702     nodes = self._config_data.nodes
1703
1704     resmod = []
1705
1706     # Try to resolve names/UUIDs first
1707     for (node_name, new_group_uuid) in mods:
1708       try:
1709         node = nodes[node_name]
1710       except KeyError:
1711         raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1712
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)
1717         continue
1718
1719       # Try to find current group of node
1720       try:
1721         old_group = groups[node.group]
1722       except KeyError:
1723         raise errors.ConfigurationError("Unable to find old group '%s'" %
1724                                         node.group)
1725
1726       # Try to find new group for node
1727       try:
1728         new_group = groups[new_group_uuid]
1729       except KeyError:
1730         raise errors.ConfigurationError("Unable to find new group '%s'" %
1731                                         new_group_uuid)
1732
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))
1739
1740       resmod.append((node, old_group, new_group))
1741
1742     # Apply changes
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"
1746
1747       node.group = new_group.uuid
1748
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)
1754
1755     # Update timestamps and serials (only once per node/group object)
1756     now = time.time()
1757     for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
1758       obj.serial_no += 1
1759       obj.mtime = now
1760
1761     # Force ssconf update
1762     self._config_data.cluster.serial_no += 1
1763
1764     self._WriteConfig()
1765
1766   def _BumpSerialNo(self):
1767     """Bump up the serial number of the config.
1768
1769     """
1770     self._config_data.serial_no += 1
1771     self._config_data.mtime = time.time()
1772
1773   def _AllUUIDObjects(self):
1774     """Returns all objects with uuid attributes.
1775
1776     """
1777     return (self._config_data.instances.values() +
1778             self._config_data.nodes.values() +
1779             self._config_data.nodegroups.values() +
1780             [self._config_data.cluster])
1781
1782   def _OpenConfig(self, accept_foreign):
1783     """Read the config data from disk.
1784
1785     """
1786     raw_data = utils.ReadFile(self._cfg_file)
1787
1788     try:
1789       data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1790     except Exception, err:
1791       raise errors.ConfigurationError(err)
1792
1793     # Make sure the configuration has the right version
1794     _ValidateConfig(data)
1795
1796     if (not hasattr(data, 'cluster') or
1797         not hasattr(data.cluster, 'rsahostkeypub')):
1798       raise errors.ConfigurationError("Incomplete configuration"
1799                                       " (missing cluster.rsahostkeypub)")
1800
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)
1807
1808     # Upgrade configuration if needed
1809     data.UpgradeConfig()
1810
1811     self._config_data = data
1812     # reset the last serial as -1 so that the next write will cause
1813     # ssconf update
1814     self._last_cluster_serial = -1
1815
1816     # And finally run our (custom) config upgrade sequence
1817     self._UpgradeConfig()
1818
1819     self._cfg_id = utils.GetFileID(path=self._cfg_file)
1820
1821   def _UpgradeConfig(self):
1822     """Run upgrade steps that cannot be done purely in the objects.
1823
1824     This is because some data elements need uniqueness across the
1825     whole configuration, etc.
1826
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.
1832
1833     """
1834     modified = False
1835     for item in self._AllUUIDObjects():
1836       if item.uuid is None:
1837         item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1838         modified = True
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,
1842                                             members=[])
1843       self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
1844       modified = True
1845     for node in self._config_data.nodes.values():
1846       if not node.group:
1847         node.group = self.LookupNodeGroup(None)
1848         modified = True
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)
1854     if modified:
1855       self._WriteConfig()
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)
1859
1860   def _DistributeConfig(self, feedback_fn):
1861     """Distribute the configuration to the other nodes.
1862
1863     Currently, this only copies the configuration file. In the future,
1864     it could be used to encapsulate the 2/3-phase update mechanism.
1865
1866     """
1867     if self._offline:
1868       return True
1869
1870     bad = False
1871
1872     node_list = []
1873     addr_list = []
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
1878     # in between
1879     for node_name in self._UnlockedGetNodeList():
1880       if node_name == myhostname:
1881         continue
1882       node_info = self._UnlockedGetNodeInfo(node_name)
1883       if not node_info.master_candidate:
1884         continue
1885       node_list.append(node_info.name)
1886       addr_list.append(node_info.primary_ip)
1887
1888     # TODO: Use dedicated resolver talking to config writer for name resolution
1889     result = \
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
1893       if msg:
1894         msg = ("Copy of file %s to node %s failed: %s" %
1895                (self._cfg_file, to_node, msg))
1896         logging.error(msg)
1897
1898         if feedback_fn:
1899           feedback_fn(msg)
1900
1901         bad = True
1902
1903     return not bad
1904
1905   def _WriteConfig(self, destination=None, feedback_fn=None):
1906     """Write the configuration data to persistent storage.
1907
1908     """
1909     assert feedback_fn is None or callable(feedback_fn)
1910
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()
1916     if config_errors:
1917       errmsg = ("Configuration data is not consistent: %s" %
1918                 (utils.CommaJoin(config_errors)))
1919       logging.critical(errmsg)
1920       if feedback_fn:
1921         feedback_fn(errmsg)
1922
1923     if destination is None:
1924       destination = self._cfg_file
1925     self._BumpSerialNo()
1926     txt = serializer.Dump(self._config_data.ToDict())
1927
1928     getents = self._getents()
1929     try:
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"
1935                                       " update")
1936     try:
1937       self._cfg_id = utils.GetFileID(fd=fd)
1938     finally:
1939       os.close(fd)
1940
1941     self.write_count += 1
1942
1943     # and redistribute the config file to master candidates
1944     self._DistributeConfig(feedback_fn)
1945
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())
1952
1953         for nname, nresu in result.items():
1954           msg = nresu.fail_msg
1955           if msg:
1956             errmsg = ("Error while uploading ssconf files to"
1957                       " node %s: %s" % (nname, msg))
1958             logging.warning(errmsg)
1959
1960             if feedback_fn:
1961               feedback_fn(errmsg)
1962
1963       self._last_cluster_serial = self._config_data.cluster.serial_no
1964
1965   def _UnlockedGetSsconfValues(self):
1966     """Return the values needed by ssconf.
1967
1968     @rtype: dict
1969     @return: a dictionary with keys the ssconf names and values their
1970         associated value
1971
1972     """
1973     fn = "\n".join
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]
1981
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)
1991
1992     cluster = self._config_data.cluster
1993     cluster_tags = fn(cluster.GetTags())
1994
1995     hypervisor_list = fn(cluster.enabled_hypervisors)
1996
1997     uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
1998
1999     nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2000                   self._config_data.nodegroups.values()]
2001     nodegroups_data = fn(utils.NiceSort(nodegroups))
2002
2003     ssconf_values = {
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,
2026       }
2027     bad_values = [(k, v) for k, v in ssconf_values.items()
2028                   if not isinstance(v, (str, basestring))]
2029     if bad_values:
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
2034
2035   @locking.ssynchronized(_config_lock, shared=1)
2036   def GetSsconfValues(self):
2037     """Wrapper using lock around _UnlockedGetSsconf().
2038
2039     """
2040     return self._UnlockedGetSsconfValues()
2041
2042   @locking.ssynchronized(_config_lock, shared=1)
2043   def GetVGName(self):
2044     """Return the volume group name.
2045
2046     """
2047     return self._config_data.cluster.volume_group_name
2048
2049   @locking.ssynchronized(_config_lock)
2050   def SetVGName(self, vg_name):
2051     """Set the volume group name.
2052
2053     """
2054     self._config_data.cluster.volume_group_name = vg_name
2055     self._config_data.cluster.serial_no += 1
2056     self._WriteConfig()
2057
2058   @locking.ssynchronized(_config_lock, shared=1)
2059   def GetDRBDHelper(self):
2060     """Return DRBD usermode helper.
2061
2062     """
2063     return self._config_data.cluster.drbd_usermode_helper
2064
2065   @locking.ssynchronized(_config_lock)
2066   def SetDRBDHelper(self, drbd_helper):
2067     """Set DRBD usermode helper.
2068
2069     """
2070     self._config_data.cluster.drbd_usermode_helper = drbd_helper
2071     self._config_data.cluster.serial_no += 1
2072     self._WriteConfig()
2073
2074   @locking.ssynchronized(_config_lock, shared=1)
2075   def GetMACPrefix(self):
2076     """Return the mac prefix.
2077
2078     """
2079     return self._config_data.cluster.mac_prefix
2080
2081   @locking.ssynchronized(_config_lock, shared=1)
2082   def GetClusterInfo(self):
2083     """Returns information about the cluster
2084
2085     @rtype: L{objects.Cluster}
2086     @return: the cluster object
2087
2088     """
2089     return self._config_data.cluster
2090
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.
2094
2095     """
2096     return self._config_data.HasAnyDiskOfType(dev_type)
2097
2098   @locking.ssynchronized(_config_lock)
2099   def Update(self, target, feedback_fn):
2100     """Notify function to be called after updates.
2101
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.
2107
2108     @param target: an instance of either L{objects.Cluster},
2109         L{objects.Node} or L{objects.Instance} which is existing in
2110         the cluster
2111     @param feedback_fn: Callable feedback function
2112
2113     """
2114     if self._config_data is None:
2115       raise errors.ProgrammerError("Configuration file not read,"
2116                                    " cannot save.")
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()
2127     else:
2128       raise errors.ProgrammerError("Invalid object type (%s) passed to"
2129                                    " ConfigWriter.Update" % type(target))
2130     if not test:
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()
2135
2136     if update_serial:
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
2140
2141     if isinstance(target, objects.Instance):
2142       self._UnlockedReleaseDRBDMinors(target.name)
2143
2144     self._WriteConfig(feedback_fn=feedback_fn)
2145
2146   @locking.ssynchronized(_config_lock)
2147   def DropECReservations(self, ec_id):
2148     """Drop per-execution-context reservations
2149
2150     """
2151     for rm in self._all_rms:
2152       rm.DropECReservations(ec_id)