Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 4fae38c5

History | View | Annotate | Download (45.9 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007 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
import os
35
import random
36
import logging
37
import time
38

    
39
from ganeti import errors
40
from ganeti import locking
41
from ganeti import utils
42
from ganeti import constants
43
from ganeti import rpc
44
from ganeti import objects
45
from ganeti import serializer
46

    
47

    
48
_config_lock = locking.SharedLock()
49

    
50
# job id used for resource management at config upgrade time
51
_UPGRADE_CONFIG_JID="jid-cfg-upgrade"
52

    
53

    
54
def _ValidateConfig(data):
55
  """Verifies that a configuration objects looks valid.
56

57
  This only verifies the version of the configuration.
58

59
  @raise errors.ConfigurationError: if the version differs from what
60
      we expect
61

62
  """
63
  if data.version != constants.CONFIG_VERSION:
64
    raise errors.ConfigurationError("Cluster configuration version"
65
                                    " mismatch, got %s instead of %s" %
66
                                    (data.version,
67
                                     constants.CONFIG_VERSION))
68

    
69

    
70
class TemporaryReservationManager:
71
  """A temporary resource reservation manager.
72

73
  This is used to reserve resources in a job, before using them, making sure
74
  other jobs cannot get them in the meantime.
75

76
  """
77
  def __init__(self):
78
    self._ec_reserved = {}
79

    
80
  def Reserved(self, resource):
81
    for holder_reserved in self._ec_reserved.items():
82
      if resource in holder_reserved:
83
        return True
84
    return False
85

    
86
  def Reserve(self, ec_id, resource):
87
    if self.Reserved(resource):
88
      raise errors.ReservationError("Duplicate reservation for resource: %s." %
89
                                    (resource))
90
    if ec_id not in self._ec_reserved:
91
      self._ec_reserved[ec_id] = set([resource])
92
    else:
93
      self._ec_reserved[ec_id].add(resource)
94

    
95
  def DropECReservations(self, ec_id):
96
    if ec_id in self._ec_reserved:
97
      del self._ec_reserved[ec_id]
98

    
99
  def GetReserved(self):
100
    all_reserved = set()
101
    for holder_reserved in self._ec_reserved.values():
102
      all_reserved.update(holder_reserved)
103
    return all_reserved
104

    
105
  def Generate(self, existing, generate_one_fn, ec_id):
106
    """Generate a new resource of this type
107

108
    """
109
    assert callable(generate_one_fn)
110

    
111
    all_elems = self.GetReserved()
112
    all_elems.update(existing)
113
    retries = 64
114
    while retries > 0:
115
      new_resource = generate_one_fn()
116
      if new_resource is not None and new_resource not in all_elems:
117
        break
118
    else:
119
      raise errors.ConfigurationError("Not able generate new resource"
120
                                      " (last tried: %s)" % new_resource)
121
    self.Reserve(ec_id, new_resource)
122
    return new_resource
123

    
124

    
125
class ConfigWriter:
126
  """The interface to the cluster configuration.
127

128
  """
129
  def __init__(self, cfg_file=None, offline=False):
130
    self.write_count = 0
131
    self._lock = _config_lock
132
    self._config_data = None
133
    self._offline = offline
134
    if cfg_file is None:
135
      self._cfg_file = constants.CLUSTER_CONF_FILE
136
    else:
137
      self._cfg_file = cfg_file
138
    self._temporary_ids = TemporaryReservationManager()
139
    self._temporary_drbds = {}
140
    self._temporary_macs = set()
141
    # Note: in order to prevent errors when resolving our name in
142
    # _DistributeConfig, we compute it here once and reuse it; it's
143
    # better to raise an error before starting to modify the config
144
    # file than after it was modified
145
    self._my_hostname = utils.HostInfo().name
146
    self._last_cluster_serial = -1
147
    self._OpenConfig()
148

    
149
  # this method needs to be static, so that we can call it on the class
150
  @staticmethod
151
  def IsCluster():
152
    """Check if the cluster is configured.
153

154
    """
155
    return os.path.exists(constants.CLUSTER_CONF_FILE)
156

    
157
  @locking.ssynchronized(_config_lock, shared=1)
158
  def GenerateMAC(self):
159
    """Generate a MAC for an instance.
160

161
    This should check the current instances for duplicates.
162

163
    """
164
    prefix = self._config_data.cluster.mac_prefix
165
    all_macs = self._AllMACs()
166
    retries = 64
167
    while retries > 0:
168
      byte1 = random.randrange(0, 256)
169
      byte2 = random.randrange(0, 256)
170
      byte3 = random.randrange(0, 256)
171
      mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
172
      if mac not in all_macs and mac not in self._temporary_macs:
173
        break
174
      retries -= 1
175
    else:
176
      raise errors.ConfigurationError("Can't generate unique MAC")
177
    self._temporary_macs.add(mac)
178
    return mac
179

    
180
  @locking.ssynchronized(_config_lock, shared=1)
181
  def IsMacInUse(self, mac):
182
    """Predicate: check if the specified MAC is in use in the Ganeti cluster.
183

184
    This only checks instances managed by this cluster, it does not
185
    check for potential collisions elsewhere.
186

187
    """
188
    all_macs = self._AllMACs()
189
    return mac in all_macs or mac in self._temporary_macs
190

    
191
  @locking.ssynchronized(_config_lock, shared=1)
192
  def GenerateDRBDSecret(self):
193
    """Generate a DRBD secret.
194

195
    This checks the current disks for duplicates.
196

197
    """
198
    all_secrets = self._AllDRBDSecrets()
199
    retries = 64
200
    while retries > 0:
201
      secret = utils.GenerateSecret()
202
      if secret not in all_secrets:
203
        break
204
      retries -= 1
205
    else:
206
      raise errors.ConfigurationError("Can't generate unique DRBD secret")
207
    return secret
208

    
209
  def _AllLVs(self):
210
    """Compute the list of all LVs.
211

212
    """
213
    lvnames = set()
214
    for instance in self._config_data.instances.values():
215
      node_data = instance.MapLVsByNode()
216
      for lv_list in node_data.values():
217
        lvnames.update(lv_list)
218
    return lvnames
219

    
220
  def _AllIDs(self, include_temporary):
221
    """Compute the list of all UUIDs and names we have.
222

223
    @type include_temporary: boolean
224
    @param include_temporary: whether to include the _temporary_ids set
225
    @rtype: set
226
    @return: a set of IDs
227

228
    """
229
    existing = set()
230
    if include_temporary:
231
      existing.update(self._temporary_ids.GetReserved())
232
    existing.update(self._AllLVs())
233
    existing.update(self._config_data.instances.keys())
234
    existing.update(self._config_data.nodes.keys())
235
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
236
    return existing
237

    
238
  def _GenerateUniqueID(self, ec_id):
239
    """Generate an unique UUID.
240

241
    This checks the current node, instances and disk names for
242
    duplicates.
243

244
    @rtype: string
245
    @return: the unique id
246

247
    """
248
    existing = self._AllIDs(include_temporary=False)
249
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
250

    
251
  @locking.ssynchronized(_config_lock, shared=1)
252
  def GenerateUniqueID(self, ec_id):
253
    """Generate an unique ID.
254

255
    This is just a wrapper over the unlocked version.
256

257
    @type ec_id: string
258
    @param ec_id: unique id for the job to reserve the id to
259

260
    """
261
    return self._GenerateUniqueID(ec_id)
262

    
263
  def _AllMACs(self):
264
    """Return all MACs present in the config.
265

266
    @rtype: list
267
    @return: the list of all MACs
268

269
    """
270
    result = []
271
    for instance in self._config_data.instances.values():
272
      for nic in instance.nics:
273
        result.append(nic.mac)
274

    
275
    return result
276

    
277
  def _AllDRBDSecrets(self):
278
    """Return all DRBD secrets present in the config.
279

280
    @rtype: list
281
    @return: the list of all DRBD secrets
282

283
    """
284
    def helper(disk, result):
285
      """Recursively gather secrets from this disk."""
286
      if disk.dev_type == constants.DT_DRBD8:
287
        result.append(disk.logical_id[5])
288
      if disk.children:
289
        for child in disk.children:
290
          helper(child, result)
291

    
292
    result = []
293
    for instance in self._config_data.instances.values():
294
      for disk in instance.disks:
295
        helper(disk, result)
296

    
297
    return result
298

    
299
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
300
    """Compute duplicate disk IDs
301

302
    @type disk: L{objects.Disk}
303
    @param disk: the disk at which to start searching
304
    @type l_ids: list
305
    @param l_ids: list of current logical ids
306
    @type p_ids: list
307
    @param p_ids: list of current physical ids
308
    @rtype: list
309
    @return: a list of error messages
310

311
    """
312
    result = []
313
    if disk.logical_id is not None:
314
      if disk.logical_id in l_ids:
315
        result.append("duplicate logical id %s" % str(disk.logical_id))
316
      else:
317
        l_ids.append(disk.logical_id)
318
    if disk.physical_id is not None:
319
      if disk.physical_id in p_ids:
320
        result.append("duplicate physical id %s" % str(disk.physical_id))
321
      else:
322
        p_ids.append(disk.physical_id)
323

    
324
    if disk.children:
325
      for child in disk.children:
326
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
327
    return result
328

    
329
  def _UnlockedVerifyConfig(self):
330
    """Verify function.
331

332
    @rtype: list
333
    @return: a list of error messages; a non-empty list signifies
334
        configuration errors
335

336
    """
337
    result = []
338
    seen_macs = []
339
    ports = {}
340
    data = self._config_data
341
    seen_lids = []
342
    seen_pids = []
343

    
344
    # global cluster checks
345
    if not data.cluster.enabled_hypervisors:
346
      result.append("enabled hypervisors list doesn't have any entries")
347
    invalid_hvs = set(data.cluster.enabled_hypervisors) - constants.HYPER_TYPES
348
    if invalid_hvs:
349
      result.append("enabled hypervisors contains invalid entries: %s" %
350
                    invalid_hvs)
351

    
352
    if data.cluster.master_node not in data.nodes:
353
      result.append("cluster has invalid primary node '%s'" %
354
                    data.cluster.master_node)
355

    
356
    # per-instance checks
357
    for instance_name in data.instances:
358
      instance = data.instances[instance_name]
359
      if instance.primary_node not in data.nodes:
360
        result.append("instance '%s' has invalid primary node '%s'" %
361
                      (instance_name, instance.primary_node))
362
      for snode in instance.secondary_nodes:
363
        if snode not in data.nodes:
364
          result.append("instance '%s' has invalid secondary node '%s'" %
365
                        (instance_name, snode))
366
      for idx, nic in enumerate(instance.nics):
367
        if nic.mac in seen_macs:
368
          result.append("instance '%s' has NIC %d mac %s duplicate" %
369
                        (instance_name, idx, nic.mac))
370
        else:
371
          seen_macs.append(nic.mac)
372

    
373
      # gather the drbd ports for duplicate checks
374
      for dsk in instance.disks:
375
        if dsk.dev_type in constants.LDS_DRBD:
376
          tcp_port = dsk.logical_id[2]
377
          if tcp_port not in ports:
378
            ports[tcp_port] = []
379
          ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
380
      # gather network port reservation
381
      net_port = getattr(instance, "network_port", None)
382
      if net_port is not None:
383
        if net_port not in ports:
384
          ports[net_port] = []
385
        ports[net_port].append((instance.name, "network port"))
386

    
387
      # instance disk verify
388
      for idx, disk in enumerate(instance.disks):
389
        result.extend(["instance '%s' disk %d error: %s" %
390
                       (instance.name, idx, msg) for msg in disk.Verify()])
391
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
392

    
393
    # cluster-wide pool of free ports
394
    for free_port in data.cluster.tcpudp_port_pool:
395
      if free_port not in ports:
396
        ports[free_port] = []
397
      ports[free_port].append(("cluster", "port marked as free"))
398

    
399
    # compute tcp/udp duplicate ports
400
    keys = ports.keys()
401
    keys.sort()
402
    for pnum in keys:
403
      pdata = ports[pnum]
404
      if len(pdata) > 1:
405
        txt = ", ".join(["%s/%s" % val for val in pdata])
406
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
407

    
408
    # highest used tcp port check
409
    if keys:
410
      if keys[-1] > data.cluster.highest_used_port:
411
        result.append("Highest used port mismatch, saved %s, computed %s" %
412
                      (data.cluster.highest_used_port, keys[-1]))
413

    
414
    if not data.nodes[data.cluster.master_node].master_candidate:
415
      result.append("Master node is not a master candidate")
416

    
417
    # master candidate checks
418
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
419
    if mc_now < mc_max:
420
      result.append("Not enough master candidates: actual %d, target %d" %
421
                    (mc_now, mc_max))
422

    
423
    # node checks
424
    for node in data.nodes.values():
425
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
426
        result.append("Node %s state is invalid: master_candidate=%s,"
427
                      " drain=%s, offline=%s" %
428
                      (node.name, node.master_candidate, node.drain,
429
                       node.offline))
430

    
431
    # drbd minors check
432
    d_map, duplicates = self._UnlockedComputeDRBDMap()
433
    for node, minor, instance_a, instance_b in duplicates:
434
      result.append("DRBD minor %d on node %s is assigned twice to instances"
435
                    " %s and %s" % (minor, node, instance_a, instance_b))
436

    
437
    # IP checks
438
    ips = { data.cluster.master_ip: ["cluster_ip"] }
439
    def _helper(ip, name):
440
      if ip in ips:
441
        ips[ip].append(name)
442
      else:
443
        ips[ip] = [name]
444

    
445
    for node in data.nodes.values():
446
      _helper(node.primary_ip, "node:%s/primary" % node.name)
447
      if node.secondary_ip != node.primary_ip:
448
        _helper(node.secondary_ip, "node:%s/secondary" % node.name)
449

    
450
    for ip, owners in ips.items():
451
      if len(owners) > 1:
452
        result.append("IP address %s is used by multiple owners: %s" %
453
                      (ip, ", ".join(owners)))
454
    return result
455

    
456
  @locking.ssynchronized(_config_lock, shared=1)
457
  def VerifyConfig(self):
458
    """Verify function.
459

460
    This is just a wrapper over L{_UnlockedVerifyConfig}.
461

462
    @rtype: list
463
    @return: a list of error messages; a non-empty list signifies
464
        configuration errors
465

466
    """
467
    return self._UnlockedVerifyConfig()
468

    
469
  def _UnlockedSetDiskID(self, disk, node_name):
470
    """Convert the unique ID to the ID needed on the target nodes.
471

472
    This is used only for drbd, which needs ip/port configuration.
473

474
    The routine descends down and updates its children also, because
475
    this helps when the only the top device is passed to the remote
476
    node.
477

478
    This function is for internal use, when the config lock is already held.
479

480
    """
481
    if disk.children:
482
      for child in disk.children:
483
        self._UnlockedSetDiskID(child, node_name)
484

    
485
    if disk.logical_id is None and disk.physical_id is not None:
486
      return
487
    if disk.dev_type == constants.LD_DRBD8:
488
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
489
      if node_name not in (pnode, snode):
490
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
491
                                        node_name)
492
      pnode_info = self._UnlockedGetNodeInfo(pnode)
493
      snode_info = self._UnlockedGetNodeInfo(snode)
494
      if pnode_info is None or snode_info is None:
495
        raise errors.ConfigurationError("Can't find primary or secondary node"
496
                                        " for %s" % str(disk))
497
      p_data = (pnode_info.secondary_ip, port)
498
      s_data = (snode_info.secondary_ip, port)
499
      if pnode == node_name:
500
        disk.physical_id = p_data + s_data + (pminor, secret)
501
      else: # it must be secondary, we tested above
502
        disk.physical_id = s_data + p_data + (sminor, secret)
503
    else:
504
      disk.physical_id = disk.logical_id
505
    return
506

    
507
  @locking.ssynchronized(_config_lock)
508
  def SetDiskID(self, disk, node_name):
509
    """Convert the unique ID to the ID needed on the target nodes.
510

511
    This is used only for drbd, which needs ip/port configuration.
512

513
    The routine descends down and updates its children also, because
514
    this helps when the only the top device is passed to the remote
515
    node.
516

517
    """
518
    return self._UnlockedSetDiskID(disk, node_name)
519

    
520
  @locking.ssynchronized(_config_lock)
521
  def AddTcpUdpPort(self, port):
522
    """Adds a new port to the available port pool.
523

524
    """
525
    if not isinstance(port, int):
526
      raise errors.ProgrammerError("Invalid type passed for port")
527

    
528
    self._config_data.cluster.tcpudp_port_pool.add(port)
529
    self._WriteConfig()
530

    
531
  @locking.ssynchronized(_config_lock, shared=1)
532
  def GetPortList(self):
533
    """Returns a copy of the current port list.
534

535
    """
536
    return self._config_data.cluster.tcpudp_port_pool.copy()
537

    
538
  @locking.ssynchronized(_config_lock)
539
  def AllocatePort(self):
540
    """Allocate a port.
541

542
    The port will be taken from the available port pool or from the
543
    default port range (and in this case we increase
544
    highest_used_port).
545

546
    """
547
    # If there are TCP/IP ports configured, we use them first.
548
    if self._config_data.cluster.tcpudp_port_pool:
549
      port = self._config_data.cluster.tcpudp_port_pool.pop()
550
    else:
551
      port = self._config_data.cluster.highest_used_port + 1
552
      if port >= constants.LAST_DRBD_PORT:
553
        raise errors.ConfigurationError("The highest used port is greater"
554
                                        " than %s. Aborting." %
555
                                        constants.LAST_DRBD_PORT)
556
      self._config_data.cluster.highest_used_port = port
557

    
558
    self._WriteConfig()
559
    return port
560

    
561
  def _UnlockedComputeDRBDMap(self):
562
    """Compute the used DRBD minor/nodes.
563

564
    @rtype: (dict, list)
565
    @return: dictionary of node_name: dict of minor: instance_name;
566
        the returned dict will have all the nodes in it (even if with
567
        an empty list), and a list of duplicates; if the duplicates
568
        list is not empty, the configuration is corrupted and its caller
569
        should raise an exception
570

571
    """
572
    def _AppendUsedPorts(instance_name, disk, used):
573
      duplicates = []
574
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
575
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
576
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
577
          assert node in used, ("Node '%s' of instance '%s' not found"
578
                                " in node list" % (node, instance_name))
579
          if port in used[node]:
580
            duplicates.append((node, port, instance_name, used[node][port]))
581
          else:
582
            used[node][port] = instance_name
583
      if disk.children:
584
        for child in disk.children:
585
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
586
      return duplicates
587

    
588
    duplicates = []
589
    my_dict = dict((node, {}) for node in self._config_data.nodes)
590
    for instance in self._config_data.instances.itervalues():
591
      for disk in instance.disks:
592
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
593
    for (node, minor), instance in self._temporary_drbds.iteritems():
594
      if minor in my_dict[node] and my_dict[node][minor] != instance:
595
        duplicates.append((node, minor, instance, my_dict[node][minor]))
596
      else:
597
        my_dict[node][minor] = instance
598
    return my_dict, duplicates
599

    
600
  @locking.ssynchronized(_config_lock)
601
  def ComputeDRBDMap(self):
602
    """Compute the used DRBD minor/nodes.
603

604
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
605

606
    @return: dictionary of node_name: dict of minor: instance_name;
607
        the returned dict will have all the nodes in it (even if with
608
        an empty list).
609

610
    """
611
    d_map, duplicates = self._UnlockedComputeDRBDMap()
612
    if duplicates:
613
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
614
                                      str(duplicates))
615
    return d_map
616

    
617
  @locking.ssynchronized(_config_lock)
618
  def AllocateDRBDMinor(self, nodes, instance):
619
    """Allocate a drbd minor.
620

621
    The free minor will be automatically computed from the existing
622
    devices. A node can be given multiple times in order to allocate
623
    multiple minors. The result is the list of minors, in the same
624
    order as the passed nodes.
625

626
    @type instance: string
627
    @param instance: the instance for which we allocate minors
628

629
    """
630
    assert isinstance(instance, basestring), \
631
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
632

    
633
    d_map, duplicates = self._UnlockedComputeDRBDMap()
634
    if duplicates:
635
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
636
                                      str(duplicates))
637
    result = []
638
    for nname in nodes:
639
      ndata = d_map[nname]
640
      if not ndata:
641
        # no minors used, we can start at 0
642
        result.append(0)
643
        ndata[0] = instance
644
        self._temporary_drbds[(nname, 0)] = instance
645
        continue
646
      keys = ndata.keys()
647
      keys.sort()
648
      ffree = utils.FirstFree(keys)
649
      if ffree is None:
650
        # return the next minor
651
        # TODO: implement high-limit check
652
        minor = keys[-1] + 1
653
      else:
654
        minor = ffree
655
      # double-check minor against current instances
656
      assert minor not in d_map[nname], \
657
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
658
              " already allocated to instance %s" %
659
              (minor, nname, d_map[nname][minor]))
660
      ndata[minor] = instance
661
      # double-check minor against reservation
662
      r_key = (nname, minor)
663
      assert r_key not in self._temporary_drbds, \
664
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
665
              " reserved for instance %s" %
666
              (minor, nname, self._temporary_drbds[r_key]))
667
      self._temporary_drbds[r_key] = instance
668
      result.append(minor)
669
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
670
                  nodes, result)
671
    return result
672

    
673
  def _UnlockedReleaseDRBDMinors(self, instance):
674
    """Release temporary drbd minors allocated for a given instance.
675

676
    @type instance: string
677
    @param instance: the instance for which temporary minors should be
678
                     released
679

680
    """
681
    assert isinstance(instance, basestring), \
682
           "Invalid argument passed to ReleaseDRBDMinors"
683
    for key, name in self._temporary_drbds.items():
684
      if name == instance:
685
        del self._temporary_drbds[key]
686

    
687
  @locking.ssynchronized(_config_lock)
688
  def ReleaseDRBDMinors(self, instance):
689
    """Release temporary drbd minors allocated for a given instance.
690

691
    This should be called on the error paths, on the success paths
692
    it's automatically called by the ConfigWriter add and update
693
    functions.
694

695
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
696

697
    @type instance: string
698
    @param instance: the instance for which temporary minors should be
699
                     released
700

701
    """
702
    self._UnlockedReleaseDRBDMinors(instance)
703

    
704
  @locking.ssynchronized(_config_lock, shared=1)
705
  def GetConfigVersion(self):
706
    """Get the configuration version.
707

708
    @return: Config version
709

710
    """
711
    return self._config_data.version
712

    
713
  @locking.ssynchronized(_config_lock, shared=1)
714
  def GetClusterName(self):
715
    """Get cluster name.
716

717
    @return: Cluster name
718

719
    """
720
    return self._config_data.cluster.cluster_name
721

    
722
  @locking.ssynchronized(_config_lock, shared=1)
723
  def GetMasterNode(self):
724
    """Get the hostname of the master node for this cluster.
725

726
    @return: Master hostname
727

728
    """
729
    return self._config_data.cluster.master_node
730

    
731
  @locking.ssynchronized(_config_lock, shared=1)
732
  def GetMasterIP(self):
733
    """Get the IP of the master node for this cluster.
734

735
    @return: Master IP
736

737
    """
738
    return self._config_data.cluster.master_ip
739

    
740
  @locking.ssynchronized(_config_lock, shared=1)
741
  def GetMasterNetdev(self):
742
    """Get the master network device for this cluster.
743

744
    """
745
    return self._config_data.cluster.master_netdev
746

    
747
  @locking.ssynchronized(_config_lock, shared=1)
748
  def GetFileStorageDir(self):
749
    """Get the file storage dir for this cluster.
750

751
    """
752
    return self._config_data.cluster.file_storage_dir
753

    
754
  @locking.ssynchronized(_config_lock, shared=1)
755
  def GetHypervisorType(self):
756
    """Get the hypervisor type for this cluster.
757

758
    """
759
    return self._config_data.cluster.enabled_hypervisors[0]
760

    
761
  @locking.ssynchronized(_config_lock, shared=1)
762
  def GetHostKey(self):
763
    """Return the rsa hostkey from the config.
764

765
    @rtype: string
766
    @return: the rsa hostkey
767

768
    """
769
    return self._config_data.cluster.rsahostkeypub
770

    
771
  @locking.ssynchronized(_config_lock)
772
  def AddInstance(self, instance, ec_id):
773
    """Add an instance to the config.
774

775
    This should be used after creating a new instance.
776

777
    @type instance: L{objects.Instance}
778
    @param instance: the instance object
779

780
    """
781
    if not isinstance(instance, objects.Instance):
782
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
783

    
784
    if instance.disk_template != constants.DT_DISKLESS:
785
      all_lvs = instance.MapLVsByNode()
786
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
787

    
788
    all_macs = self._AllMACs()
789
    for nic in instance.nics:
790
      if nic.mac in all_macs:
791
        raise errors.ConfigurationError("Cannot add instance %s:"
792
                                        " MAC address '%s' already in use." %
793
                                        (instance.name, nic.mac))
794

    
795
    self._EnsureUUID(instance, ec_id)
796

    
797
    instance.serial_no = 1
798
    instance.ctime = instance.mtime = time.time()
799
    self._config_data.instances[instance.name] = instance
800
    self._config_data.cluster.serial_no += 1
801
    self._UnlockedReleaseDRBDMinors(instance.name)
802
    for nic in instance.nics:
803
      self._temporary_macs.discard(nic.mac)
804
    self._WriteConfig()
805

    
806
  def _EnsureUUID(self, item, ec_id):
807
    """Ensures a given object has a valid UUID.
808

809
    @param item: the instance or node to be checked
810
    @param ec_id: the execution context id for the uuid reservation
811

812
    """
813
    if not item.uuid:
814
      item.uuid = self._GenerateUniqueID(ec_id)
815
    elif item.uuid in self._AllIDs(temporary=True):
816
      raise errors.ConfigurationError("Cannot add '%s': UUID already in use" %
817
                                      (item.name, item.uuid))
818

    
819
  def _SetInstanceStatus(self, instance_name, status):
820
    """Set the instance's status to a given value.
821

822
    """
823
    assert isinstance(status, bool), \
824
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
825

    
826
    if instance_name not in self._config_data.instances:
827
      raise errors.ConfigurationError("Unknown instance '%s'" %
828
                                      instance_name)
829
    instance = self._config_data.instances[instance_name]
830
    if instance.admin_up != status:
831
      instance.admin_up = status
832
      instance.serial_no += 1
833
      instance.mtime = time.time()
834
      self._WriteConfig()
835

    
836
  @locking.ssynchronized(_config_lock)
837
  def MarkInstanceUp(self, instance_name):
838
    """Mark the instance status to up in the config.
839

840
    """
841
    self._SetInstanceStatus(instance_name, True)
842

    
843
  @locking.ssynchronized(_config_lock)
844
  def RemoveInstance(self, instance_name):
845
    """Remove the instance from the configuration.
846

847
    """
848
    if instance_name not in self._config_data.instances:
849
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
850
    del self._config_data.instances[instance_name]
851
    self._config_data.cluster.serial_no += 1
852
    self._WriteConfig()
853

    
854
  @locking.ssynchronized(_config_lock)
855
  def RenameInstance(self, old_name, new_name):
856
    """Rename an instance.
857

858
    This needs to be done in ConfigWriter and not by RemoveInstance
859
    combined with AddInstance as only we can guarantee an atomic
860
    rename.
861

862
    """
863
    if old_name not in self._config_data.instances:
864
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
865
    inst = self._config_data.instances[old_name]
866
    del self._config_data.instances[old_name]
867
    inst.name = new_name
868

    
869
    for disk in inst.disks:
870
      if disk.dev_type == constants.LD_FILE:
871
        # rename the file paths in logical and physical id
872
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
873
        disk.physical_id = disk.logical_id = (disk.logical_id[0],
874
                                              os.path.join(file_storage_dir,
875
                                                           inst.name,
876
                                                           disk.iv_name))
877

    
878
    self._config_data.instances[inst.name] = inst
879
    self._WriteConfig()
880

    
881
  @locking.ssynchronized(_config_lock)
882
  def MarkInstanceDown(self, instance_name):
883
    """Mark the status of an instance to down in the configuration.
884

885
    """
886
    self._SetInstanceStatus(instance_name, False)
887

    
888
  def _UnlockedGetInstanceList(self):
889
    """Get the list of instances.
890

891
    This function is for internal use, when the config lock is already held.
892

893
    """
894
    return self._config_data.instances.keys()
895

    
896
  @locking.ssynchronized(_config_lock, shared=1)
897
  def GetInstanceList(self):
898
    """Get the list of instances.
899

900
    @return: array of instances, ex. ['instance2.example.com',
901
        'instance1.example.com']
902

903
    """
904
    return self._UnlockedGetInstanceList()
905

    
906
  @locking.ssynchronized(_config_lock, shared=1)
907
  def ExpandInstanceName(self, short_name):
908
    """Attempt to expand an incomplete instance name.
909

910
    """
911
    return utils.MatchNameComponent(short_name,
912
                                    self._config_data.instances.keys(),
913
                                    case_sensitive=False)
914

    
915
  def _UnlockedGetInstanceInfo(self, instance_name):
916
    """Returns information about an instance.
917

918
    This function is for internal use, when the config lock is already held.
919

920
    """
921
    if instance_name not in self._config_data.instances:
922
      return None
923

    
924
    return self._config_data.instances[instance_name]
925

    
926
  @locking.ssynchronized(_config_lock, shared=1)
927
  def GetInstanceInfo(self, instance_name):
928
    """Returns information about an instance.
929

930
    It takes the information from the configuration file. Other information of
931
    an instance are taken from the live systems.
932

933
    @param instance_name: name of the instance, e.g.
934
        I{instance1.example.com}
935

936
    @rtype: L{objects.Instance}
937
    @return: the instance object
938

939
    """
940
    return self._UnlockedGetInstanceInfo(instance_name)
941

    
942
  @locking.ssynchronized(_config_lock, shared=1)
943
  def GetAllInstancesInfo(self):
944
    """Get the configuration of all instances.
945

946
    @rtype: dict
947
    @return: dict of (instance, instance_info), where instance_info is what
948
              would GetInstanceInfo return for the node
949

950
    """
951
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
952
                    for instance in self._UnlockedGetInstanceList()])
953
    return my_dict
954

    
955
  @locking.ssynchronized(_config_lock)
956
  def AddNode(self, node, ec_id):
957
    """Add a node to the configuration.
958

959
    @type node: L{objects.Node}
960
    @param node: a Node instance
961

962
    """
963
    logging.info("Adding node %s to configuration", node.name)
964

    
965
    self._EnsureUUID(node, ec_id)
966

    
967
    node.serial_no = 1
968
    node.ctime = node.mtime = time.time()
969
    self._config_data.nodes[node.name] = node
970
    self._config_data.cluster.serial_no += 1
971
    self._WriteConfig()
972

    
973
  @locking.ssynchronized(_config_lock)
974
  def RemoveNode(self, node_name):
975
    """Remove a node from the configuration.
976

977
    """
978
    logging.info("Removing node %s from configuration", node_name)
979

    
980
    if node_name not in self._config_data.nodes:
981
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
982

    
983
    del self._config_data.nodes[node_name]
984
    self._config_data.cluster.serial_no += 1
985
    self._WriteConfig()
986

    
987
  @locking.ssynchronized(_config_lock, shared=1)
988
  def ExpandNodeName(self, short_name):
989
    """Attempt to expand an incomplete instance name.
990

991
    """
992
    return utils.MatchNameComponent(short_name,
993
                                    self._config_data.nodes.keys(),
994
                                    case_sensitive=False)
995

    
996
  def _UnlockedGetNodeInfo(self, node_name):
997
    """Get the configuration of a node, as stored in the config.
998

999
    This function is for internal use, when the config lock is already
1000
    held.
1001

1002
    @param node_name: the node name, e.g. I{node1.example.com}
1003

1004
    @rtype: L{objects.Node}
1005
    @return: the node object
1006

1007
    """
1008
    if node_name not in self._config_data.nodes:
1009
      return None
1010

    
1011
    return self._config_data.nodes[node_name]
1012

    
1013

    
1014
  @locking.ssynchronized(_config_lock, shared=1)
1015
  def GetNodeInfo(self, node_name):
1016
    """Get the configuration of a node, as stored in the config.
1017

1018
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1019

1020
    @param node_name: the node name, e.g. I{node1.example.com}
1021

1022
    @rtype: L{objects.Node}
1023
    @return: the node object
1024

1025
    """
1026
    return self._UnlockedGetNodeInfo(node_name)
1027

    
1028
  def _UnlockedGetNodeList(self):
1029
    """Return the list of nodes which are in the configuration.
1030

1031
    This function is for internal use, when the config lock is already
1032
    held.
1033

1034
    @rtype: list
1035

1036
    """
1037
    return self._config_data.nodes.keys()
1038

    
1039

    
1040
  @locking.ssynchronized(_config_lock, shared=1)
1041
  def GetNodeList(self):
1042
    """Return the list of nodes which are in the configuration.
1043

1044
    """
1045
    return self._UnlockedGetNodeList()
1046

    
1047
  @locking.ssynchronized(_config_lock, shared=1)
1048
  def GetOnlineNodeList(self):
1049
    """Return the list of nodes which are online.
1050

1051
    """
1052
    all_nodes = [self._UnlockedGetNodeInfo(node)
1053
                 for node in self._UnlockedGetNodeList()]
1054
    return [node.name for node in all_nodes if not node.offline]
1055

    
1056
  @locking.ssynchronized(_config_lock, shared=1)
1057
  def GetAllNodesInfo(self):
1058
    """Get the configuration of all nodes.
1059

1060
    @rtype: dict
1061
    @return: dict of (node, node_info), where node_info is what
1062
              would GetNodeInfo return for the node
1063

1064
    """
1065
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
1066
                    for node in self._UnlockedGetNodeList()])
1067
    return my_dict
1068

    
1069
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1070
    """Get the number of current and maximum desired and possible candidates.
1071

1072
    @type exceptions: list
1073
    @param exceptions: if passed, list of nodes that should be ignored
1074
    @rtype: tuple
1075
    @return: tuple of (current, desired and possible, possible)
1076

1077
    """
1078
    mc_now = mc_should = mc_max = 0
1079
    for node in self._config_data.nodes.values():
1080
      if exceptions and node.name in exceptions:
1081
        continue
1082
      if not (node.offline or node.drained):
1083
        mc_max += 1
1084
      if node.master_candidate:
1085
        mc_now += 1
1086
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1087
    return (mc_now, mc_should, mc_max)
1088

    
1089
  @locking.ssynchronized(_config_lock, shared=1)
1090
  def GetMasterCandidateStats(self, exceptions=None):
1091
    """Get the number of current and maximum possible candidates.
1092

1093
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1094

1095
    @type exceptions: list
1096
    @param exceptions: if passed, list of nodes that should be ignored
1097
    @rtype: tuple
1098
    @return: tuple of (current, max)
1099

1100
    """
1101
    return self._UnlockedGetMasterCandidateStats(exceptions)
1102

    
1103
  @locking.ssynchronized(_config_lock)
1104
  def MaintainCandidatePool(self, exceptions):
1105
    """Try to grow the candidate pool to the desired size.
1106

1107
    @type exceptions: list
1108
    @param exceptions: if passed, list of nodes that should be ignored
1109
    @rtype: list
1110
    @return: list with the adjusted nodes (L{objects.Node} instances)
1111

1112
    """
1113
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1114
    mod_list = []
1115
    if mc_now < mc_max:
1116
      node_list = self._config_data.nodes.keys()
1117
      random.shuffle(node_list)
1118
      for name in node_list:
1119
        if mc_now >= mc_max:
1120
          break
1121
        node = self._config_data.nodes[name]
1122
        if (node.master_candidate or node.offline or node.drained or
1123
            node.name in exceptions):
1124
          continue
1125
        mod_list.append(node)
1126
        node.master_candidate = True
1127
        node.serial_no += 1
1128
        mc_now += 1
1129
      if mc_now != mc_max:
1130
        # this should not happen
1131
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1132
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1133
      if mod_list:
1134
        self._config_data.cluster.serial_no += 1
1135
        self._WriteConfig()
1136

    
1137
    return mod_list
1138

    
1139
  def _BumpSerialNo(self):
1140
    """Bump up the serial number of the config.
1141

1142
    """
1143
    self._config_data.serial_no += 1
1144
    self._config_data.mtime = time.time()
1145

    
1146
  def _AllUUIDObjects(self):
1147
    """Returns all objects with uuid attributes.
1148

1149
    """
1150
    return (self._config_data.instances.values() +
1151
            self._config_data.nodes.values() +
1152
            [self._config_data.cluster])
1153

    
1154
  def _OpenConfig(self):
1155
    """Read the config data from disk.
1156

1157
    """
1158
    raw_data = utils.ReadFile(self._cfg_file)
1159

    
1160
    try:
1161
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1162
    except Exception, err:
1163
      raise errors.ConfigurationError(err)
1164

    
1165
    # Make sure the configuration has the right version
1166
    _ValidateConfig(data)
1167

    
1168
    if (not hasattr(data, 'cluster') or
1169
        not hasattr(data.cluster, 'rsahostkeypub')):
1170
      raise errors.ConfigurationError("Incomplete configuration"
1171
                                      " (missing cluster.rsahostkeypub)")
1172

    
1173
    # Upgrade configuration if needed
1174
    data.UpgradeConfig()
1175

    
1176
    self._config_data = data
1177
    # reset the last serial as -1 so that the next write will cause
1178
    # ssconf update
1179
    self._last_cluster_serial = -1
1180

    
1181
    # And finally run our (custom) config upgrade sequence
1182
    self._UpgradeConfig()
1183

    
1184
  def _UpgradeConfig(self):
1185
    """Run upgrade steps that cannot be done purely in the objects.
1186

1187
    This is because some data elements need uniqueness across the
1188
    whole configuration, etc.
1189

1190
    @warning: this function will call L{_WriteConfig()}, so it needs
1191
        to either be called with the lock held or from a safe place
1192
        (the constructor)
1193

1194
    """
1195
    modified = False
1196
    for item in self._AllUUIDObjects():
1197
      if item.uuid is None:
1198
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1199
        modified = True
1200
    if modified:
1201
      self._WriteConfig()
1202
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
1203
      # only called at config init time, without the lock held
1204
      self.DropECReservations(_UPGRADE_CONFIG_JID)
1205

    
1206

    
1207
  def _DistributeConfig(self, feedback_fn):
1208
    """Distribute the configuration to the other nodes.
1209

1210
    Currently, this only copies the configuration file. In the future,
1211
    it could be used to encapsulate the 2/3-phase update mechanism.
1212

1213
    """
1214
    if self._offline:
1215
      return True
1216

    
1217
    bad = False
1218

    
1219
    node_list = []
1220
    addr_list = []
1221
    myhostname = self._my_hostname
1222
    # we can skip checking whether _UnlockedGetNodeInfo returns None
1223
    # since the node list comes from _UnlocketGetNodeList, and we are
1224
    # called with the lock held, so no modifications should take place
1225
    # in between
1226
    for node_name in self._UnlockedGetNodeList():
1227
      if node_name == myhostname:
1228
        continue
1229
      node_info = self._UnlockedGetNodeInfo(node_name)
1230
      if not node_info.master_candidate:
1231
        continue
1232
      node_list.append(node_info.name)
1233
      addr_list.append(node_info.primary_ip)
1234

    
1235
    result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
1236
                                            address_list=addr_list)
1237
    for to_node, to_result in result.items():
1238
      msg = to_result.fail_msg
1239
      if msg:
1240
        msg = ("Copy of file %s to node %s failed: %s" %
1241
               (self._cfg_file, to_node, msg))
1242
        logging.error(msg)
1243

    
1244
        if feedback_fn:
1245
          feedback_fn(msg)
1246

    
1247
        bad = True
1248

    
1249
    return not bad
1250

    
1251
  def _WriteConfig(self, destination=None, feedback_fn=None):
1252
    """Write the configuration data to persistent storage.
1253

1254
    """
1255
    assert feedback_fn is None or callable(feedback_fn)
1256

    
1257
    # Warn on config errors, but don't abort the save - the
1258
    # configuration has already been modified, and we can't revert;
1259
    # the best we can do is to warn the user and save as is, leaving
1260
    # recovery to the user
1261
    config_errors = self._UnlockedVerifyConfig()
1262
    if config_errors:
1263
      errmsg = ("Configuration data is not consistent: %s" %
1264
                (", ".join(config_errors)))
1265
      logging.critical(errmsg)
1266
      if feedback_fn:
1267
        feedback_fn(errmsg)
1268

    
1269
    if destination is None:
1270
      destination = self._cfg_file
1271
    self._BumpSerialNo()
1272
    txt = serializer.Dump(self._config_data.ToDict())
1273

    
1274
    utils.WriteFile(destination, data=txt)
1275

    
1276
    self.write_count += 1
1277

    
1278
    # and redistribute the config file to master candidates
1279
    self._DistributeConfig(feedback_fn)
1280

    
1281
    # Write ssconf files on all nodes (including locally)
1282
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
1283
      if not self._offline:
1284
        result = rpc.RpcRunner.call_write_ssconf_files(
1285
          self._UnlockedGetNodeList(),
1286
          self._UnlockedGetSsconfValues())
1287

    
1288
        for nname, nresu in result.items():
1289
          msg = nresu.fail_msg
1290
          if msg:
1291
            errmsg = ("Error while uploading ssconf files to"
1292
                      " node %s: %s" % (nname, msg))
1293
            logging.warning(errmsg)
1294

    
1295
            if feedback_fn:
1296
              feedback_fn(errmsg)
1297

    
1298
      self._last_cluster_serial = self._config_data.cluster.serial_no
1299

    
1300
  def _UnlockedGetSsconfValues(self):
1301
    """Return the values needed by ssconf.
1302

1303
    @rtype: dict
1304
    @return: a dictionary with keys the ssconf names and values their
1305
        associated value
1306

1307
    """
1308
    fn = "\n".join
1309
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1310
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
1311
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1312
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
1313
                    for ninfo in node_info]
1314
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
1315
                    for ninfo in node_info]
1316

    
1317
    instance_data = fn(instance_names)
1318
    off_data = fn(node.name for node in node_info if node.offline)
1319
    on_data = fn(node.name for node in node_info if not node.offline)
1320
    mc_data = fn(node.name for node in node_info if node.master_candidate)
1321
    mc_ips_data = fn(node.primary_ip for node in node_info
1322
                     if node.master_candidate)
1323
    node_data = fn(node_names)
1324
    node_pri_ips_data = fn(node_pri_ips)
1325
    node_snd_ips_data = fn(node_snd_ips)
1326

    
1327
    cluster = self._config_data.cluster
1328
    cluster_tags = fn(cluster.GetTags())
1329
    return {
1330
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
1331
      constants.SS_CLUSTER_TAGS: cluster_tags,
1332
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1333
      constants.SS_MASTER_CANDIDATES: mc_data,
1334
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
1335
      constants.SS_MASTER_IP: cluster.master_ip,
1336
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
1337
      constants.SS_MASTER_NODE: cluster.master_node,
1338
      constants.SS_NODE_LIST: node_data,
1339
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
1340
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
1341
      constants.SS_OFFLINE_NODES: off_data,
1342
      constants.SS_ONLINE_NODES: on_data,
1343
      constants.SS_INSTANCE_LIST: instance_data,
1344
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1345
      }
1346

    
1347
  @locking.ssynchronized(_config_lock, shared=1)
1348
  def GetVGName(self):
1349
    """Return the volume group name.
1350

1351
    """
1352
    return self._config_data.cluster.volume_group_name
1353

    
1354
  @locking.ssynchronized(_config_lock)
1355
  def SetVGName(self, vg_name):
1356
    """Set the volume group name.
1357

1358
    """
1359
    self._config_data.cluster.volume_group_name = vg_name
1360
    self._config_data.cluster.serial_no += 1
1361
    self._WriteConfig()
1362

    
1363
  @locking.ssynchronized(_config_lock, shared=1)
1364
  def GetMACPrefix(self):
1365
    """Return the mac prefix.
1366

1367
    """
1368
    return self._config_data.cluster.mac_prefix
1369

    
1370
  @locking.ssynchronized(_config_lock, shared=1)
1371
  def GetClusterInfo(self):
1372
    """Returns information about the cluster
1373

1374
    @rtype: L{objects.Cluster}
1375
    @return: the cluster object
1376

1377
    """
1378
    return self._config_data.cluster
1379

    
1380
  @locking.ssynchronized(_config_lock)
1381
  def Update(self, target, feedback_fn):
1382
    """Notify function to be called after updates.
1383

1384
    This function must be called when an object (as returned by
1385
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
1386
    caller wants the modifications saved to the backing store. Note
1387
    that all modified objects will be saved, but the target argument
1388
    is the one the caller wants to ensure that it's saved.
1389

1390
    @param target: an instance of either L{objects.Cluster},
1391
        L{objects.Node} or L{objects.Instance} which is existing in
1392
        the cluster
1393
    @param feedback_fn: Callable feedback function
1394

1395
    """
1396
    if self._config_data is None:
1397
      raise errors.ProgrammerError("Configuration file not read,"
1398
                                   " cannot save.")
1399
    update_serial = False
1400
    if isinstance(target, objects.Cluster):
1401
      test = target == self._config_data.cluster
1402
    elif isinstance(target, objects.Node):
1403
      test = target in self._config_data.nodes.values()
1404
      update_serial = True
1405
    elif isinstance(target, objects.Instance):
1406
      test = target in self._config_data.instances.values()
1407
    else:
1408
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
1409
                                   " ConfigWriter.Update" % type(target))
1410
    if not test:
1411
      raise errors.ConfigurationError("Configuration updated since object"
1412
                                      " has been read or unknown object")
1413
    target.serial_no += 1
1414
    target.mtime = now = time.time()
1415

    
1416
    if update_serial:
1417
      # for node updates, we need to increase the cluster serial too
1418
      self._config_data.cluster.serial_no += 1
1419
      self._config_data.cluster.mtime = now
1420

    
1421
    if isinstance(target, objects.Instance):
1422
      self._UnlockedReleaseDRBDMinors(target.name)
1423
      for nic in target.nics:
1424
        self._temporary_macs.discard(nic.mac)
1425

    
1426
    self._WriteConfig(feedback_fn=feedback_fn)
1427

    
1428
  @locking.ssynchronized(_config_lock)
1429
  def DropECReservations(self, ec_id):
1430
    """Drop per-execution-context reservations
1431

1432
    """
1433
    self._temporary_ids.DropECReservations(ec_id)
1434