Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 0debfb35

History | View | Annotate | Download (44.4 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, ec_id):
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, ec_id)
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, ec_id):
762
    """Ensures a given object has a valid UUID.
763

764
    @param item: the instance or node to be checked
765
    @param ec_id: the execution context id for the uuid reservation
766

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
879
    return self._config_data.instances[instance_name]
880

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

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

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

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

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

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

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

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

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

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

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

    
920
    self._EnsureUUID(node, ec_id)
921

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

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

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

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

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

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

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

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

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

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

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

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

    
966
    return self._config_data.nodes[node_name]
967

    
968

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

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

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

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

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

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

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

989
    @rtype: list
990

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

    
994

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1092
    return mod_list
1093

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1168
    bad = False
1169

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

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

    
1195
        if feedback_fn:
1196
          feedback_fn(msg)
1197

    
1198
        bad = True
1199

    
1200
    return not bad
1201

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

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

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

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

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

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

    
1232
    self.write_count += 1
1233

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

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

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

    
1251
            if feedback_fn:
1252
              feedback_fn(errmsg)
1253

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1382
    self._WriteConfig(feedback_fn=feedback_fn)
1383

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

1388
    """
1389
    pass
1390