Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 73064714

History | View | Annotate | Download (44.3 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

    
51
def _ValidateConfig(data):
52
  """Verifies that a configuration objects looks valid.
53

54
  This only verifies the version of the configuration.
55

56
  @raise errors.ConfigurationError: if the version differs from what
57
      we expect
58

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

    
66

    
67
class ConfigWriter:
68
  """The interface to the cluster configuration.
69

70
  """
71
  def __init__(self, cfg_file=None, offline=False):
72
    self.write_count = 0
73
    self._lock = _config_lock
74
    self._config_data = None
75
    self._offline = offline
76
    if cfg_file is None:
77
      self._cfg_file = constants.CLUSTER_CONF_FILE
78
    else:
79
      self._cfg_file = cfg_file
80
    self._temporary_ids = set()
81
    self._temporary_drbds = {}
82
    self._temporary_macs = set()
83
    # Note: in order to prevent errors when resolving our name in
84
    # _DistributeConfig, we compute it here once and reuse it; it's
85
    # better to raise an error before starting to modify the config
86
    # file than after it was modified
87
    self._my_hostname = utils.HostInfo().name
88
    self._last_cluster_serial = -1
89
    self._OpenConfig()
90

    
91
  # this method needs to be static, so that we can call it on the class
92
  @staticmethod
93
  def IsCluster():
94
    """Check if the cluster is configured.
95

96
    """
97
    return os.path.exists(constants.CLUSTER_CONF_FILE)
98

    
99
  @locking.ssynchronized(_config_lock, shared=1)
100
  def GenerateMAC(self):
101
    """Generate a MAC for an instance.
102

103
    This should check the current instances for duplicates.
104

105
    """
106
    prefix = self._config_data.cluster.mac_prefix
107
    all_macs = self._AllMACs()
108
    retries = 64
109
    while retries > 0:
110
      byte1 = random.randrange(0, 256)
111
      byte2 = random.randrange(0, 256)
112
      byte3 = random.randrange(0, 256)
113
      mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
114
      if mac not in all_macs and mac not in self._temporary_macs:
115
        break
116
      retries -= 1
117
    else:
118
      raise errors.ConfigurationError("Can't generate unique MAC")
119
    self._temporary_macs.add(mac)
120
    return mac
121

    
122
  @locking.ssynchronized(_config_lock, shared=1)
123
  def IsMacInUse(self, mac):
124
    """Predicate: check if the specified MAC is in use in the Ganeti cluster.
125

126
    This only checks instances managed by this cluster, it does not
127
    check for potential collisions elsewhere.
128

129
    """
130
    all_macs = self._AllMACs()
131
    return mac in all_macs or mac in self._temporary_macs
132

    
133
  @locking.ssynchronized(_config_lock, shared=1)
134
  def GenerateDRBDSecret(self):
135
    """Generate a DRBD secret.
136

137
    This checks the current disks for duplicates.
138

139
    """
140
    all_secrets = self._AllDRBDSecrets()
141
    retries = 64
142
    while retries > 0:
143
      secret = utils.GenerateSecret()
144
      if secret not in all_secrets:
145
        break
146
      retries -= 1
147
    else:
148
      raise errors.ConfigurationError("Can't generate unique DRBD secret")
149
    return secret
150

    
151
  def _AllLVs(self):
152
    """Compute the list of all LVs.
153

154
    """
155
    lvnames = set()
156
    for instance in self._config_data.instances.values():
157
      node_data = instance.MapLVsByNode()
158
      for lv_list in node_data.values():
159
        lvnames.update(lv_list)
160
    return lvnames
161

    
162
  def _AllIDs(self, include_temporary):
163
    """Compute the list of all UUIDs and names we have.
164

165
    @type include_temporary: boolean
166
    @param include_temporary: whether to include the _temporary_ids set
167
    @rtype: set
168
    @return: a set of IDs
169

170
    """
171
    existing = set()
172
    if include_temporary:
173
      existing.update(self._temporary_ids)
174
    existing.update(self._AllLVs())
175
    existing.update(self._config_data.instances.keys())
176
    existing.update(self._config_data.nodes.keys())
177
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
178
    return existing
179

    
180
  def _GenerateUniqueID(self):
181
    """Generate an unique UUID.
182

183
    This checks the current node, instances and disk names for
184
    duplicates.
185

186
    @rtype: string
187
    @return: the unique id
188

189
    """
190
    existing = self._AllIDs(include_temporary=True)
191
    retries = 64
192
    while retries > 0:
193
      unique_id = utils.NewUUID()
194
      if unique_id not in existing and unique_id is not None:
195
        break
196
    else:
197
      raise errors.ConfigurationError("Not able generate an unique ID"
198
                                      " (last tried ID: %s" % unique_id)
199
    self._temporary_ids.add(unique_id)
200
    return unique_id
201

    
202
  @locking.ssynchronized(_config_lock, shared=1)
203
  def GenerateUniqueID(self):
204
    """Generate an unique ID.
205

206
    This is just a wrapper over the unlocked version.
207

208
    """
209
    return self._GenerateUniqueID()
210

    
211
  def _CleanupTemporaryIDs(self):
212
    """Cleanups the _temporary_ids structure.
213

214
    """
215
    existing = self._AllIDs(include_temporary=False)
216
    self._temporary_ids = self._temporary_ids - existing
217

    
218
  def _AllMACs(self):
219
    """Return all MACs present in the config.
220

221
    @rtype: list
222
    @return: the list of all MACs
223

224
    """
225
    result = []
226
    for instance in self._config_data.instances.values():
227
      for nic in instance.nics:
228
        result.append(nic.mac)
229

    
230
    return result
231

    
232
  def _AllDRBDSecrets(self):
233
    """Return all DRBD secrets present in the config.
234

235
    @rtype: list
236
    @return: the list of all DRBD secrets
237

238
    """
239
    def helper(disk, result):
240
      """Recursively gather secrets from this disk."""
241
      if disk.dev_type == constants.DT_DRBD8:
242
        result.append(disk.logical_id[5])
243
      if disk.children:
244
        for child in disk.children:
245
          helper(child, result)
246

    
247
    result = []
248
    for instance in self._config_data.instances.values():
249
      for disk in instance.disks:
250
        helper(disk, result)
251

    
252
    return result
253

    
254
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
255
    """Compute duplicate disk IDs
256

257
    @type disk: L{objects.Disk}
258
    @param disk: the disk at which to start searching
259
    @type l_ids: list
260
    @param l_ids: list of current logical ids
261
    @type p_ids: list
262
    @param p_ids: list of current physical ids
263
    @rtype: list
264
    @return: a list of error messages
265

266
    """
267
    result = []
268
    if disk.logical_id is not None:
269
      if disk.logical_id in l_ids:
270
        result.append("duplicate logical id %s" % str(disk.logical_id))
271
      else:
272
        l_ids.append(disk.logical_id)
273
    if disk.physical_id is not None:
274
      if disk.physical_id in p_ids:
275
        result.append("duplicate physical id %s" % str(disk.physical_id))
276
      else:
277
        p_ids.append(disk.physical_id)
278

    
279
    if disk.children:
280
      for child in disk.children:
281
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
282
    return result
283

    
284
  def _UnlockedVerifyConfig(self):
285
    """Verify function.
286

287
    @rtype: list
288
    @return: a list of error messages; a non-empty list signifies
289
        configuration errors
290

291
    """
292
    result = []
293
    seen_macs = []
294
    ports = {}
295
    data = self._config_data
296
    seen_lids = []
297
    seen_pids = []
298

    
299
    # global cluster checks
300
    if not data.cluster.enabled_hypervisors:
301
      result.append("enabled hypervisors list doesn't have any entries")
302
    invalid_hvs = set(data.cluster.enabled_hypervisors) - constants.HYPER_TYPES
303
    if invalid_hvs:
304
      result.append("enabled hypervisors contains invalid entries: %s" %
305
                    invalid_hvs)
306

    
307
    if data.cluster.master_node not in data.nodes:
308
      result.append("cluster has invalid primary node '%s'" %
309
                    data.cluster.master_node)
310

    
311
    # per-instance checks
312
    for instance_name in data.instances:
313
      instance = data.instances[instance_name]
314
      if instance.primary_node not in data.nodes:
315
        result.append("instance '%s' has invalid primary node '%s'" %
316
                      (instance_name, instance.primary_node))
317
      for snode in instance.secondary_nodes:
318
        if snode not in data.nodes:
319
          result.append("instance '%s' has invalid secondary node '%s'" %
320
                        (instance_name, snode))
321
      for idx, nic in enumerate(instance.nics):
322
        if nic.mac in seen_macs:
323
          result.append("instance '%s' has NIC %d mac %s duplicate" %
324
                        (instance_name, idx, nic.mac))
325
        else:
326
          seen_macs.append(nic.mac)
327

    
328
      # gather the drbd ports for duplicate checks
329
      for dsk in instance.disks:
330
        if dsk.dev_type in constants.LDS_DRBD:
331
          tcp_port = dsk.logical_id[2]
332
          if tcp_port not in ports:
333
            ports[tcp_port] = []
334
          ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
335
      # gather network port reservation
336
      net_port = getattr(instance, "network_port", None)
337
      if net_port is not None:
338
        if net_port not in ports:
339
          ports[net_port] = []
340
        ports[net_port].append((instance.name, "network port"))
341

    
342
      # instance disk verify
343
      for idx, disk in enumerate(instance.disks):
344
        result.extend(["instance '%s' disk %d error: %s" %
345
                       (instance.name, idx, msg) for msg in disk.Verify()])
346
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
347

    
348
    # cluster-wide pool of free ports
349
    for free_port in data.cluster.tcpudp_port_pool:
350
      if free_port not in ports:
351
        ports[free_port] = []
352
      ports[free_port].append(("cluster", "port marked as free"))
353

    
354
    # compute tcp/udp duplicate ports
355
    keys = ports.keys()
356
    keys.sort()
357
    for pnum in keys:
358
      pdata = ports[pnum]
359
      if len(pdata) > 1:
360
        txt = ", ".join(["%s/%s" % val for val in pdata])
361
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
362

    
363
    # highest used tcp port check
364
    if keys:
365
      if keys[-1] > data.cluster.highest_used_port:
366
        result.append("Highest used port mismatch, saved %s, computed %s" %
367
                      (data.cluster.highest_used_port, keys[-1]))
368

    
369
    if not data.nodes[data.cluster.master_node].master_candidate:
370
      result.append("Master node is not a master candidate")
371

    
372
    # master candidate checks
373
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
374
    if mc_now < mc_max:
375
      result.append("Not enough master candidates: actual %d, target %d" %
376
                    (mc_now, mc_max))
377

    
378
    # node checks
379
    for node in data.nodes.values():
380
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
381
        result.append("Node %s state is invalid: master_candidate=%s,"
382
                      " drain=%s, offline=%s" %
383
                      (node.name, node.master_candidate, node.drain,
384
                       node.offline))
385

    
386
    # drbd minors check
387
    d_map, duplicates = self._UnlockedComputeDRBDMap()
388
    for node, minor, instance_a, instance_b in duplicates:
389
      result.append("DRBD minor %d on node %s is assigned twice to instances"
390
                    " %s and %s" % (minor, node, instance_a, instance_b))
391

    
392
    # IP checks
393
    ips = { data.cluster.master_ip: ["cluster_ip"] }
394
    def _helper(ip, name):
395
      if ip in ips:
396
        ips[ip].append(name)
397
      else:
398
        ips[ip] = [name]
399

    
400
    for node in data.nodes.values():
401
      _helper(node.primary_ip, "node:%s/primary" % node.name)
402
      if node.secondary_ip != node.primary_ip:
403
        _helper(node.secondary_ip, "node:%s/secondary" % node.name)
404

    
405
    for ip, owners in ips.items():
406
      if len(owners) > 1:
407
        result.append("IP address %s is used by multiple owners: %s" %
408
                      (ip, ", ".join(owners)))
409
    return result
410

    
411
  @locking.ssynchronized(_config_lock, shared=1)
412
  def VerifyConfig(self):
413
    """Verify function.
414

415
    This is just a wrapper over L{_UnlockedVerifyConfig}.
416

417
    @rtype: list
418
    @return: a list of error messages; a non-empty list signifies
419
        configuration errors
420

421
    """
422
    return self._UnlockedVerifyConfig()
423

    
424
  def _UnlockedSetDiskID(self, disk, node_name):
425
    """Convert the unique ID to the ID needed on the target nodes.
426

427
    This is used only for drbd, which needs ip/port configuration.
428

429
    The routine descends down and updates its children also, because
430
    this helps when the only the top device is passed to the remote
431
    node.
432

433
    This function is for internal use, when the config lock is already held.
434

435
    """
436
    if disk.children:
437
      for child in disk.children:
438
        self._UnlockedSetDiskID(child, node_name)
439

    
440
    if disk.logical_id is None and disk.physical_id is not None:
441
      return
442
    if disk.dev_type == constants.LD_DRBD8:
443
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
444
      if node_name not in (pnode, snode):
445
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
446
                                        node_name)
447
      pnode_info = self._UnlockedGetNodeInfo(pnode)
448
      snode_info = self._UnlockedGetNodeInfo(snode)
449
      if pnode_info is None or snode_info is None:
450
        raise errors.ConfigurationError("Can't find primary or secondary node"
451
                                        " for %s" % str(disk))
452
      p_data = (pnode_info.secondary_ip, port)
453
      s_data = (snode_info.secondary_ip, port)
454
      if pnode == node_name:
455
        disk.physical_id = p_data + s_data + (pminor, secret)
456
      else: # it must be secondary, we tested above
457
        disk.physical_id = s_data + p_data + (sminor, secret)
458
    else:
459
      disk.physical_id = disk.logical_id
460
    return
461

    
462
  @locking.ssynchronized(_config_lock)
463
  def SetDiskID(self, disk, node_name):
464
    """Convert the unique ID to the ID needed on the target nodes.
465

466
    This is used only for drbd, which needs ip/port configuration.
467

468
    The routine descends down and updates its children also, because
469
    this helps when the only the top device is passed to the remote
470
    node.
471

472
    """
473
    return self._UnlockedSetDiskID(disk, node_name)
474

    
475
  @locking.ssynchronized(_config_lock)
476
  def AddTcpUdpPort(self, port):
477
    """Adds a new port to the available port pool.
478

479
    """
480
    if not isinstance(port, int):
481
      raise errors.ProgrammerError("Invalid type passed for port")
482

    
483
    self._config_data.cluster.tcpudp_port_pool.add(port)
484
    self._WriteConfig()
485

    
486
  @locking.ssynchronized(_config_lock, shared=1)
487
  def GetPortList(self):
488
    """Returns a copy of the current port list.
489

490
    """
491
    return self._config_data.cluster.tcpudp_port_pool.copy()
492

    
493
  @locking.ssynchronized(_config_lock)
494
  def AllocatePort(self):
495
    """Allocate a port.
496

497
    The port will be taken from the available port pool or from the
498
    default port range (and in this case we increase
499
    highest_used_port).
500

501
    """
502
    # If there are TCP/IP ports configured, we use them first.
503
    if self._config_data.cluster.tcpudp_port_pool:
504
      port = self._config_data.cluster.tcpudp_port_pool.pop()
505
    else:
506
      port = self._config_data.cluster.highest_used_port + 1
507
      if port >= constants.LAST_DRBD_PORT:
508
        raise errors.ConfigurationError("The highest used port is greater"
509
                                        " than %s. Aborting." %
510
                                        constants.LAST_DRBD_PORT)
511
      self._config_data.cluster.highest_used_port = port
512

    
513
    self._WriteConfig()
514
    return port
515

    
516
  def _UnlockedComputeDRBDMap(self):
517
    """Compute the used DRBD minor/nodes.
518

519
    @rtype: (dict, list)
520
    @return: dictionary of node_name: dict of minor: instance_name;
521
        the returned dict will have all the nodes in it (even if with
522
        an empty list), and a list of duplicates; if the duplicates
523
        list is not empty, the configuration is corrupted and its caller
524
        should raise an exception
525

526
    """
527
    def _AppendUsedPorts(instance_name, disk, used):
528
      duplicates = []
529
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
530
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
531
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
532
          assert node in used, ("Node '%s' of instance '%s' not found"
533
                                " in node list" % (node, instance_name))
534
          if port in used[node]:
535
            duplicates.append((node, port, instance_name, used[node][port]))
536
          else:
537
            used[node][port] = instance_name
538
      if disk.children:
539
        for child in disk.children:
540
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
541
      return duplicates
542

    
543
    duplicates = []
544
    my_dict = dict((node, {}) for node in self._config_data.nodes)
545
    for instance in self._config_data.instances.itervalues():
546
      for disk in instance.disks:
547
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
548
    for (node, minor), instance in self._temporary_drbds.iteritems():
549
      if minor in my_dict[node] and my_dict[node][minor] != instance:
550
        duplicates.append((node, minor, instance, my_dict[node][minor]))
551
      else:
552
        my_dict[node][minor] = instance
553
    return my_dict, duplicates
554

    
555
  @locking.ssynchronized(_config_lock)
556
  def ComputeDRBDMap(self):
557
    """Compute the used DRBD minor/nodes.
558

559
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
560

561
    @return: dictionary of node_name: dict of minor: instance_name;
562
        the returned dict will have all the nodes in it (even if with
563
        an empty list).
564

565
    """
566
    d_map, duplicates = self._UnlockedComputeDRBDMap()
567
    if duplicates:
568
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
569
                                      str(duplicates))
570
    return d_map
571

    
572
  @locking.ssynchronized(_config_lock)
573
  def AllocateDRBDMinor(self, nodes, instance):
574
    """Allocate a drbd minor.
575

576
    The free minor will be automatically computed from the existing
577
    devices. A node can be given multiple times in order to allocate
578
    multiple minors. The result is the list of minors, in the same
579
    order as the passed nodes.
580

581
    @type instance: string
582
    @param instance: the instance for which we allocate minors
583

584
    """
585
    assert isinstance(instance, basestring), \
586
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
587

    
588
    d_map, duplicates = self._UnlockedComputeDRBDMap()
589
    if duplicates:
590
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
591
                                      str(duplicates))
592
    result = []
593
    for nname in nodes:
594
      ndata = d_map[nname]
595
      if not ndata:
596
        # no minors used, we can start at 0
597
        result.append(0)
598
        ndata[0] = instance
599
        self._temporary_drbds[(nname, 0)] = instance
600
        continue
601
      keys = ndata.keys()
602
      keys.sort()
603
      ffree = utils.FirstFree(keys)
604
      if ffree is None:
605
        # return the next minor
606
        # TODO: implement high-limit check
607
        minor = keys[-1] + 1
608
      else:
609
        minor = ffree
610
      # double-check minor against current instances
611
      assert minor not in d_map[nname], \
612
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
613
              " already allocated to instance %s" %
614
              (minor, nname, d_map[nname][minor]))
615
      ndata[minor] = instance
616
      # double-check minor against reservation
617
      r_key = (nname, minor)
618
      assert r_key not in self._temporary_drbds, \
619
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
620
              " reserved for instance %s" %
621
              (minor, nname, self._temporary_drbds[r_key]))
622
      self._temporary_drbds[r_key] = instance
623
      result.append(minor)
624
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
625
                  nodes, result)
626
    return result
627

    
628
  def _UnlockedReleaseDRBDMinors(self, instance):
629
    """Release temporary drbd minors allocated for a given instance.
630

631
    @type instance: string
632
    @param instance: the instance for which temporary minors should be
633
                     released
634

635
    """
636
    assert isinstance(instance, basestring), \
637
           "Invalid argument passed to ReleaseDRBDMinors"
638
    for key, name in self._temporary_drbds.items():
639
      if name == instance:
640
        del self._temporary_drbds[key]
641

    
642
  @locking.ssynchronized(_config_lock)
643
  def ReleaseDRBDMinors(self, instance):
644
    """Release temporary drbd minors allocated for a given instance.
645

646
    This should be called on the error paths, on the success paths
647
    it's automatically called by the ConfigWriter add and update
648
    functions.
649

650
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
651

652
    @type instance: string
653
    @param instance: the instance for which temporary minors should be
654
                     released
655

656
    """
657
    self._UnlockedReleaseDRBDMinors(instance)
658

    
659
  @locking.ssynchronized(_config_lock, shared=1)
660
  def GetConfigVersion(self):
661
    """Get the configuration version.
662

663
    @return: Config version
664

665
    """
666
    return self._config_data.version
667

    
668
  @locking.ssynchronized(_config_lock, shared=1)
669
  def GetClusterName(self):
670
    """Get cluster name.
671

672
    @return: Cluster name
673

674
    """
675
    return self._config_data.cluster.cluster_name
676

    
677
  @locking.ssynchronized(_config_lock, shared=1)
678
  def GetMasterNode(self):
679
    """Get the hostname of the master node for this cluster.
680

681
    @return: Master hostname
682

683
    """
684
    return self._config_data.cluster.master_node
685

    
686
  @locking.ssynchronized(_config_lock, shared=1)
687
  def GetMasterIP(self):
688
    """Get the IP of the master node for this cluster.
689

690
    @return: Master IP
691

692
    """
693
    return self._config_data.cluster.master_ip
694

    
695
  @locking.ssynchronized(_config_lock, shared=1)
696
  def GetMasterNetdev(self):
697
    """Get the master network device for this cluster.
698

699
    """
700
    return self._config_data.cluster.master_netdev
701

    
702
  @locking.ssynchronized(_config_lock, shared=1)
703
  def GetFileStorageDir(self):
704
    """Get the file storage dir for this cluster.
705

706
    """
707
    return self._config_data.cluster.file_storage_dir
708

    
709
  @locking.ssynchronized(_config_lock, shared=1)
710
  def GetHypervisorType(self):
711
    """Get the hypervisor type for this cluster.
712

713
    """
714
    return self._config_data.cluster.enabled_hypervisors[0]
715

    
716
  @locking.ssynchronized(_config_lock, shared=1)
717
  def GetHostKey(self):
718
    """Return the rsa hostkey from the config.
719

720
    @rtype: string
721
    @return: the rsa hostkey
722

723
    """
724
    return self._config_data.cluster.rsahostkeypub
725

    
726
  @locking.ssynchronized(_config_lock)
727
  def AddInstance(self, instance):
728
    """Add an instance to the config.
729

730
    This should be used after creating a new instance.
731

732
    @type instance: L{objects.Instance}
733
    @param instance: the instance object
734

735
    """
736
    if not isinstance(instance, objects.Instance):
737
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
738

    
739
    if instance.disk_template != constants.DT_DISKLESS:
740
      all_lvs = instance.MapLVsByNode()
741
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
742

    
743
    all_macs = self._AllMACs()
744
    for nic in instance.nics:
745
      if nic.mac in all_macs:
746
        raise errors.ConfigurationError("Cannot add instance %s:"
747
                                        " MAC address '%s' already in use." %
748
                                        (instance.name, nic.mac))
749

    
750
    self._EnsureUUID(instance)
751

    
752
    instance.serial_no = 1
753
    instance.ctime = instance.mtime = time.time()
754
    self._config_data.instances[instance.name] = instance
755
    self._config_data.cluster.serial_no += 1
756
    self._UnlockedReleaseDRBDMinors(instance.name)
757
    for nic in instance.nics:
758
      self._temporary_macs.discard(nic.mac)
759
    self._WriteConfig()
760

    
761
  def _EnsureUUID(self, item):
762
    """Ensures a given object has a valid UUID.
763

764
    @param item: the instance or node to be checked
765

766
    """
767
    if not item.uuid:
768
      item.uuid = self._GenerateUniqueID()
769
    elif item.uuid in self._AllIDs(temporary=True):
770
      raise errors.ConfigurationError("Cannot add '%s': UUID already in use" %
771
                                      (item.name, item.uuid))
772

    
773
  def _SetInstanceStatus(self, instance_name, status):
774
    """Set the instance's status to a given value.
775

776
    """
777
    assert isinstance(status, bool), \
778
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
779

    
780
    if instance_name not in self._config_data.instances:
781
      raise errors.ConfigurationError("Unknown instance '%s'" %
782
                                      instance_name)
783
    instance = self._config_data.instances[instance_name]
784
    if instance.admin_up != status:
785
      instance.admin_up = status
786
      instance.serial_no += 1
787
      instance.mtime = time.time()
788
      self._WriteConfig()
789

    
790
  @locking.ssynchronized(_config_lock)
791
  def MarkInstanceUp(self, instance_name):
792
    """Mark the instance status to up in the config.
793

794
    """
795
    self._SetInstanceStatus(instance_name, True)
796

    
797
  @locking.ssynchronized(_config_lock)
798
  def RemoveInstance(self, instance_name):
799
    """Remove the instance from the configuration.
800

801
    """
802
    if instance_name not in self._config_data.instances:
803
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
804
    del self._config_data.instances[instance_name]
805
    self._config_data.cluster.serial_no += 1
806
    self._WriteConfig()
807

    
808
  @locking.ssynchronized(_config_lock)
809
  def RenameInstance(self, old_name, new_name):
810
    """Rename an instance.
811

812
    This needs to be done in ConfigWriter and not by RemoveInstance
813
    combined with AddInstance as only we can guarantee an atomic
814
    rename.
815

816
    """
817
    if old_name not in self._config_data.instances:
818
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
819
    inst = self._config_data.instances[old_name]
820
    del self._config_data.instances[old_name]
821
    inst.name = new_name
822

    
823
    for disk in inst.disks:
824
      if disk.dev_type == constants.LD_FILE:
825
        # rename the file paths in logical and physical id
826
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
827
        disk.physical_id = disk.logical_id = (disk.logical_id[0],
828
                                              os.path.join(file_storage_dir,
829
                                                           inst.name,
830
                                                           disk.iv_name))
831

    
832
    self._config_data.instances[inst.name] = inst
833
    self._WriteConfig()
834

    
835
  @locking.ssynchronized(_config_lock)
836
  def MarkInstanceDown(self, instance_name):
837
    """Mark the status of an instance to down in the configuration.
838

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

    
842
  def _UnlockedGetInstanceList(self):
843
    """Get the list of instances.
844

845
    This function is for internal use, when the config lock is already held.
846

847
    """
848
    return self._config_data.instances.keys()
849

    
850
  @locking.ssynchronized(_config_lock, shared=1)
851
  def GetInstanceList(self):
852
    """Get the list of instances.
853

854
    @return: array of instances, ex. ['instance2.example.com',
855
        'instance1.example.com']
856

857
    """
858
    return self._UnlockedGetInstanceList()
859

    
860
  @locking.ssynchronized(_config_lock, shared=1)
861
  def ExpandInstanceName(self, short_name):
862
    """Attempt to expand an incomplete instance name.
863

864
    """
865
    return utils.MatchNameComponent(short_name,
866
                                    self._config_data.instances.keys(),
867
                                    case_sensitive=False)
868

    
869
  def _UnlockedGetInstanceInfo(self, instance_name):
870
    """Returns information about an instance.
871

872
    This function is for internal use, when the config lock is already held.
873

874
    """
875
    if instance_name not in self._config_data.instances:
876
      return None
877

    
878
    return self._config_data.instances[instance_name]
879

    
880
  @locking.ssynchronized(_config_lock, shared=1)
881
  def GetInstanceInfo(self, instance_name):
882
    """Returns information about an instance.
883

884
    It takes the information from the configuration file. Other information of
885
    an instance are taken from the live systems.
886

887
    @param instance_name: name of the instance, e.g.
888
        I{instance1.example.com}
889

890
    @rtype: L{objects.Instance}
891
    @return: the instance object
892

893
    """
894
    return self._UnlockedGetInstanceInfo(instance_name)
895

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

900
    @rtype: dict
901
    @return: dict of (instance, instance_info), where instance_info is what
902
              would GetInstanceInfo return for the node
903

904
    """
905
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
906
                    for instance in self._UnlockedGetInstanceList()])
907
    return my_dict
908

    
909
  @locking.ssynchronized(_config_lock)
910
  def AddNode(self, node):
911
    """Add a node to the configuration.
912

913
    @type node: L{objects.Node}
914
    @param node: a Node instance
915

916
    """
917
    logging.info("Adding node %s to configuration", node.name)
918

    
919
    self._EnsureUUID(node)
920

    
921
    node.serial_no = 1
922
    node.ctime = node.mtime = time.time()
923
    self._config_data.nodes[node.name] = node
924
    self._config_data.cluster.serial_no += 1
925
    self._WriteConfig()
926

    
927
  @locking.ssynchronized(_config_lock)
928
  def RemoveNode(self, node_name):
929
    """Remove a node from the configuration.
930

931
    """
932
    logging.info("Removing node %s from configuration", node_name)
933

    
934
    if node_name not in self._config_data.nodes:
935
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
936

    
937
    del self._config_data.nodes[node_name]
938
    self._config_data.cluster.serial_no += 1
939
    self._WriteConfig()
940

    
941
  @locking.ssynchronized(_config_lock, shared=1)
942
  def ExpandNodeName(self, short_name):
943
    """Attempt to expand an incomplete instance name.
944

945
    """
946
    return utils.MatchNameComponent(short_name,
947
                                    self._config_data.nodes.keys(),
948
                                    case_sensitive=False)
949

    
950
  def _UnlockedGetNodeInfo(self, node_name):
951
    """Get the configuration of a node, as stored in the config.
952

953
    This function is for internal use, when the config lock is already
954
    held.
955

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

958
    @rtype: L{objects.Node}
959
    @return: the node object
960

961
    """
962
    if node_name not in self._config_data.nodes:
963
      return None
964

    
965
    return self._config_data.nodes[node_name]
966

    
967

    
968
  @locking.ssynchronized(_config_lock, shared=1)
969
  def GetNodeInfo(self, node_name):
970
    """Get the configuration of a node, as stored in the config.
971

972
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
973

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

976
    @rtype: L{objects.Node}
977
    @return: the node object
978

979
    """
980
    return self._UnlockedGetNodeInfo(node_name)
981

    
982
  def _UnlockedGetNodeList(self):
983
    """Return the list of nodes which are in the configuration.
984

985
    This function is for internal use, when the config lock is already
986
    held.
987

988
    @rtype: list
989

990
    """
991
    return self._config_data.nodes.keys()
992

    
993

    
994
  @locking.ssynchronized(_config_lock, shared=1)
995
  def GetNodeList(self):
996
    """Return the list of nodes which are in the configuration.
997

998
    """
999
    return self._UnlockedGetNodeList()
1000

    
1001
  @locking.ssynchronized(_config_lock, shared=1)
1002
  def GetOnlineNodeList(self):
1003
    """Return the list of nodes which are online.
1004

1005
    """
1006
    all_nodes = [self._UnlockedGetNodeInfo(node)
1007
                 for node in self._UnlockedGetNodeList()]
1008
    return [node.name for node in all_nodes if not node.offline]
1009

    
1010
  @locking.ssynchronized(_config_lock, shared=1)
1011
  def GetAllNodesInfo(self):
1012
    """Get the configuration of all nodes.
1013

1014
    @rtype: dict
1015
    @return: dict of (node, node_info), where node_info is what
1016
              would GetNodeInfo return for the node
1017

1018
    """
1019
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
1020
                    for node in self._UnlockedGetNodeList()])
1021
    return my_dict
1022

    
1023
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1024
    """Get the number of current and maximum desired and possible candidates.
1025

1026
    @type exceptions: list
1027
    @param exceptions: if passed, list of nodes that should be ignored
1028
    @rtype: tuple
1029
    @return: tuple of (current, desired and possible, possible)
1030

1031
    """
1032
    mc_now = mc_should = mc_max = 0
1033
    for node in self._config_data.nodes.values():
1034
      if exceptions and node.name in exceptions:
1035
        continue
1036
      if not (node.offline or node.drained):
1037
        mc_max += 1
1038
      if node.master_candidate:
1039
        mc_now += 1
1040
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1041
    return (mc_now, mc_should, mc_max)
1042

    
1043
  @locking.ssynchronized(_config_lock, shared=1)
1044
  def GetMasterCandidateStats(self, exceptions=None):
1045
    """Get the number of current and maximum possible candidates.
1046

1047
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1048

1049
    @type exceptions: list
1050
    @param exceptions: if passed, list of nodes that should be ignored
1051
    @rtype: tuple
1052
    @return: tuple of (current, max)
1053

1054
    """
1055
    return self._UnlockedGetMasterCandidateStats(exceptions)
1056

    
1057
  @locking.ssynchronized(_config_lock)
1058
  def MaintainCandidatePool(self, exceptions):
1059
    """Try to grow the candidate pool to the desired size.
1060

1061
    @type exceptions: list
1062
    @param exceptions: if passed, list of nodes that should be ignored
1063
    @rtype: list
1064
    @return: list with the adjusted nodes (L{objects.Node} instances)
1065

1066
    """
1067
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1068
    mod_list = []
1069
    if mc_now < mc_max:
1070
      node_list = self._config_data.nodes.keys()
1071
      random.shuffle(node_list)
1072
      for name in node_list:
1073
        if mc_now >= mc_max:
1074
          break
1075
        node = self._config_data.nodes[name]
1076
        if (node.master_candidate or node.offline or node.drained or
1077
            node.name in exceptions):
1078
          continue
1079
        mod_list.append(node)
1080
        node.master_candidate = True
1081
        node.serial_no += 1
1082
        mc_now += 1
1083
      if mc_now != mc_max:
1084
        # this should not happen
1085
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1086
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1087
      if mod_list:
1088
        self._config_data.cluster.serial_no += 1
1089
        self._WriteConfig()
1090

    
1091
    return mod_list
1092

    
1093
  def _BumpSerialNo(self):
1094
    """Bump up the serial number of the config.
1095

1096
    """
1097
    self._config_data.serial_no += 1
1098
    self._config_data.mtime = time.time()
1099

    
1100
  def _AllUUIDObjects(self):
1101
    """Returns all objects with uuid attributes.
1102

1103
    """
1104
    return (self._config_data.instances.values() +
1105
            self._config_data.nodes.values() +
1106
            [self._config_data.cluster])
1107

    
1108
  def _OpenConfig(self):
1109
    """Read the config data from disk.
1110

1111
    """
1112
    raw_data = utils.ReadFile(self._cfg_file)
1113

    
1114
    try:
1115
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1116
    except Exception, err:
1117
      raise errors.ConfigurationError(err)
1118

    
1119
    # Make sure the configuration has the right version
1120
    _ValidateConfig(data)
1121

    
1122
    if (not hasattr(data, 'cluster') or
1123
        not hasattr(data.cluster, 'rsahostkeypub')):
1124
      raise errors.ConfigurationError("Incomplete configuration"
1125
                                      " (missing cluster.rsahostkeypub)")
1126

    
1127
    # Upgrade configuration if needed
1128
    data.UpgradeConfig()
1129

    
1130
    self._config_data = data
1131
    # reset the last serial as -1 so that the next write will cause
1132
    # ssconf update
1133
    self._last_cluster_serial = -1
1134

    
1135
    # And finally run our (custom) config upgrade sequence
1136
    self._UpgradeConfig()
1137

    
1138
  def _UpgradeConfig(self):
1139
    """Run upgrade steps that cannot be done purely in the objects.
1140

1141
    This is because some data elements need uniqueness across the
1142
    whole configuration, etc.
1143

1144
    @warning: this function will call L{_WriteConfig()}, so it needs
1145
        to either be called with the lock held or from a safe place
1146
        (the constructor)
1147

1148
    """
1149
    modified = False
1150
    for item in self._AllUUIDObjects():
1151
      if item.uuid is None:
1152
        item.uuid = self._GenerateUniqueID()
1153
        modified = True
1154
    if modified:
1155
      self._WriteConfig()
1156

    
1157
  def _DistributeConfig(self, feedback_fn):
1158
    """Distribute the configuration to the other nodes.
1159

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

1163
    """
1164
    if self._offline:
1165
      return True
1166

    
1167
    bad = False
1168

    
1169
    node_list = []
1170
    addr_list = []
1171
    myhostname = self._my_hostname
1172
    # we can skip checking whether _UnlockedGetNodeInfo returns None
1173
    # since the node list comes from _UnlocketGetNodeList, and we are
1174
    # called with the lock held, so no modifications should take place
1175
    # in between
1176
    for node_name in self._UnlockedGetNodeList():
1177
      if node_name == myhostname:
1178
        continue
1179
      node_info = self._UnlockedGetNodeInfo(node_name)
1180
      if not node_info.master_candidate:
1181
        continue
1182
      node_list.append(node_info.name)
1183
      addr_list.append(node_info.primary_ip)
1184

    
1185
    result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
1186
                                            address_list=addr_list)
1187
    for to_node, to_result in result.items():
1188
      msg = to_result.fail_msg
1189
      if msg:
1190
        msg = ("Copy of file %s to node %s failed: %s" %
1191
               (self._cfg_file, to_node, msg))
1192
        logging.error(msg)
1193

    
1194
        if feedback_fn:
1195
          feedback_fn(msg)
1196

    
1197
        bad = True
1198

    
1199
    return not bad
1200

    
1201
  def _WriteConfig(self, destination=None, feedback_fn=None):
1202
    """Write the configuration data to persistent storage.
1203

1204
    """
1205
    assert feedback_fn is None or callable(feedback_fn)
1206

    
1207
    # First, cleanup the _temporary_ids set, if an ID is now in the
1208
    # other objects it should be discarded to prevent unbounded growth
1209
    # of that structure
1210
    self._CleanupTemporaryIDs()
1211

    
1212
    # Warn on config errors, but don't abort the save - the
1213
    # configuration has already been modified, and we can't revert;
1214
    # the best we can do is to warn the user and save as is, leaving
1215
    # recovery to the user
1216
    config_errors = self._UnlockedVerifyConfig()
1217
    if config_errors:
1218
      errmsg = ("Configuration data is not consistent: %s" %
1219
                (", ".join(config_errors)))
1220
      logging.critical(errmsg)
1221
      if feedback_fn:
1222
        feedback_fn(errmsg)
1223

    
1224
    if destination is None:
1225
      destination = self._cfg_file
1226
    self._BumpSerialNo()
1227
    txt = serializer.Dump(self._config_data.ToDict())
1228

    
1229
    utils.WriteFile(destination, data=txt)
1230

    
1231
    self.write_count += 1
1232

    
1233
    # and redistribute the config file to master candidates
1234
    self._DistributeConfig(feedback_fn)
1235

    
1236
    # Write ssconf files on all nodes (including locally)
1237
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
1238
      if not self._offline:
1239
        result = rpc.RpcRunner.call_write_ssconf_files(
1240
          self._UnlockedGetNodeList(),
1241
          self._UnlockedGetSsconfValues())
1242

    
1243
        for nname, nresu in result.items():
1244
          msg = nresu.fail_msg
1245
          if msg:
1246
            errmsg = ("Error while uploading ssconf files to"
1247
                      " node %s: %s" % (nname, msg))
1248
            logging.warning(errmsg)
1249

    
1250
            if feedback_fn:
1251
              feedback_fn(errmsg)
1252

    
1253
      self._last_cluster_serial = self._config_data.cluster.serial_no
1254

    
1255
  def _UnlockedGetSsconfValues(self):
1256
    """Return the values needed by ssconf.
1257

1258
    @rtype: dict
1259
    @return: a dictionary with keys the ssconf names and values their
1260
        associated value
1261

1262
    """
1263
    fn = "\n".join
1264
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1265
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
1266
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1267
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
1268
                    for ninfo in node_info]
1269
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
1270
                    for ninfo in node_info]
1271

    
1272
    instance_data = fn(instance_names)
1273
    off_data = fn(node.name for node in node_info if node.offline)
1274
    on_data = fn(node.name for node in node_info if not node.offline)
1275
    mc_data = fn(node.name for node in node_info if node.master_candidate)
1276
    mc_ips_data = fn(node.primary_ip for node in node_info
1277
                     if node.master_candidate)
1278
    node_data = fn(node_names)
1279
    node_pri_ips_data = fn(node_pri_ips)
1280
    node_snd_ips_data = fn(node_snd_ips)
1281

    
1282
    cluster = self._config_data.cluster
1283
    cluster_tags = fn(cluster.GetTags())
1284
    return {
1285
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
1286
      constants.SS_CLUSTER_TAGS: cluster_tags,
1287
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1288
      constants.SS_MASTER_CANDIDATES: mc_data,
1289
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
1290
      constants.SS_MASTER_IP: cluster.master_ip,
1291
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
1292
      constants.SS_MASTER_NODE: cluster.master_node,
1293
      constants.SS_NODE_LIST: node_data,
1294
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
1295
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
1296
      constants.SS_OFFLINE_NODES: off_data,
1297
      constants.SS_ONLINE_NODES: on_data,
1298
      constants.SS_INSTANCE_LIST: instance_data,
1299
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1300
      }
1301

    
1302
  @locking.ssynchronized(_config_lock, shared=1)
1303
  def GetVGName(self):
1304
    """Return the volume group name.
1305

1306
    """
1307
    return self._config_data.cluster.volume_group_name
1308

    
1309
  @locking.ssynchronized(_config_lock)
1310
  def SetVGName(self, vg_name):
1311
    """Set the volume group name.
1312

1313
    """
1314
    self._config_data.cluster.volume_group_name = vg_name
1315
    self._config_data.cluster.serial_no += 1
1316
    self._WriteConfig()
1317

    
1318
  @locking.ssynchronized(_config_lock, shared=1)
1319
  def GetMACPrefix(self):
1320
    """Return the mac prefix.
1321

1322
    """
1323
    return self._config_data.cluster.mac_prefix
1324

    
1325
  @locking.ssynchronized(_config_lock, shared=1)
1326
  def GetClusterInfo(self):
1327
    """Returns information about the cluster
1328

1329
    @rtype: L{objects.Cluster}
1330
    @return: the cluster object
1331

1332
    """
1333
    return self._config_data.cluster
1334

    
1335
  @locking.ssynchronized(_config_lock)
1336
  def Update(self, target, feedback_fn):
1337
    """Notify function to be called after updates.
1338

1339
    This function must be called when an object (as returned by
1340
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
1341
    caller wants the modifications saved to the backing store. Note
1342
    that all modified objects will be saved, but the target argument
1343
    is the one the caller wants to ensure that it's saved.
1344

1345
    @param target: an instance of either L{objects.Cluster},
1346
        L{objects.Node} or L{objects.Instance} which is existing in
1347
        the cluster
1348
    @param feedback_fn: Callable feedback function
1349

1350
    """
1351
    if self._config_data is None:
1352
      raise errors.ProgrammerError("Configuration file not read,"
1353
                                   " cannot save.")
1354
    update_serial = False
1355
    if isinstance(target, objects.Cluster):
1356
      test = target == self._config_data.cluster
1357
    elif isinstance(target, objects.Node):
1358
      test = target in self._config_data.nodes.values()
1359
      update_serial = True
1360
    elif isinstance(target, objects.Instance):
1361
      test = target in self._config_data.instances.values()
1362
    else:
1363
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
1364
                                   " ConfigWriter.Update" % type(target))
1365
    if not test:
1366
      raise errors.ConfigurationError("Configuration updated since object"
1367
                                      " has been read or unknown object")
1368
    target.serial_no += 1
1369
    target.mtime = now = time.time()
1370

    
1371
    if update_serial:
1372
      # for node updates, we need to increase the cluster serial too
1373
      self._config_data.cluster.serial_no += 1
1374
      self._config_data.cluster.mtime = now
1375

    
1376
    if isinstance(target, objects.Instance):
1377
      self._UnlockedReleaseDRBDMinors(target.name)
1378
      for nic in target.nics:
1379
        self._temporary_macs.discard(nic.mac)
1380

    
1381
    self._WriteConfig(feedback_fn=feedback_fn)
1382

    
1383
  @locking.ssynchronized(_config_lock)
1384
  def DropECReservations(self, ec_id):
1385
    """Drop per-execution-context reservations
1386

1387
    """
1388
    pass
1389