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