Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 36b66e6e

History | View | Annotate | Download (45.7 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 = TemporaryReservationManager()
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
  def _GenerateOneMAC(self):
158
    """Generate one mac address
159

160
    """
161
    prefix = self._config_data.cluster.mac_prefix
162
    byte1 = random.randrange(0, 256)
163
    byte2 = random.randrange(0, 256)
164
    byte3 = random.randrange(0, 256)
165
    mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
166
    return mac
167

    
168
  @locking.ssynchronized(_config_lock, shared=1)
169
  def GenerateMAC(self, ec_id):
170
    """Generate a MAC for an instance.
171

172
    This should check the current instances for duplicates.
173

174
    """
175
    existing = self._AllMACs()
176
    return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
177

    
178
  @locking.ssynchronized(_config_lock, shared=1)
179
  def ReserveMAC(self, mac, ec_id):
180
    """Reserve a MAC for an instance.
181

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

185
    """
186
    all_macs = self._AllMACs()
187
    if mac in all_macs:
188
      raise errors.ReservationError("mac already in use")
189
    else:
190
      self._temporary_macs.Reserve(mac, ec_id)
191

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

196
    This checks the current disks for duplicates.
197

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
276
    return result
277

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

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

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

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

    
298
    return result
299

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
559
    self._WriteConfig()
560
    return port
561

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

709
    @return: Config version
710

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

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

718
    @return: Cluster name
719

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

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

727
    @return: Master hostname
728

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

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

736
    @return: Master IP
737

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
796
    self._EnsureUUID(instance, ec_id)
797

    
798
    instance.serial_no = 1
799
    instance.ctime = instance.mtime = time.time()
800
    self._config_data.instances[instance.name] = instance
801
    self._config_data.cluster.serial_no += 1
802
    self._UnlockedReleaseDRBDMinors(instance.name)
803
    self._WriteConfig()
804

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
923
    return self._config_data.instances[instance_name]
924

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

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

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

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

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

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

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

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

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

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

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

    
964
    self._EnsureUUID(node, ec_id)
965

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

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

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

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

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

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

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

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

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

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

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

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

    
1010
    return self._config_data.nodes[node_name]
1011

    
1012

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

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

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

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

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

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

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

1033
    @rtype: list
1034

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

    
1038

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1136
    return mod_list
1137

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1205

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

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

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

    
1216
    bad = False
1217

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

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

    
1243
        if feedback_fn:
1244
          feedback_fn(msg)
1245

    
1246
        bad = True
1247

    
1248
    return not bad
1249

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

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

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

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

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

    
1275
    self.write_count += 1
1276

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

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

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

    
1294
            if feedback_fn:
1295
              feedback_fn(errmsg)
1296

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1420
    if isinstance(target, objects.Instance):
1421
      self._UnlockedReleaseDRBDMinors(target.name)
1422

    
1423
    self._WriteConfig(feedback_fn=feedback_fn)
1424

    
1425
  @locking.ssynchronized(_config_lock)
1426
  def DropECReservations(self, ec_id):
1427
    """Drop per-execution-context reservations
1428

1429
    """
1430
    self._temporary_ids.DropECReservations(ec_id)
1431
    self._temporary_macs.DropECReservations(ec_id)
1432