Fix a bug in command line option parsing code
[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-msg=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 class ConfigWriter:
130   """The interface to the cluster configuration.
131
132   @ivar _temporary_lvs: reservation manager for temporary LVs
133   @ivar _all_rms: a list of all temporary reservation managers
134
135   """
136   def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts,
137                accept_foreign=False):
138     self.write_count = 0
139     self._lock = _config_lock
140     self._config_data = None
141     self._offline = offline
142     if cfg_file is None:
143       self._cfg_file = constants.CLUSTER_CONF_FILE
144     else:
145       self._cfg_file = cfg_file
146     self._getents = _getents
147     self._temporary_ids = TemporaryReservationManager()
148     self._temporary_drbds = {}
149     self._temporary_macs = TemporaryReservationManager()
150     self._temporary_secrets = TemporaryReservationManager()
151     self._temporary_lvs = TemporaryReservationManager()
152     self._all_rms = [self._temporary_ids, self._temporary_macs,
153                      self._temporary_secrets, self._temporary_lvs]
154     # Note: in order to prevent errors when resolving our name in
155     # _DistributeConfig, we compute it here once and reuse it; it's
156     # better to raise an error before starting to modify the config
157     # file than after it was modified
158     self._my_hostname = netutils.Hostname.GetSysName()
159     self._last_cluster_serial = -1
160     self._cfg_id = None
161     self._OpenConfig(accept_foreign)
162
163   # this method needs to be static, so that we can call it on the class
164   @staticmethod
165   def IsCluster():
166     """Check if the cluster is configured.
167
168     """
169     return os.path.exists(constants.CLUSTER_CONF_FILE)
170
171   def _GenerateOneMAC(self):
172     """Generate one mac address
173
174     """
175     prefix = self._config_data.cluster.mac_prefix
176     byte1 = random.randrange(0, 256)
177     byte2 = random.randrange(0, 256)
178     byte3 = random.randrange(0, 256)
179     mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
180     return mac
181
182   @locking.ssynchronized(_config_lock, shared=1)
183   def GetNdParams(self, node):
184     """Get the node params populated with cluster defaults.
185
186     @type node: L{object.Node}
187     @param node: The node we want to know the params for
188     @return: A dict with the filled in node params
189
190     """
191     nodegroup = self._UnlockedGetNodeGroup(node.group)
192     return self._config_data.cluster.FillND(node, nodegroup)
193
194   @locking.ssynchronized(_config_lock, shared=1)
195   def GenerateMAC(self, ec_id):
196     """Generate a MAC for an instance.
197
198     This should check the current instances for duplicates.
199
200     """
201     existing = self._AllMACs()
202     return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
203
204   @locking.ssynchronized(_config_lock, shared=1)
205   def ReserveMAC(self, mac, ec_id):
206     """Reserve a MAC for an instance.
207
208     This only checks instances managed by this cluster, it does not
209     check for potential collisions elsewhere.
210
211     """
212     all_macs = self._AllMACs()
213     if mac in all_macs:
214       raise errors.ReservationError("mac already in use")
215     else:
216       self._temporary_macs.Reserve(ec_id, mac)
217
218   @locking.ssynchronized(_config_lock, shared=1)
219   def ReserveLV(self, lv_name, ec_id):
220     """Reserve an VG/LV pair for an instance.
221
222     @type lv_name: string
223     @param lv_name: the logical volume name to reserve
224
225     """
226     all_lvs = self._AllLVs()
227     if lv_name in all_lvs:
228       raise errors.ReservationError("LV already in use")
229     else:
230       self._temporary_lvs.Reserve(ec_id, lv_name)
231
232   @locking.ssynchronized(_config_lock, shared=1)
233   def GenerateDRBDSecret(self, ec_id):
234     """Generate a DRBD secret.
235
236     This checks the current disks for duplicates.
237
238     """
239     return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
240                                             utils.GenerateSecret,
241                                             ec_id)
242
243   def _AllLVs(self):
244     """Compute the list of all LVs.
245
246     """
247     lvnames = set()
248     for instance in self._config_data.instances.values():
249       node_data = instance.MapLVsByNode()
250       for lv_list in node_data.values():
251         lvnames.update(lv_list)
252     return lvnames
253
254   def _AllIDs(self, include_temporary):
255     """Compute the list of all UUIDs and names we have.
256
257     @type include_temporary: boolean
258     @param include_temporary: whether to include the _temporary_ids set
259     @rtype: set
260     @return: a set of IDs
261
262     """
263     existing = set()
264     if include_temporary:
265       existing.update(self._temporary_ids.GetReserved())
266     existing.update(self._AllLVs())
267     existing.update(self._config_data.instances.keys())
268     existing.update(self._config_data.nodes.keys())
269     existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
270     return existing
271
272   def _GenerateUniqueID(self, ec_id):
273     """Generate an unique UUID.
274
275     This checks the current node, instances and disk names for
276     duplicates.
277
278     @rtype: string
279     @return: the unique id
280
281     """
282     existing = self._AllIDs(include_temporary=False)
283     return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
284
285   @locking.ssynchronized(_config_lock, shared=1)
286   def GenerateUniqueID(self, ec_id):
287     """Generate an unique ID.
288
289     This is just a wrapper over the unlocked version.
290
291     @type ec_id: string
292     @param ec_id: unique id for the job to reserve the id to
293
294     """
295     return self._GenerateUniqueID(ec_id)
296
297   def _AllMACs(self):
298     """Return all MACs present in the config.
299
300     @rtype: list
301     @return: the list of all MACs
302
303     """
304     result = []
305     for instance in self._config_data.instances.values():
306       for nic in instance.nics:
307         result.append(nic.mac)
308
309     return result
310
311   def _AllDRBDSecrets(self):
312     """Return all DRBD secrets present in the config.
313
314     @rtype: list
315     @return: the list of all DRBD secrets
316
317     """
318     def helper(disk, result):
319       """Recursively gather secrets from this disk."""
320       if disk.dev_type == constants.DT_DRBD8:
321         result.append(disk.logical_id[5])
322       if disk.children:
323         for child in disk.children:
324           helper(child, result)
325
326     result = []
327     for instance in self._config_data.instances.values():
328       for disk in instance.disks:
329         helper(disk, result)
330
331     return result
332
333   def _CheckDiskIDs(self, disk, l_ids, p_ids):
334     """Compute duplicate disk IDs
335
336     @type disk: L{objects.Disk}
337     @param disk: the disk at which to start searching
338     @type l_ids: list
339     @param l_ids: list of current logical ids
340     @type p_ids: list
341     @param p_ids: list of current physical ids
342     @rtype: list
343     @return: a list of error messages
344
345     """
346     result = []
347     if disk.logical_id is not None:
348       if disk.logical_id in l_ids:
349         result.append("duplicate logical id %s" % str(disk.logical_id))
350       else:
351         l_ids.append(disk.logical_id)
352     if disk.physical_id is not None:
353       if disk.physical_id in p_ids:
354         result.append("duplicate physical id %s" % str(disk.physical_id))
355       else:
356         p_ids.append(disk.physical_id)
357
358     if disk.children:
359       for child in disk.children:
360         result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
361     return result
362
363   def _UnlockedVerifyConfig(self):
364     """Verify function.
365
366     @rtype: list
367     @return: a list of error messages; a non-empty list signifies
368         configuration errors
369
370     """
371     # pylint: disable-msg=R0914
372     result = []
373     seen_macs = []
374     ports = {}
375     data = self._config_data
376     cluster = data.cluster
377     seen_lids = []
378     seen_pids = []
379
380     # global cluster checks
381     if not cluster.enabled_hypervisors:
382       result.append("enabled hypervisors list doesn't have any entries")
383     invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
384     if invalid_hvs:
385       result.append("enabled hypervisors contains invalid entries: %s" %
386                     invalid_hvs)
387     missing_hvp = (set(cluster.enabled_hypervisors) -
388                    set(cluster.hvparams.keys()))
389     if missing_hvp:
390       result.append("hypervisor parameters missing for the enabled"
391                     " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
392
393     if cluster.master_node not in data.nodes:
394       result.append("cluster has invalid primary node '%s'" %
395                     cluster.master_node)
396
397     def _helper(owner, attr, value, template):
398       try:
399         utils.ForceDictType(value, template)
400       except errors.GenericError, err:
401         result.append("%s has invalid %s: %s" % (owner, attr, err))
402
403     def _helper_nic(owner, params):
404       try:
405         objects.NIC.CheckParameterSyntax(params)
406       except errors.ConfigurationError, err:
407         result.append("%s has invalid nicparams: %s" % (owner, err))
408
409     # check cluster parameters
410     _helper("cluster", "beparams", cluster.SimpleFillBE({}),
411             constants.BES_PARAMETER_TYPES)
412     _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
413             constants.NICS_PARAMETER_TYPES)
414     _helper_nic("cluster", cluster.SimpleFillNIC({}))
415     _helper("cluster", "ndparams", cluster.SimpleFillND({}),
416             constants.NDS_PARAMETER_TYPES)
417
418     # per-instance checks
419     for instance_name in data.instances:
420       instance = data.instances[instance_name]
421       if instance.name != instance_name:
422         result.append("instance '%s' is indexed by wrong name '%s'" %
423                       (instance.name, instance_name))
424       if instance.primary_node not in data.nodes:
425         result.append("instance '%s' has invalid primary node '%s'" %
426                       (instance_name, instance.primary_node))
427       for snode in instance.secondary_nodes:
428         if snode not in data.nodes:
429           result.append("instance '%s' has invalid secondary node '%s'" %
430                         (instance_name, snode))
431       for idx, nic in enumerate(instance.nics):
432         if nic.mac in seen_macs:
433           result.append("instance '%s' has NIC %d mac %s duplicate" %
434                         (instance_name, idx, nic.mac))
435         else:
436           seen_macs.append(nic.mac)
437         if nic.nicparams:
438           filled = cluster.SimpleFillNIC(nic.nicparams)
439           owner = "instance %s nic %d" % (instance.name, idx)
440           _helper(owner, "nicparams",
441                   filled, constants.NICS_PARAMETER_TYPES)
442           _helper_nic(owner, filled)
443
444       # parameter checks
445       if instance.beparams:
446         _helper("instance %s" % instance.name, "beparams",
447                 cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
448
449       # gather the drbd ports for duplicate checks
450       for dsk in instance.disks:
451         if dsk.dev_type in constants.LDS_DRBD:
452           tcp_port = dsk.logical_id[2]
453           if tcp_port not in ports:
454             ports[tcp_port] = []
455           ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
456       # gather network port reservation
457       net_port = getattr(instance, "network_port", None)
458       if net_port is not None:
459         if net_port not in ports:
460           ports[net_port] = []
461         ports[net_port].append((instance.name, "network port"))
462
463       # instance disk verify
464       for idx, disk in enumerate(instance.disks):
465         result.extend(["instance '%s' disk %d error: %s" %
466                        (instance.name, idx, msg) for msg in disk.Verify()])
467         result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
468
469     # cluster-wide pool of free ports
470     for free_port in cluster.tcpudp_port_pool:
471       if free_port not in ports:
472         ports[free_port] = []
473       ports[free_port].append(("cluster", "port marked as free"))
474
475     # compute tcp/udp duplicate ports
476     keys = ports.keys()
477     keys.sort()
478     for pnum in keys:
479       pdata = ports[pnum]
480       if len(pdata) > 1:
481         txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
482         result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
483
484     # highest used tcp port check
485     if keys:
486       if keys[-1] > cluster.highest_used_port:
487         result.append("Highest used port mismatch, saved %s, computed %s" %
488                       (cluster.highest_used_port, keys[-1]))
489
490     if not data.nodes[cluster.master_node].master_candidate:
491       result.append("Master node is not a master candidate")
492
493     # master candidate checks
494     mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
495     if mc_now < mc_max:
496       result.append("Not enough master candidates: actual %d, target %d" %
497                     (mc_now, mc_max))
498
499     # node checks
500     for node_name, node in data.nodes.items():
501       if node.name != node_name:
502         result.append("Node '%s' is indexed by wrong name '%s'" %
503                       (node.name, node_name))
504       if [node.master_candidate, node.drained, node.offline].count(True) > 1:
505         result.append("Node %s state is invalid: master_candidate=%s,"
506                       " drain=%s, offline=%s" %
507                       (node.name, node.master_candidate, node.drained,
508                        node.offline))
509       if node.group not in data.nodegroups:
510         result.append("Node '%s' has invalid group '%s'" %
511                       (node.name, node.group))
512       else:
513         _helper("node %s" % node.name, "ndparams",
514                 cluster.FillND(node, data.nodegroups[node.group]),
515                 constants.NDS_PARAMETER_TYPES)
516
517     # nodegroups checks
518     nodegroups_names = set()
519     for nodegroup_uuid in data.nodegroups:
520       nodegroup = data.nodegroups[nodegroup_uuid]
521       if nodegroup.uuid != nodegroup_uuid:
522         result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
523                       % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
524       if utils.UUID_RE.match(nodegroup.name.lower()):
525         result.append("node group '%s' (uuid: '%s') has uuid-like name" %
526                       (nodegroup.name, nodegroup.uuid))
527       if nodegroup.name in nodegroups_names:
528         result.append("duplicate node group name '%s'" % nodegroup.name)
529       else:
530         nodegroups_names.add(nodegroup.name)
531       if nodegroup.ndparams:
532         _helper("group %s" % nodegroup.name, "ndparams",
533                 cluster.SimpleFillND(nodegroup.ndparams),
534                 constants.NDS_PARAMETER_TYPES)
535
536
537     # drbd minors check
538     _, duplicates = self._UnlockedComputeDRBDMap()
539     for node, minor, instance_a, instance_b in duplicates:
540       result.append("DRBD minor %d on node %s is assigned twice to instances"
541                     " %s and %s" % (minor, node, instance_a, instance_b))
542
543     # IP checks
544     default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
545     ips = {}
546
547     def _AddIpAddress(ip, name):
548       ips.setdefault(ip, []).append(name)
549
550     _AddIpAddress(cluster.master_ip, "cluster_ip")
551
552     for node in data.nodes.values():
553       _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
554       if node.secondary_ip != node.primary_ip:
555         _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
556
557     for instance in data.instances.values():
558       for idx, nic in enumerate(instance.nics):
559         if nic.ip is None:
560           continue
561
562         nicparams = objects.FillDict(default_nicparams, nic.nicparams)
563         nic_mode = nicparams[constants.NIC_MODE]
564         nic_link = nicparams[constants.NIC_LINK]
565
566         if nic_mode == constants.NIC_MODE_BRIDGED:
567           link = "bridge:%s" % nic_link
568         elif nic_mode == constants.NIC_MODE_ROUTED:
569           link = "route:%s" % nic_link
570         else:
571           raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
572
573         _AddIpAddress("%s/%s" % (link, nic.ip),
574                       "instance:%s/nic:%d" % (instance.name, idx))
575
576     for ip, owners in ips.items():
577       if len(owners) > 1:
578         result.append("IP address %s is used by multiple owners: %s" %
579                       (ip, utils.CommaJoin(owners)))
580
581     return result
582
583   @locking.ssynchronized(_config_lock, shared=1)
584   def VerifyConfig(self):
585     """Verify function.
586
587     This is just a wrapper over L{_UnlockedVerifyConfig}.
588
589     @rtype: list
590     @return: a list of error messages; a non-empty list signifies
591         configuration errors
592
593     """
594     return self._UnlockedVerifyConfig()
595
596   def _UnlockedSetDiskID(self, disk, node_name):
597     """Convert the unique ID to the ID needed on the target nodes.
598
599     This is used only for drbd, which needs ip/port configuration.
600
601     The routine descends down and updates its children also, because
602     this helps when the only the top device is passed to the remote
603     node.
604
605     This function is for internal use, when the config lock is already held.
606
607     """
608     if disk.children:
609       for child in disk.children:
610         self._UnlockedSetDiskID(child, node_name)
611
612     if disk.logical_id is None and disk.physical_id is not None:
613       return
614     if disk.dev_type == constants.LD_DRBD8:
615       pnode, snode, port, pminor, sminor, secret = disk.logical_id
616       if node_name not in (pnode, snode):
617         raise errors.ConfigurationError("DRBD device not knowing node %s" %
618                                         node_name)
619       pnode_info = self._UnlockedGetNodeInfo(pnode)
620       snode_info = self._UnlockedGetNodeInfo(snode)
621       if pnode_info is None or snode_info is None:
622         raise errors.ConfigurationError("Can't find primary or secondary node"
623                                         " for %s" % str(disk))
624       p_data = (pnode_info.secondary_ip, port)
625       s_data = (snode_info.secondary_ip, port)
626       if pnode == node_name:
627         disk.physical_id = p_data + s_data + (pminor, secret)
628       else: # it must be secondary, we tested above
629         disk.physical_id = s_data + p_data + (sminor, secret)
630     else:
631       disk.physical_id = disk.logical_id
632     return
633
634   @locking.ssynchronized(_config_lock)
635   def SetDiskID(self, disk, node_name):
636     """Convert the unique ID to the ID needed on the target nodes.
637
638     This is used only for drbd, which needs ip/port configuration.
639
640     The routine descends down and updates its children also, because
641     this helps when the only the top device is passed to the remote
642     node.
643
644     """
645     return self._UnlockedSetDiskID(disk, node_name)
646
647   @locking.ssynchronized(_config_lock)
648   def AddTcpUdpPort(self, port):
649     """Adds a new port to the available port pool.
650
651     """
652     if not isinstance(port, int):
653       raise errors.ProgrammerError("Invalid type passed for port")
654
655     self._config_data.cluster.tcpudp_port_pool.add(port)
656     self._WriteConfig()
657
658   @locking.ssynchronized(_config_lock, shared=1)
659   def GetPortList(self):
660     """Returns a copy of the current port list.
661
662     """
663     return self._config_data.cluster.tcpudp_port_pool.copy()
664
665   @locking.ssynchronized(_config_lock)
666   def AllocatePort(self):
667     """Allocate a port.
668
669     The port will be taken from the available port pool or from the
670     default port range (and in this case we increase
671     highest_used_port).
672
673     """
674     # If there are TCP/IP ports configured, we use them first.
675     if self._config_data.cluster.tcpudp_port_pool:
676       port = self._config_data.cluster.tcpudp_port_pool.pop()
677     else:
678       port = self._config_data.cluster.highest_used_port + 1
679       if port >= constants.LAST_DRBD_PORT:
680         raise errors.ConfigurationError("The highest used port is greater"
681                                         " than %s. Aborting." %
682                                         constants.LAST_DRBD_PORT)
683       self._config_data.cluster.highest_used_port = port
684
685     self._WriteConfig()
686     return port
687
688   def _UnlockedComputeDRBDMap(self):
689     """Compute the used DRBD minor/nodes.
690
691     @rtype: (dict, list)
692     @return: dictionary of node_name: dict of minor: instance_name;
693         the returned dict will have all the nodes in it (even if with
694         an empty list), and a list of duplicates; if the duplicates
695         list is not empty, the configuration is corrupted and its caller
696         should raise an exception
697
698     """
699     def _AppendUsedPorts(instance_name, disk, used):
700       duplicates = []
701       if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
702         node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
703         for node, port in ((node_a, minor_a), (node_b, minor_b)):
704           assert node in used, ("Node '%s' of instance '%s' not found"
705                                 " in node list" % (node, instance_name))
706           if port in used[node]:
707             duplicates.append((node, port, instance_name, used[node][port]))
708           else:
709             used[node][port] = instance_name
710       if disk.children:
711         for child in disk.children:
712           duplicates.extend(_AppendUsedPorts(instance_name, child, used))
713       return duplicates
714
715     duplicates = []
716     my_dict = dict((node, {}) for node in self._config_data.nodes)
717     for instance in self._config_data.instances.itervalues():
718       for disk in instance.disks:
719         duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
720     for (node, minor), instance in self._temporary_drbds.iteritems():
721       if minor in my_dict[node] and my_dict[node][minor] != instance:
722         duplicates.append((node, minor, instance, my_dict[node][minor]))
723       else:
724         my_dict[node][minor] = instance
725     return my_dict, duplicates
726
727   @locking.ssynchronized(_config_lock)
728   def ComputeDRBDMap(self):
729     """Compute the used DRBD minor/nodes.
730
731     This is just a wrapper over L{_UnlockedComputeDRBDMap}.
732
733     @return: dictionary of node_name: dict of minor: instance_name;
734         the returned dict will have all the nodes in it (even if with
735         an empty list).
736
737     """
738     d_map, duplicates = self._UnlockedComputeDRBDMap()
739     if duplicates:
740       raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
741                                       str(duplicates))
742     return d_map
743
744   @locking.ssynchronized(_config_lock)
745   def AllocateDRBDMinor(self, nodes, instance):
746     """Allocate a drbd minor.
747
748     The free minor will be automatically computed from the existing
749     devices. A node can be given multiple times in order to allocate
750     multiple minors. The result is the list of minors, in the same
751     order as the passed nodes.
752
753     @type instance: string
754     @param instance: the instance for which we allocate minors
755
756     """
757     assert isinstance(instance, basestring), \
758            "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
759
760     d_map, duplicates = self._UnlockedComputeDRBDMap()
761     if duplicates:
762       raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
763                                       str(duplicates))
764     result = []
765     for nname in nodes:
766       ndata = d_map[nname]
767       if not ndata:
768         # no minors used, we can start at 0
769         result.append(0)
770         ndata[0] = instance
771         self._temporary_drbds[(nname, 0)] = instance
772         continue
773       keys = ndata.keys()
774       keys.sort()
775       ffree = utils.FirstFree(keys)
776       if ffree is None:
777         # return the next minor
778         # TODO: implement high-limit check
779         minor = keys[-1] + 1
780       else:
781         minor = ffree
782       # double-check minor against current instances
783       assert minor not in d_map[nname], \
784              ("Attempt to reuse allocated DRBD minor %d on node %s,"
785               " already allocated to instance %s" %
786               (minor, nname, d_map[nname][minor]))
787       ndata[minor] = instance
788       # double-check minor against reservation
789       r_key = (nname, minor)
790       assert r_key not in self._temporary_drbds, \
791              ("Attempt to reuse reserved DRBD minor %d on node %s,"
792               " reserved for instance %s" %
793               (minor, nname, self._temporary_drbds[r_key]))
794       self._temporary_drbds[r_key] = instance
795       result.append(minor)
796     logging.debug("Request to allocate drbd minors, input: %s, returning %s",
797                   nodes, result)
798     return result
799
800   def _UnlockedReleaseDRBDMinors(self, instance):
801     """Release temporary drbd minors allocated for a given instance.
802
803     @type instance: string
804     @param instance: the instance for which temporary minors should be
805                      released
806
807     """
808     assert isinstance(instance, basestring), \
809            "Invalid argument passed to ReleaseDRBDMinors"
810     for key, name in self._temporary_drbds.items():
811       if name == instance:
812         del self._temporary_drbds[key]
813
814   @locking.ssynchronized(_config_lock)
815   def ReleaseDRBDMinors(self, instance):
816     """Release temporary drbd minors allocated for a given instance.
817
818     This should be called on the error paths, on the success paths
819     it's automatically called by the ConfigWriter add and update
820     functions.
821
822     This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
823
824     @type instance: string
825     @param instance: the instance for which temporary minors should be
826                      released
827
828     """
829     self._UnlockedReleaseDRBDMinors(instance)
830
831   @locking.ssynchronized(_config_lock, shared=1)
832   def GetConfigVersion(self):
833     """Get the configuration version.
834
835     @return: Config version
836
837     """
838     return self._config_data.version
839
840   @locking.ssynchronized(_config_lock, shared=1)
841   def GetClusterName(self):
842     """Get cluster name.
843
844     @return: Cluster name
845
846     """
847     return self._config_data.cluster.cluster_name
848
849   @locking.ssynchronized(_config_lock, shared=1)
850   def GetMasterNode(self):
851     """Get the hostname of the master node for this cluster.
852
853     @return: Master hostname
854
855     """
856     return self._config_data.cluster.master_node
857
858   @locking.ssynchronized(_config_lock, shared=1)
859   def GetMasterIP(self):
860     """Get the IP of the master node for this cluster.
861
862     @return: Master IP
863
864     """
865     return self._config_data.cluster.master_ip
866
867   @locking.ssynchronized(_config_lock, shared=1)
868   def GetMasterNetdev(self):
869     """Get the master network device for this cluster.
870
871     """
872     return self._config_data.cluster.master_netdev
873
874   @locking.ssynchronized(_config_lock, shared=1)
875   def GetFileStorageDir(self):
876     """Get the file storage dir for this cluster.
877
878     """
879     return self._config_data.cluster.file_storage_dir
880
881   @locking.ssynchronized(_config_lock, shared=1)
882   def GetHypervisorType(self):
883     """Get the hypervisor type for this cluster.
884
885     """
886     return self._config_data.cluster.enabled_hypervisors[0]
887
888   @locking.ssynchronized(_config_lock, shared=1)
889   def GetHostKey(self):
890     """Return the rsa hostkey from the config.
891
892     @rtype: string
893     @return: the rsa hostkey
894
895     """
896     return self._config_data.cluster.rsahostkeypub
897
898   @locking.ssynchronized(_config_lock, shared=1)
899   def GetDefaultIAllocator(self):
900     """Get the default instance allocator for this cluster.
901
902     """
903     return self._config_data.cluster.default_iallocator
904
905   @locking.ssynchronized(_config_lock, shared=1)
906   def GetPrimaryIPFamily(self):
907     """Get cluster primary ip family.
908
909     @return: primary ip family
910
911     """
912     return self._config_data.cluster.primary_ip_family
913
914   @locking.ssynchronized(_config_lock)
915   def AddNodeGroup(self, group, ec_id, check_uuid=True):
916     """Add a node group to the configuration.
917
918     This method calls group.UpgradeConfig() to fill any missing attributes
919     according to their default values.
920
921     @type group: L{objects.NodeGroup}
922     @param group: the NodeGroup object to add
923     @type ec_id: string
924     @param ec_id: unique id for the job to use when creating a missing UUID
925     @type check_uuid: bool
926     @param check_uuid: add an UUID to the group if it doesn't have one or, if
927                        it does, ensure that it does not exist in the
928                        configuration already
929
930     """
931     self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
932     self._WriteConfig()
933
934   def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
935     """Add a node group to the configuration.
936
937     """
938     logging.info("Adding node group %s to configuration", group.name)
939
940     # Some code might need to add a node group with a pre-populated UUID
941     # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
942     # the "does this UUID" exist already check.
943     if check_uuid:
944       self._EnsureUUID(group, ec_id)
945
946     try:
947       existing_uuid = self._UnlockedLookupNodeGroup(group.name)
948     except errors.OpPrereqError:
949       pass
950     else:
951       raise errors.OpPrereqError("Desired group name '%s' already exists as a"
952                                  " node group (UUID: %s)" %
953                                  (group.name, existing_uuid),
954                                  errors.ECODE_EXISTS)
955
956     group.serial_no = 1
957     group.ctime = group.mtime = time.time()
958     group.UpgradeConfig()
959
960     self._config_data.nodegroups[group.uuid] = group
961     self._config_data.cluster.serial_no += 1
962
963   @locking.ssynchronized(_config_lock)
964   def RemoveNodeGroup(self, group_uuid):
965     """Remove a node group from the configuration.
966
967     @type group_uuid: string
968     @param group_uuid: the UUID of the node group to remove
969
970     """
971     logging.info("Removing node group %s from configuration", group_uuid)
972
973     if group_uuid not in self._config_data.nodegroups:
974       raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
975
976     assert len(self._config_data.nodegroups) != 1, \
977             "Group '%s' is the only group, cannot be removed" % group_uuid
978
979     del self._config_data.nodegroups[group_uuid]
980     self._config_data.cluster.serial_no += 1
981     self._WriteConfig()
982
983   def _UnlockedLookupNodeGroup(self, target):
984     """Lookup a node group's UUID.
985
986     @type target: string or None
987     @param target: group name or UUID or None to look for the default
988     @rtype: string
989     @return: nodegroup UUID
990     @raises errors.OpPrereqError: when the target group cannot be found
991
992     """
993     if target is None:
994       if len(self._config_data.nodegroups) != 1:
995         raise errors.OpPrereqError("More than one node group exists. Target"
996                                    " group must be specified explicitely.")
997       else:
998         return self._config_data.nodegroups.keys()[0]
999     if target in self._config_data.nodegroups:
1000       return target
1001     for nodegroup in self._config_data.nodegroups.values():
1002       if nodegroup.name == target:
1003         return nodegroup.uuid
1004     raise errors.OpPrereqError("Node group '%s' not found" % target,
1005                                errors.ECODE_NOENT)
1006
1007   @locking.ssynchronized(_config_lock, shared=1)
1008   def LookupNodeGroup(self, target):
1009     """Lookup a node group's UUID.
1010
1011     This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1012
1013     @type target: string or None
1014     @param target: group name or UUID or None to look for the default
1015     @rtype: string
1016     @return: nodegroup UUID
1017
1018     """
1019     return self._UnlockedLookupNodeGroup(target)
1020
1021   def _UnlockedGetNodeGroup(self, uuid):
1022     """Lookup a node group.
1023
1024     @type uuid: string
1025     @param uuid: group UUID
1026     @rtype: L{objects.NodeGroup} or None
1027     @return: nodegroup object, or None if not found
1028
1029     """
1030     if uuid not in self._config_data.nodegroups:
1031       return None
1032
1033     return self._config_data.nodegroups[uuid]
1034
1035   @locking.ssynchronized(_config_lock, shared=1)
1036   def GetNodeGroup(self, uuid):
1037     """Lookup a node group.
1038
1039     @type uuid: string
1040     @param uuid: group UUID
1041     @rtype: L{objects.NodeGroup} or None
1042     @return: nodegroup object, or None if not found
1043
1044     """
1045     return self._UnlockedGetNodeGroup(uuid)
1046
1047   @locking.ssynchronized(_config_lock, shared=1)
1048   def GetAllNodeGroupsInfo(self):
1049     """Get the configuration of all node groups.
1050
1051     """
1052     return dict(self._config_data.nodegroups)
1053
1054   @locking.ssynchronized(_config_lock, shared=1)
1055   def GetNodeGroupList(self):
1056     """Get a list of node groups.
1057
1058     """
1059     return self._config_data.nodegroups.keys()
1060
1061   @locking.ssynchronized(_config_lock)
1062   def AddInstance(self, instance, ec_id):
1063     """Add an instance to the config.
1064
1065     This should be used after creating a new instance.
1066
1067     @type instance: L{objects.Instance}
1068     @param instance: the instance object
1069
1070     """
1071     if not isinstance(instance, objects.Instance):
1072       raise errors.ProgrammerError("Invalid type passed to AddInstance")
1073
1074     if instance.disk_template != constants.DT_DISKLESS:
1075       all_lvs = instance.MapLVsByNode()
1076       logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1077
1078     all_macs = self._AllMACs()
1079     for nic in instance.nics:
1080       if nic.mac in all_macs:
1081         raise errors.ConfigurationError("Cannot add instance %s:"
1082                                         " MAC address '%s' already in use." %
1083                                         (instance.name, nic.mac))
1084
1085     self._EnsureUUID(instance, ec_id)
1086
1087     instance.serial_no = 1
1088     instance.ctime = instance.mtime = time.time()
1089     self._config_data.instances[instance.name] = instance
1090     self._config_data.cluster.serial_no += 1
1091     self._UnlockedReleaseDRBDMinors(instance.name)
1092     self._WriteConfig()
1093
1094   def _EnsureUUID(self, item, ec_id):
1095     """Ensures a given object has a valid UUID.
1096
1097     @param item: the instance or node to be checked
1098     @param ec_id: the execution context id for the uuid reservation
1099
1100     """
1101     if not item.uuid:
1102       item.uuid = self._GenerateUniqueID(ec_id)
1103     elif item.uuid in self._AllIDs(include_temporary=True):
1104       raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1105                                       " in use" % (item.name, item.uuid))
1106
1107   def _SetInstanceStatus(self, instance_name, status):
1108     """Set the instance's status to a given value.
1109
1110     """
1111     assert isinstance(status, bool), \
1112            "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1113
1114     if instance_name not in self._config_data.instances:
1115       raise errors.ConfigurationError("Unknown instance '%s'" %
1116                                       instance_name)
1117     instance = self._config_data.instances[instance_name]
1118     if instance.admin_up != status:
1119       instance.admin_up = status
1120       instance.serial_no += 1
1121       instance.mtime = time.time()
1122       self._WriteConfig()
1123
1124   @locking.ssynchronized(_config_lock)
1125   def MarkInstanceUp(self, instance_name):
1126     """Mark the instance status to up in the config.
1127
1128     """
1129     self._SetInstanceStatus(instance_name, True)
1130
1131   @locking.ssynchronized(_config_lock)
1132   def RemoveInstance(self, instance_name):
1133     """Remove the instance from the configuration.
1134
1135     """
1136     if instance_name not in self._config_data.instances:
1137       raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1138
1139     # If a network port has been allocated to the instance,
1140     # return it to the pool of free ports.
1141     inst = self._config_data.instances[instance_name]
1142     network_port = getattr(inst, "network_port", None)
1143     if network_port is not None:
1144       self._config_data.cluster.tcpudp_port_pool.add(network_port)
1145
1146     del self._config_data.instances[instance_name]
1147     self._config_data.cluster.serial_no += 1
1148     self._WriteConfig()
1149
1150   @locking.ssynchronized(_config_lock)
1151   def RenameInstance(self, old_name, new_name):
1152     """Rename an instance.
1153
1154     This needs to be done in ConfigWriter and not by RemoveInstance
1155     combined with AddInstance as only we can guarantee an atomic
1156     rename.
1157
1158     """
1159     if old_name not in self._config_data.instances:
1160       raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1161     inst = self._config_data.instances[old_name]
1162     del self._config_data.instances[old_name]
1163     inst.name = new_name
1164
1165     for disk in inst.disks:
1166       if disk.dev_type == constants.LD_FILE:
1167         # rename the file paths in logical and physical id
1168         file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1169         disk_fname = "disk%s" % disk.iv_name.split("/")[1]
1170         disk.physical_id = disk.logical_id = (disk.logical_id[0],
1171                                               utils.PathJoin(file_storage_dir,
1172                                                              inst.name,
1173                                                              disk_fname))
1174
1175     # Force update of ssconf files
1176     self._config_data.cluster.serial_no += 1
1177
1178     self._config_data.instances[inst.name] = inst
1179     self._WriteConfig()
1180
1181   @locking.ssynchronized(_config_lock)
1182   def MarkInstanceDown(self, instance_name):
1183     """Mark the status of an instance to down in the configuration.
1184
1185     """
1186     self._SetInstanceStatus(instance_name, False)
1187
1188   def _UnlockedGetInstanceList(self):
1189     """Get the list of instances.
1190
1191     This function is for internal use, when the config lock is already held.
1192
1193     """
1194     return self._config_data.instances.keys()
1195
1196   @locking.ssynchronized(_config_lock, shared=1)
1197   def GetInstanceList(self):
1198     """Get the list of instances.
1199
1200     @return: array of instances, ex. ['instance2.example.com',
1201         'instance1.example.com']
1202
1203     """
1204     return self._UnlockedGetInstanceList()
1205
1206   @locking.ssynchronized(_config_lock, shared=1)
1207   def ExpandInstanceName(self, short_name):
1208     """Attempt to expand an incomplete instance name.
1209
1210     """
1211     return utils.MatchNameComponent(short_name,
1212                                     self._config_data.instances.keys(),
1213                                     case_sensitive=False)
1214
1215   def _UnlockedGetInstanceInfo(self, instance_name):
1216     """Returns information about an instance.
1217
1218     This function is for internal use, when the config lock is already held.
1219
1220     """
1221     if instance_name not in self._config_data.instances:
1222       return None
1223
1224     return self._config_data.instances[instance_name]
1225
1226   @locking.ssynchronized(_config_lock, shared=1)
1227   def GetInstanceInfo(self, instance_name):
1228     """Returns information about an instance.
1229
1230     It takes the information from the configuration file. Other information of
1231     an instance are taken from the live systems.
1232
1233     @param instance_name: name of the instance, e.g.
1234         I{instance1.example.com}
1235
1236     @rtype: L{objects.Instance}
1237     @return: the instance object
1238
1239     """
1240     return self._UnlockedGetInstanceInfo(instance_name)
1241
1242   @locking.ssynchronized(_config_lock, shared=1)
1243   def GetAllInstancesInfo(self):
1244     """Get the configuration of all instances.
1245
1246     @rtype: dict
1247     @return: dict of (instance, instance_info), where instance_info is what
1248               would GetInstanceInfo return for the node
1249
1250     """
1251     my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1252                     for instance in self._UnlockedGetInstanceList()])
1253     return my_dict
1254
1255   @locking.ssynchronized(_config_lock)
1256   def AddNode(self, node, ec_id):
1257     """Add a node to the configuration.
1258
1259     @type node: L{objects.Node}
1260     @param node: a Node instance
1261
1262     """
1263     logging.info("Adding node %s to configuration", node.name)
1264
1265     self._EnsureUUID(node, ec_id)
1266
1267     node.serial_no = 1
1268     node.ctime = node.mtime = time.time()
1269     self._UnlockedAddNodeToGroup(node.name, node.group)
1270     self._config_data.nodes[node.name] = node
1271     self._config_data.cluster.serial_no += 1
1272     self._WriteConfig()
1273
1274   @locking.ssynchronized(_config_lock)
1275   def RemoveNode(self, node_name):
1276     """Remove a node from the configuration.
1277
1278     """
1279     logging.info("Removing node %s from configuration", node_name)
1280
1281     if node_name not in self._config_data.nodes:
1282       raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1283
1284     self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1285     del self._config_data.nodes[node_name]
1286     self._config_data.cluster.serial_no += 1
1287     self._WriteConfig()
1288
1289   @locking.ssynchronized(_config_lock, shared=1)
1290   def ExpandNodeName(self, short_name):
1291     """Attempt to expand an incomplete instance name.
1292
1293     """
1294     return utils.MatchNameComponent(short_name,
1295                                     self._config_data.nodes.keys(),
1296                                     case_sensitive=False)
1297
1298   def _UnlockedGetNodeInfo(self, node_name):
1299     """Get the configuration of a node, as stored in the config.
1300
1301     This function is for internal use, when the config lock is already
1302     held.
1303
1304     @param node_name: the node name, e.g. I{node1.example.com}
1305
1306     @rtype: L{objects.Node}
1307     @return: the node object
1308
1309     """
1310     if node_name not in self._config_data.nodes:
1311       return None
1312
1313     return self._config_data.nodes[node_name]
1314
1315   @locking.ssynchronized(_config_lock, shared=1)
1316   def GetNodeInfo(self, node_name):
1317     """Get the configuration of a node, as stored in the config.
1318
1319     This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1320
1321     @param node_name: the node name, e.g. I{node1.example.com}
1322
1323     @rtype: L{objects.Node}
1324     @return: the node object
1325
1326     """
1327     return self._UnlockedGetNodeInfo(node_name)
1328
1329   @locking.ssynchronized(_config_lock, shared=1)
1330   def GetNodeInstances(self, node_name):
1331     """Get the instances of a node, as stored in the config.
1332
1333     @param node_name: the node name, e.g. I{node1.example.com}
1334
1335     @rtype: (list, list)
1336     @return: a tuple with two lists: the primary and the secondary instances
1337
1338     """
1339     pri = []
1340     sec = []
1341     for inst in self._config_data.instances.values():
1342       if inst.primary_node == node_name:
1343         pri.append(inst.name)
1344       if node_name in inst.secondary_nodes:
1345         sec.append(inst.name)
1346     return (pri, sec)
1347
1348   def _UnlockedGetNodeList(self):
1349     """Return the list of nodes which are in the configuration.
1350
1351     This function is for internal use, when the config lock is already
1352     held.
1353
1354     @rtype: list
1355
1356     """
1357     return self._config_data.nodes.keys()
1358
1359   @locking.ssynchronized(_config_lock, shared=1)
1360   def GetNodeList(self):
1361     """Return the list of nodes which are in the configuration.
1362
1363     """
1364     return self._UnlockedGetNodeList()
1365
1366   def _UnlockedGetOnlineNodeList(self):
1367     """Return the list of nodes which are online.
1368
1369     """
1370     all_nodes = [self._UnlockedGetNodeInfo(node)
1371                  for node in self._UnlockedGetNodeList()]
1372     return [node.name for node in all_nodes if not node.offline]
1373
1374   @locking.ssynchronized(_config_lock, shared=1)
1375   def GetOnlineNodeList(self):
1376     """Return the list of nodes which are online.
1377
1378     """
1379     return self._UnlockedGetOnlineNodeList()
1380
1381   @locking.ssynchronized(_config_lock, shared=1)
1382   def GetVmCapableNodeList(self):
1383     """Return the list of nodes which are not vm capable.
1384
1385     """
1386     all_nodes = [self._UnlockedGetNodeInfo(node)
1387                  for node in self._UnlockedGetNodeList()]
1388     return [node.name for node in all_nodes if node.vm_capable]
1389
1390   @locking.ssynchronized(_config_lock, shared=1)
1391   def GetNonVmCapableNodeList(self):
1392     """Return the list of nodes which are not vm capable.
1393
1394     """
1395     all_nodes = [self._UnlockedGetNodeInfo(node)
1396                  for node in self._UnlockedGetNodeList()]
1397     return [node.name for node in all_nodes if not node.vm_capable]
1398
1399   @locking.ssynchronized(_config_lock, shared=1)
1400   def GetAllNodesInfo(self):
1401     """Get the configuration of all nodes.
1402
1403     @rtype: dict
1404     @return: dict of (node, node_info), where node_info is what
1405               would GetNodeInfo return for the node
1406
1407     """
1408     my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
1409                     for node in self._UnlockedGetNodeList()])
1410     return my_dict
1411
1412   @locking.ssynchronized(_config_lock, shared=1)
1413   def GetNodeGroupsFromNodes(self, nodes):
1414     """Returns groups for a list of nodes.
1415
1416     @type nodes: list of string
1417     @param nodes: List of node names
1418     @rtype: frozenset
1419
1420     """
1421     return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1422
1423   def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1424     """Get the number of current and maximum desired and possible candidates.
1425
1426     @type exceptions: list
1427     @param exceptions: if passed, list of nodes that should be ignored
1428     @rtype: tuple
1429     @return: tuple of (current, desired and possible, possible)
1430
1431     """
1432     mc_now = mc_should = mc_max = 0
1433     for node in self._config_data.nodes.values():
1434       if exceptions and node.name in exceptions:
1435         continue
1436       if not (node.offline or node.drained) and node.master_capable:
1437         mc_max += 1
1438       if node.master_candidate:
1439         mc_now += 1
1440     mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1441     return (mc_now, mc_should, mc_max)
1442
1443   @locking.ssynchronized(_config_lock, shared=1)
1444   def GetMasterCandidateStats(self, exceptions=None):
1445     """Get the number of current and maximum possible candidates.
1446
1447     This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1448
1449     @type exceptions: list
1450     @param exceptions: if passed, list of nodes that should be ignored
1451     @rtype: tuple
1452     @return: tuple of (current, max)
1453
1454     """
1455     return self._UnlockedGetMasterCandidateStats(exceptions)
1456
1457   @locking.ssynchronized(_config_lock)
1458   def MaintainCandidatePool(self, exceptions):
1459     """Try to grow the candidate pool to the desired size.
1460
1461     @type exceptions: list
1462     @param exceptions: if passed, list of nodes that should be ignored
1463     @rtype: list
1464     @return: list with the adjusted nodes (L{objects.Node} instances)
1465
1466     """
1467     mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1468     mod_list = []
1469     if mc_now < mc_max:
1470       node_list = self._config_data.nodes.keys()
1471       random.shuffle(node_list)
1472       for name in node_list:
1473         if mc_now >= mc_max:
1474           break
1475         node = self._config_data.nodes[name]
1476         if (node.master_candidate or node.offline or node.drained or
1477             node.name in exceptions or not node.master_capable):
1478           continue
1479         mod_list.append(node)
1480         node.master_candidate = True
1481         node.serial_no += 1
1482         mc_now += 1
1483       if mc_now != mc_max:
1484         # this should not happen
1485         logging.warning("Warning: MaintainCandidatePool didn't manage to"
1486                         " fill the candidate pool (%d/%d)", mc_now, mc_max)
1487       if mod_list:
1488         self._config_data.cluster.serial_no += 1
1489         self._WriteConfig()
1490
1491     return mod_list
1492
1493   def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1494     """Add a given node to the specified group.
1495
1496     """
1497     if nodegroup_uuid not in self._config_data.nodegroups:
1498       # This can happen if a node group gets deleted between its lookup and
1499       # when we're adding the first node to it, since we don't keep a lock in
1500       # the meantime. It's ok though, as we'll fail cleanly if the node group
1501       # is not found anymore.
1502       raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1503     if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1504       self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1505
1506   def _UnlockedRemoveNodeFromGroup(self, node):
1507     """Remove a given node from its group.
1508
1509     """
1510     nodegroup = node.group
1511     if nodegroup not in self._config_data.nodegroups:
1512       logging.warning("Warning: node '%s' has unknown node group '%s'"
1513                       " (while being removed from it)", node.name, nodegroup)
1514     nodegroup_obj = self._config_data.nodegroups[nodegroup]
1515     if node.name not in nodegroup_obj.members:
1516       logging.warning("Warning: node '%s' not a member of its node group '%s'"
1517                       " (while being removed from it)", node.name, nodegroup)
1518     else:
1519       nodegroup_obj.members.remove(node.name)
1520
1521   @locking.ssynchronized(_config_lock)
1522   def AssignGroupNodes(self, mods):
1523     """Changes the group of a number of nodes.
1524
1525     @type mods: list of tuples; (node name, new group UUID)
1526     @param mods: Node membership modifications
1527
1528     """
1529     groups = self._config_data.nodegroups
1530     nodes = self._config_data.nodes
1531
1532     resmod = []
1533
1534     # Try to resolve names/UUIDs first
1535     for (node_name, new_group_uuid) in mods:
1536       try:
1537         node = nodes[node_name]
1538       except KeyError:
1539         raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1540
1541       if node.group == new_group_uuid:
1542         # Node is being assigned to its current group
1543         logging.debug("Node '%s' was assigned to its current group (%s)",
1544                       node_name, node.group)
1545         continue
1546
1547       # Try to find current group of node
1548       try:
1549         old_group = groups[node.group]
1550       except KeyError:
1551         raise errors.ConfigurationError("Unable to find old group '%s'" %
1552                                         node.group)
1553
1554       # Try to find new group for node
1555       try:
1556         new_group = groups[new_group_uuid]
1557       except KeyError:
1558         raise errors.ConfigurationError("Unable to find new group '%s'" %
1559                                         new_group_uuid)
1560
1561       assert node.name in old_group.members, \
1562         ("Inconsistent configuration: node '%s' not listed in members for its"
1563          " old group '%s'" % (node.name, old_group.uuid))
1564       assert node.name not in new_group.members, \
1565         ("Inconsistent configuration: node '%s' already listed in members for"
1566          " its new group '%s'" % (node.name, new_group.uuid))
1567
1568       resmod.append((node, old_group, new_group))
1569
1570     # Apply changes
1571     for (node, old_group, new_group) in resmod:
1572       assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
1573         "Assigning to current group is not possible"
1574
1575       node.group = new_group.uuid
1576
1577       # Update members of involved groups
1578       if node.name in old_group.members:
1579         old_group.members.remove(node.name)
1580       if node.name not in new_group.members:
1581         new_group.members.append(node.name)
1582
1583     # Update timestamps and serials (only once per node/group object)
1584     now = time.time()
1585     for obj in frozenset(itertools.chain(*resmod)): # pylint: disable-msg=W0142
1586       obj.serial_no += 1
1587       obj.mtime = now
1588
1589     # Force ssconf update
1590     self._config_data.cluster.serial_no += 1
1591
1592     self._WriteConfig()
1593
1594   def _BumpSerialNo(self):
1595     """Bump up the serial number of the config.
1596
1597     """
1598     self._config_data.serial_no += 1
1599     self._config_data.mtime = time.time()
1600
1601   def _AllUUIDObjects(self):
1602     """Returns all objects with uuid attributes.
1603
1604     """
1605     return (self._config_data.instances.values() +
1606             self._config_data.nodes.values() +
1607             self._config_data.nodegroups.values() +
1608             [self._config_data.cluster])
1609
1610   def _OpenConfig(self, accept_foreign):
1611     """Read the config data from disk.
1612
1613     """
1614     raw_data = utils.ReadFile(self._cfg_file)
1615
1616     try:
1617       data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1618     except Exception, err:
1619       raise errors.ConfigurationError(err)
1620
1621     # Make sure the configuration has the right version
1622     _ValidateConfig(data)
1623
1624     if (not hasattr(data, 'cluster') or
1625         not hasattr(data.cluster, 'rsahostkeypub')):
1626       raise errors.ConfigurationError("Incomplete configuration"
1627                                       " (missing cluster.rsahostkeypub)")
1628
1629     if data.cluster.master_node != self._my_hostname and not accept_foreign:
1630       msg = ("The configuration denotes node %s as master, while my"
1631              " hostname is %s; opening a foreign configuration is only"
1632              " possible in accept_foreign mode" %
1633              (data.cluster.master_node, self._my_hostname))
1634       raise errors.ConfigurationError(msg)
1635
1636     # Upgrade configuration if needed
1637     data.UpgradeConfig()
1638
1639     self._config_data = data
1640     # reset the last serial as -1 so that the next write will cause
1641     # ssconf update
1642     self._last_cluster_serial = -1
1643
1644     # And finally run our (custom) config upgrade sequence
1645     self._UpgradeConfig()
1646
1647     self._cfg_id = utils.GetFileID(path=self._cfg_file)
1648
1649   def _UpgradeConfig(self):
1650     """Run upgrade steps that cannot be done purely in the objects.
1651
1652     This is because some data elements need uniqueness across the
1653     whole configuration, etc.
1654
1655     @warning: this function will call L{_WriteConfig()}, but also
1656         L{DropECReservations} so it needs to be called only from a
1657         "safe" place (the constructor). If one wanted to call it with
1658         the lock held, a DropECReservationUnlocked would need to be
1659         created first, to avoid causing deadlock.
1660
1661     """
1662     modified = False
1663     for item in self._AllUUIDObjects():
1664       if item.uuid is None:
1665         item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1666         modified = True
1667     if not self._config_data.nodegroups:
1668       default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
1669       default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
1670                                             members=[])
1671       self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
1672       modified = True
1673     for node in self._config_data.nodes.values():
1674       if not node.group:
1675         node.group = self.LookupNodeGroup(None)
1676         modified = True
1677       # This is technically *not* an upgrade, but needs to be done both when
1678       # nodegroups are being added, and upon normally loading the config,
1679       # because the members list of a node group is discarded upon
1680       # serializing/deserializing the object.
1681       self._UnlockedAddNodeToGroup(node.name, node.group)
1682     if modified:
1683       self._WriteConfig()
1684       # This is ok even if it acquires the internal lock, as _UpgradeConfig is
1685       # only called at config init time, without the lock held
1686       self.DropECReservations(_UPGRADE_CONFIG_JID)
1687
1688   def _DistributeConfig(self, feedback_fn):
1689     """Distribute the configuration to the other nodes.
1690
1691     Currently, this only copies the configuration file. In the future,
1692     it could be used to encapsulate the 2/3-phase update mechanism.
1693
1694     """
1695     if self._offline:
1696       return True
1697
1698     bad = False
1699
1700     node_list = []
1701     addr_list = []
1702     myhostname = self._my_hostname
1703     # we can skip checking whether _UnlockedGetNodeInfo returns None
1704     # since the node list comes from _UnlocketGetNodeList, and we are
1705     # called with the lock held, so no modifications should take place
1706     # in between
1707     for node_name in self._UnlockedGetNodeList():
1708       if node_name == myhostname:
1709         continue
1710       node_info = self._UnlockedGetNodeInfo(node_name)
1711       if not node_info.master_candidate:
1712         continue
1713       node_list.append(node_info.name)
1714       addr_list.append(node_info.primary_ip)
1715
1716     result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
1717                                             address_list=addr_list)
1718     for to_node, to_result in result.items():
1719       msg = to_result.fail_msg
1720       if msg:
1721         msg = ("Copy of file %s to node %s failed: %s" %
1722                (self._cfg_file, to_node, msg))
1723         logging.error(msg)
1724
1725         if feedback_fn:
1726           feedback_fn(msg)
1727
1728         bad = True
1729
1730     return not bad
1731
1732   def _WriteConfig(self, destination=None, feedback_fn=None):
1733     """Write the configuration data to persistent storage.
1734
1735     """
1736     assert feedback_fn is None or callable(feedback_fn)
1737
1738     # Warn on config errors, but don't abort the save - the
1739     # configuration has already been modified, and we can't revert;
1740     # the best we can do is to warn the user and save as is, leaving
1741     # recovery to the user
1742     config_errors = self._UnlockedVerifyConfig()
1743     if config_errors:
1744       errmsg = ("Configuration data is not consistent: %s" %
1745                 (utils.CommaJoin(config_errors)))
1746       logging.critical(errmsg)
1747       if feedback_fn:
1748         feedback_fn(errmsg)
1749
1750     if destination is None:
1751       destination = self._cfg_file
1752     self._BumpSerialNo()
1753     txt = serializer.Dump(self._config_data.ToDict())
1754
1755     getents = self._getents()
1756     try:
1757       fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
1758                                close=False, gid=getents.confd_gid, mode=0640)
1759     except errors.LockError:
1760       raise errors.ConfigurationError("The configuration file has been"
1761                                       " modified since the last write, cannot"
1762                                       " update")
1763     try:
1764       self._cfg_id = utils.GetFileID(fd=fd)
1765     finally:
1766       os.close(fd)
1767
1768     self.write_count += 1
1769
1770     # and redistribute the config file to master candidates
1771     self._DistributeConfig(feedback_fn)
1772
1773     # Write ssconf files on all nodes (including locally)
1774     if self._last_cluster_serial < self._config_data.cluster.serial_no:
1775       if not self._offline:
1776         result = rpc.RpcRunner.call_write_ssconf_files(
1777           self._UnlockedGetOnlineNodeList(),
1778           self._UnlockedGetSsconfValues())
1779
1780         for nname, nresu in result.items():
1781           msg = nresu.fail_msg
1782           if msg:
1783             errmsg = ("Error while uploading ssconf files to"
1784                       " node %s: %s" % (nname, msg))
1785             logging.warning(errmsg)
1786
1787             if feedback_fn:
1788               feedback_fn(errmsg)
1789
1790       self._last_cluster_serial = self._config_data.cluster.serial_no
1791
1792   def _UnlockedGetSsconfValues(self):
1793     """Return the values needed by ssconf.
1794
1795     @rtype: dict
1796     @return: a dictionary with keys the ssconf names and values their
1797         associated value
1798
1799     """
1800     fn = "\n".join
1801     instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1802     node_names = utils.NiceSort(self._UnlockedGetNodeList())
1803     node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1804     node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
1805                     for ninfo in node_info]
1806     node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
1807                     for ninfo in node_info]
1808
1809     instance_data = fn(instance_names)
1810     off_data = fn(node.name for node in node_info if node.offline)
1811     on_data = fn(node.name for node in node_info if not node.offline)
1812     mc_data = fn(node.name for node in node_info if node.master_candidate)
1813     mc_ips_data = fn(node.primary_ip for node in node_info
1814                      if node.master_candidate)
1815     node_data = fn(node_names)
1816     node_pri_ips_data = fn(node_pri_ips)
1817     node_snd_ips_data = fn(node_snd_ips)
1818
1819     cluster = self._config_data.cluster
1820     cluster_tags = fn(cluster.GetTags())
1821
1822     hypervisor_list = fn(cluster.enabled_hypervisors)
1823
1824     uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
1825
1826     nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
1827                   self._config_data.nodegroups.values()]
1828     nodegroups_data = fn(utils.NiceSort(nodegroups))
1829
1830     return {
1831       constants.SS_CLUSTER_NAME: cluster.cluster_name,
1832       constants.SS_CLUSTER_TAGS: cluster_tags,
1833       constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1834       constants.SS_MASTER_CANDIDATES: mc_data,
1835       constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
1836       constants.SS_MASTER_IP: cluster.master_ip,
1837       constants.SS_MASTER_NETDEV: cluster.master_netdev,
1838       constants.SS_MASTER_NODE: cluster.master_node,
1839       constants.SS_NODE_LIST: node_data,
1840       constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
1841       constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
1842       constants.SS_OFFLINE_NODES: off_data,
1843       constants.SS_ONLINE_NODES: on_data,
1844       constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
1845       constants.SS_INSTANCE_LIST: instance_data,
1846       constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1847       constants.SS_HYPERVISOR_LIST: hypervisor_list,
1848       constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
1849       constants.SS_UID_POOL: uid_pool,
1850       constants.SS_NODEGROUPS: nodegroups_data,
1851       }
1852
1853   @locking.ssynchronized(_config_lock, shared=1)
1854   def GetSsconfValues(self):
1855     """Wrapper using lock around _UnlockedGetSsconf().
1856
1857     """
1858     return self._UnlockedGetSsconfValues()
1859
1860   @locking.ssynchronized(_config_lock, shared=1)
1861   def GetVGName(self):
1862     """Return the volume group name.
1863
1864     """
1865     return self._config_data.cluster.volume_group_name
1866
1867   @locking.ssynchronized(_config_lock)
1868   def SetVGName(self, vg_name):
1869     """Set the volume group name.
1870
1871     """
1872     self._config_data.cluster.volume_group_name = vg_name
1873     self._config_data.cluster.serial_no += 1
1874     self._WriteConfig()
1875
1876   @locking.ssynchronized(_config_lock, shared=1)
1877   def GetDRBDHelper(self):
1878     """Return DRBD usermode helper.
1879
1880     """
1881     return self._config_data.cluster.drbd_usermode_helper
1882
1883   @locking.ssynchronized(_config_lock)
1884   def SetDRBDHelper(self, drbd_helper):
1885     """Set DRBD usermode helper.
1886
1887     """
1888     self._config_data.cluster.drbd_usermode_helper = drbd_helper
1889     self._config_data.cluster.serial_no += 1
1890     self._WriteConfig()
1891
1892   @locking.ssynchronized(_config_lock, shared=1)
1893   def GetMACPrefix(self):
1894     """Return the mac prefix.
1895
1896     """
1897     return self._config_data.cluster.mac_prefix
1898
1899   @locking.ssynchronized(_config_lock, shared=1)
1900   def GetClusterInfo(self):
1901     """Returns information about the cluster
1902
1903     @rtype: L{objects.Cluster}
1904     @return: the cluster object
1905
1906     """
1907     return self._config_data.cluster
1908
1909   @locking.ssynchronized(_config_lock, shared=1)
1910   def HasAnyDiskOfType(self, dev_type):
1911     """Check if in there is at disk of the given type in the configuration.
1912
1913     """
1914     return self._config_data.HasAnyDiskOfType(dev_type)
1915
1916   @locking.ssynchronized(_config_lock)
1917   def Update(self, target, feedback_fn):
1918     """Notify function to be called after updates.
1919
1920     This function must be called when an object (as returned by
1921     GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
1922     caller wants the modifications saved to the backing store. Note
1923     that all modified objects will be saved, but the target argument
1924     is the one the caller wants to ensure that it's saved.
1925
1926     @param target: an instance of either L{objects.Cluster},
1927         L{objects.Node} or L{objects.Instance} which is existing in
1928         the cluster
1929     @param feedback_fn: Callable feedback function
1930
1931     """
1932     if self._config_data is None:
1933       raise errors.ProgrammerError("Configuration file not read,"
1934                                    " cannot save.")
1935     update_serial = False
1936     if isinstance(target, objects.Cluster):
1937       test = target == self._config_data.cluster
1938     elif isinstance(target, objects.Node):
1939       test = target in self._config_data.nodes.values()
1940       update_serial = True
1941     elif isinstance(target, objects.Instance):
1942       test = target in self._config_data.instances.values()
1943     elif isinstance(target, objects.NodeGroup):
1944       test = target in self._config_data.nodegroups.values()
1945     else:
1946       raise errors.ProgrammerError("Invalid object type (%s) passed to"
1947                                    " ConfigWriter.Update" % type(target))
1948     if not test:
1949       raise errors.ConfigurationError("Configuration updated since object"
1950                                       " has been read or unknown object")
1951     target.serial_no += 1
1952     target.mtime = now = time.time()
1953
1954     if update_serial:
1955       # for node updates, we need to increase the cluster serial too
1956       self._config_data.cluster.serial_no += 1
1957       self._config_data.cluster.mtime = now
1958
1959     if isinstance(target, objects.Instance):
1960       self._UnlockedReleaseDRBDMinors(target.name)
1961
1962     self._WriteConfig(feedback_fn=feedback_fn)
1963
1964   @locking.ssynchronized(_config_lock)
1965   def DropECReservations(self, ec_id):
1966     """Drop per-execution-context reservations
1967
1968     """
1969     for rm in self._all_rms:
1970       rm.DropECReservations(ec_id)