Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 5bf07049

History | View | Annotate | Download (38.6 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 tempfile
36
import random
37
import logging
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
    # Note: in order to prevent errors when resolving our name in
83
    # _DistributeConfig, we compute it here once and reuse it; it's
84
    # better to raise an error before starting to modify the config
85
    # file than after it was modified
86
    self._my_hostname = utils.HostInfo().name
87
    self._last_cluster_serial = -1
88
    self._OpenConfig()
89

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

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

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

102
    This should check the current instances for duplicates.
103

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

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

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

127
    """
128
    all_macs = self._AllMACs()
129
    return mac in all_macs
130

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

135
    This checks the current disks for duplicates.
136

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

    
149
  def _ComputeAllLVs(self):
150
    """Compute the list of all LVs.
151

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

    
160
  @locking.ssynchronized(_config_lock, shared=1)
161
  def GenerateUniqueID(self, exceptions=None):
162
    """Generate an unique disk name.
163

164
    This checks the current node, instances and disk names for
165
    duplicates.
166

167
    @param exceptions: a list with some other names which should be checked
168
        for uniqueness (used for example when you want to get
169
        more than one id at one time without adding each one in
170
        turn to the config file)
171

172
    @rtype: string
173
    @return: the unique id
174

175
    """
176
    existing = set()
177
    existing.update(self._temporary_ids)
178
    existing.update(self._ComputeAllLVs())
179
    existing.update(self._config_data.instances.keys())
180
    existing.update(self._config_data.nodes.keys())
181
    if exceptions is not None:
182
      existing.update(exceptions)
183
    retries = 64
184
    while retries > 0:
185
      unique_id = utils.NewUUID()
186
      if unique_id not in existing and unique_id is not None:
187
        break
188
    else:
189
      raise errors.ConfigurationError("Not able generate an unique ID"
190
                                      " (last tried ID: %s" % unique_id)
191
    self._temporary_ids.add(unique_id)
192
    return unique_id
193

    
194
  def _AllMACs(self):
195
    """Return all MACs present in the config.
196

197
    @rtype: list
198
    @return: the list of all MACs
199

200
    """
201
    result = []
202
    for instance in self._config_data.instances.values():
203
      for nic in instance.nics:
204
        result.append(nic.mac)
205

    
206
    return result
207

    
208
  def _AllDRBDSecrets(self):
209
    """Return all DRBD secrets present in the config.
210

211
    @rtype: list
212
    @return: the list of all DRBD secrets
213

214
    """
215
    def helper(disk, result):
216
      """Recursively gather secrets from this disk."""
217
      if disk.dev_type == constants.DT_DRBD8:
218
        result.append(disk.logical_id[5])
219
      if disk.children:
220
        for child in disk.children:
221
          helper(child, result)
222

    
223
    result = []
224
    for instance in self._config_data.instances.values():
225
      for disk in instance.disks:
226
        helper(disk, result)
227

    
228
    return result
229

    
230
  def _UnlockedVerifyConfig(self):
231
    """Verify function.
232

233
    @rtype: list
234
    @return: a list of error messages; a non-empty list signifies
235
        configuration errors
236

237
    """
238
    result = []
239
    seen_macs = []
240
    ports = {}
241
    data = self._config_data
242
    for instance_name in data.instances:
243
      instance = data.instances[instance_name]
244
      if instance.primary_node not in data.nodes:
245
        result.append("instance '%s' has invalid primary node '%s'" %
246
                      (instance_name, instance.primary_node))
247
      for snode in instance.secondary_nodes:
248
        if snode not in data.nodes:
249
          result.append("instance '%s' has invalid secondary node '%s'" %
250
                        (instance_name, snode))
251
      for idx, nic in enumerate(instance.nics):
252
        if nic.mac in seen_macs:
253
          result.append("instance '%s' has NIC %d mac %s duplicate" %
254
                        (instance_name, idx, nic.mac))
255
        else:
256
          seen_macs.append(nic.mac)
257

    
258
      # gather the drbd ports for duplicate checks
259
      for dsk in instance.disks:
260
        if dsk.dev_type in constants.LDS_DRBD:
261
          tcp_port = dsk.logical_id[2]
262
          if tcp_port not in ports:
263
            ports[tcp_port] = []
264
          ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
265
      # gather network port reservation
266
      net_port = getattr(instance, "network_port", None)
267
      if net_port is not None:
268
        if net_port not in ports:
269
          ports[net_port] = []
270
        ports[net_port].append((instance.name, "network port"))
271

    
272
      # instance disk verify
273
      for idx, disk in enumerate(instance.disks):
274
        result.extend(["instance '%s' disk %d error: %s" %
275
                       (instance.name, idx, msg) for msg in disk.Verify()])
276

    
277
    # cluster-wide pool of free ports
278
    for free_port in data.cluster.tcpudp_port_pool:
279
      if free_port not in ports:
280
        ports[free_port] = []
281
      ports[free_port].append(("cluster", "port marked as free"))
282

    
283
    # compute tcp/udp duplicate ports
284
    keys = ports.keys()
285
    keys.sort()
286
    for pnum in keys:
287
      pdata = ports[pnum]
288
      if len(pdata) > 1:
289
        txt = ", ".join(["%s/%s" % val for val in pdata])
290
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
291

    
292
    # highest used tcp port check
293
    if keys:
294
      if keys[-1] > data.cluster.highest_used_port:
295
        result.append("Highest used port mismatch, saved %s, computed %s" %
296
                      (data.cluster.highest_used_port, keys[-1]))
297

    
298
    if not data.nodes[data.cluster.master_node].master_candidate:
299
      result.append("Master node is not a master candidate")
300

    
301
    # master candidate checks
302
    mc_now, mc_max = self._UnlockedGetMasterCandidateStats()
303
    if mc_now < mc_max:
304
      result.append("Not enough master candidates: actual %d, target %d" %
305
                    (mc_now, mc_max))
306

    
307
    # node checks
308
    for node in data.nodes.values():
309
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
310
        result.append("Node %s state is invalid: master_candidate=%s,"
311
                      " drain=%s, offline=%s" %
312
                      (node.name, node.master_candidate, node.drain,
313
                       node.offline))
314

    
315
    # drbd minors check
316
    d_map, duplicates = self._UnlockedComputeDRBDMap()
317
    for node, minor, instance_a, instance_b in duplicates:
318
      result.append("DRBD minor %d on node %s is assigned twice to instances"
319
                    " %s and %s" % (minor, node, instance_a, instance_b))
320

    
321
    return result
322

    
323
  @locking.ssynchronized(_config_lock, shared=1)
324
  def VerifyConfig(self):
325
    """Verify function.
326

327
    This is just a wrapper over L{_UnlockedVerifyConfig}.
328

329
    @rtype: list
330
    @return: a list of error messages; a non-empty list signifies
331
        configuration errors
332

333
    """
334
    return self._UnlockedVerifyConfig()
335

    
336
  def _UnlockedSetDiskID(self, disk, node_name):
337
    """Convert the unique ID to the ID needed on the target nodes.
338

339
    This is used only for drbd, which needs ip/port configuration.
340

341
    The routine descends down and updates its children also, because
342
    this helps when the only the top device is passed to the remote
343
    node.
344

345
    This function is for internal use, when the config lock is already held.
346

347
    """
348
    if disk.children:
349
      for child in disk.children:
350
        self._UnlockedSetDiskID(child, node_name)
351

    
352
    if disk.logical_id is None and disk.physical_id is not None:
353
      return
354
    if disk.dev_type == constants.LD_DRBD8:
355
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
356
      if node_name not in (pnode, snode):
357
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
358
                                        node_name)
359
      pnode_info = self._UnlockedGetNodeInfo(pnode)
360
      snode_info = self._UnlockedGetNodeInfo(snode)
361
      if pnode_info is None or snode_info is None:
362
        raise errors.ConfigurationError("Can't find primary or secondary node"
363
                                        " for %s" % str(disk))
364
      p_data = (pnode_info.secondary_ip, port)
365
      s_data = (snode_info.secondary_ip, port)
366
      if pnode == node_name:
367
        disk.physical_id = p_data + s_data + (pminor, secret)
368
      else: # it must be secondary, we tested above
369
        disk.physical_id = s_data + p_data + (sminor, secret)
370
    else:
371
      disk.physical_id = disk.logical_id
372
    return
373

    
374
  @locking.ssynchronized(_config_lock)
375
  def SetDiskID(self, disk, node_name):
376
    """Convert the unique ID to the ID needed on the target nodes.
377

378
    This is used only for drbd, which needs ip/port configuration.
379

380
    The routine descends down and updates its children also, because
381
    this helps when the only the top device is passed to the remote
382
    node.
383

384
    """
385
    return self._UnlockedSetDiskID(disk, node_name)
386

    
387
  @locking.ssynchronized(_config_lock)
388
  def AddTcpUdpPort(self, port):
389
    """Adds a new port to the available port pool.
390

391
    """
392
    if not isinstance(port, int):
393
      raise errors.ProgrammerError("Invalid type passed for port")
394

    
395
    self._config_data.cluster.tcpudp_port_pool.add(port)
396
    self._WriteConfig()
397

    
398
  @locking.ssynchronized(_config_lock, shared=1)
399
  def GetPortList(self):
400
    """Returns a copy of the current port list.
401

402
    """
403
    return self._config_data.cluster.tcpudp_port_pool.copy()
404

    
405
  @locking.ssynchronized(_config_lock)
406
  def AllocatePort(self):
407
    """Allocate a port.
408

409
    The port will be taken from the available port pool or from the
410
    default port range (and in this case we increase
411
    highest_used_port).
412

413
    """
414
    # If there are TCP/IP ports configured, we use them first.
415
    if self._config_data.cluster.tcpudp_port_pool:
416
      port = self._config_data.cluster.tcpudp_port_pool.pop()
417
    else:
418
      port = self._config_data.cluster.highest_used_port + 1
419
      if port >= constants.LAST_DRBD_PORT:
420
        raise errors.ConfigurationError("The highest used port is greater"
421
                                        " than %s. Aborting." %
422
                                        constants.LAST_DRBD_PORT)
423
      self._config_data.cluster.highest_used_port = port
424

    
425
    self._WriteConfig()
426
    return port
427

    
428
  def _UnlockedComputeDRBDMap(self):
429
    """Compute the used DRBD minor/nodes.
430

431
    @rtype: (dict, list)
432
    @return: dictionary of node_name: dict of minor: instance_name;
433
        the returned dict will have all the nodes in it (even if with
434
        an empty list), and a list of duplicates; if the duplicates
435
        list is not empty, the configuration is corrupted and its caller
436
        should raise an exception
437

438
    """
439
    def _AppendUsedPorts(instance_name, disk, used):
440
      duplicates = []
441
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
442
        nodeA, nodeB, dummy, minorA, minorB = disk.logical_id[:5]
443
        for node, port in ((nodeA, minorA), (nodeB, minorB)):
444
          assert node in used, ("Node '%s' of instance '%s' not found"
445
                                " in node list" % (node, instance_name))
446
          if port in used[node]:
447
            duplicates.append((node, port, instance_name, used[node][port]))
448
          else:
449
            used[node][port] = instance_name
450
      if disk.children:
451
        for child in disk.children:
452
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
453
      return duplicates
454

    
455
    duplicates = []
456
    my_dict = dict((node, {}) for node in self._config_data.nodes)
457
    for instance in self._config_data.instances.itervalues():
458
      for disk in instance.disks:
459
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
460
    for (node, minor), instance in self._temporary_drbds.iteritems():
461
      if minor in my_dict[node] and my_dict[node][minor] != instance:
462
        duplicates.append((node, minor, instance, my_dict[node][minor]))
463
      else:
464
        my_dict[node][minor] = instance
465
    return my_dict, duplicates
466

    
467
  @locking.ssynchronized(_config_lock)
468
  def ComputeDRBDMap(self):
469
    """Compute the used DRBD minor/nodes.
470

471
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
472

473
    @return: dictionary of node_name: dict of minor: instance_name;
474
        the returned dict will have all the nodes in it (even if with
475
        an empty list).
476

477
    """
478
    d_map, duplicates = self._UnlockedComputeDRBDMap()
479
    if duplicates:
480
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
481
                                      str(duplicates))
482
    return d_map
483

    
484
  @locking.ssynchronized(_config_lock)
485
  def AllocateDRBDMinor(self, nodes, instance):
486
    """Allocate a drbd minor.
487

488
    The free minor will be automatically computed from the existing
489
    devices. A node can be given multiple times in order to allocate
490
    multiple minors. The result is the list of minors, in the same
491
    order as the passed nodes.
492

493
    @type instance: string
494
    @param instance: the instance for which we allocate minors
495

496
    """
497
    assert isinstance(instance, basestring), \
498
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
499

    
500
    d_map, duplicates = self._UnlockedComputeDRBDMap()
501
    if duplicates:
502
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
503
                                      str(duplicates))
504
    result = []
505
    for nname in nodes:
506
      ndata = d_map[nname]
507
      if not ndata:
508
        # no minors used, we can start at 0
509
        result.append(0)
510
        ndata[0] = instance
511
        self._temporary_drbds[(nname, 0)] = instance
512
        continue
513
      keys = ndata.keys()
514
      keys.sort()
515
      ffree = utils.FirstFree(keys)
516
      if ffree is None:
517
        # return the next minor
518
        # TODO: implement high-limit check
519
        minor = keys[-1] + 1
520
      else:
521
        minor = ffree
522
      # double-check minor against current instances
523
      assert minor not in d_map[nname], \
524
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
525
              " already allocated to instance %s" %
526
              (minor, nname, d_map[nname][minor]))
527
      ndata[minor] = instance
528
      # double-check minor against reservation
529
      r_key = (nname, minor)
530
      assert r_key not in self._temporary_drbds, \
531
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
532
              " reserved for instance %s" %
533
              (minor, nname, self._temporary_drbds[r_key]))
534
      self._temporary_drbds[r_key] = instance
535
      result.append(minor)
536
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
537
                  nodes, result)
538
    return result
539

    
540
  def _UnlockedReleaseDRBDMinors(self, instance):
541
    """Release temporary drbd minors allocated for a given instance.
542

543
    @type instance: string
544
    @param instance: the instance for which temporary minors should be
545
                     released
546

547
    """
548
    assert isinstance(instance, basestring), \
549
           "Invalid argument passed to ReleaseDRBDMinors"
550
    for key, name in self._temporary_drbds.items():
551
      if name == instance:
552
        del self._temporary_drbds[key]
553

    
554
  @locking.ssynchronized(_config_lock)
555
  def ReleaseDRBDMinors(self, instance):
556
    """Release temporary drbd minors allocated for a given instance.
557

558
    This should be called on the error paths, on the success paths
559
    it's automatically called by the ConfigWriter add and update
560
    functions.
561

562
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
563

564
    @type instance: string
565
    @param instance: the instance for which temporary minors should be
566
                     released
567

568
    """
569
    self._UnlockedReleaseDRBDMinors(instance)
570

    
571
  @locking.ssynchronized(_config_lock, shared=1)
572
  def GetConfigVersion(self):
573
    """Get the configuration version.
574

575
    @return: Config version
576

577
    """
578
    return self._config_data.version
579

    
580
  @locking.ssynchronized(_config_lock, shared=1)
581
  def GetClusterName(self):
582
    """Get cluster name.
583

584
    @return: Cluster name
585

586
    """
587
    return self._config_data.cluster.cluster_name
588

    
589
  @locking.ssynchronized(_config_lock, shared=1)
590
  def GetMasterNode(self):
591
    """Get the hostname of the master node for this cluster.
592

593
    @return: Master hostname
594

595
    """
596
    return self._config_data.cluster.master_node
597

    
598
  @locking.ssynchronized(_config_lock, shared=1)
599
  def GetMasterIP(self):
600
    """Get the IP of the master node for this cluster.
601

602
    @return: Master IP
603

604
    """
605
    return self._config_data.cluster.master_ip
606

    
607
  @locking.ssynchronized(_config_lock, shared=1)
608
  def GetMasterNetdev(self):
609
    """Get the master network device for this cluster.
610

611
    """
612
    return self._config_data.cluster.master_netdev
613

    
614
  @locking.ssynchronized(_config_lock, shared=1)
615
  def GetFileStorageDir(self):
616
    """Get the file storage dir for this cluster.
617

618
    """
619
    return self._config_data.cluster.file_storage_dir
620

    
621
  @locking.ssynchronized(_config_lock, shared=1)
622
  def GetHypervisorType(self):
623
    """Get the hypervisor type for this cluster.
624

625
    """
626
    return self._config_data.cluster.default_hypervisor
627

    
628
  @locking.ssynchronized(_config_lock, shared=1)
629
  def GetHostKey(self):
630
    """Return the rsa hostkey from the config.
631

632
    @rtype: string
633
    @return: the rsa hostkey
634

635
    """
636
    return self._config_data.cluster.rsahostkeypub
637

    
638
  @locking.ssynchronized(_config_lock)
639
  def AddInstance(self, instance):
640
    """Add an instance to the config.
641

642
    This should be used after creating a new instance.
643

644
    @type instance: L{objects.Instance}
645
    @param instance: the instance object
646

647
    """
648
    if not isinstance(instance, objects.Instance):
649
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
650

    
651
    if instance.disk_template != constants.DT_DISKLESS:
652
      all_lvs = instance.MapLVsByNode()
653
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
654

    
655
    instance.serial_no = 1
656
    self._config_data.instances[instance.name] = instance
657
    self._config_data.cluster.serial_no += 1
658
    self._UnlockedReleaseDRBDMinors(instance.name)
659
    self._WriteConfig()
660

    
661
  def _SetInstanceStatus(self, instance_name, status):
662
    """Set the instance's status to a given value.
663

664
    """
665
    assert isinstance(status, bool), \
666
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
667

    
668
    if instance_name not in self._config_data.instances:
669
      raise errors.ConfigurationError("Unknown instance '%s'" %
670
                                      instance_name)
671
    instance = self._config_data.instances[instance_name]
672
    if instance.admin_up != status:
673
      instance.admin_up = status
674
      instance.serial_no += 1
675
      self._WriteConfig()
676

    
677
  @locking.ssynchronized(_config_lock)
678
  def MarkInstanceUp(self, instance_name):
679
    """Mark the instance status to up in the config.
680

681
    """
682
    self._SetInstanceStatus(instance_name, True)
683

    
684
  @locking.ssynchronized(_config_lock)
685
  def RemoveInstance(self, instance_name):
686
    """Remove the instance from the configuration.
687

688
    """
689
    if instance_name not in self._config_data.instances:
690
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
691
    del self._config_data.instances[instance_name]
692
    self._config_data.cluster.serial_no += 1
693
    self._WriteConfig()
694

    
695
  @locking.ssynchronized(_config_lock)
696
  def RenameInstance(self, old_name, new_name):
697
    """Rename an instance.
698

699
    This needs to be done in ConfigWriter and not by RemoveInstance
700
    combined with AddInstance as only we can guarantee an atomic
701
    rename.
702

703
    """
704
    if old_name not in self._config_data.instances:
705
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
706
    inst = self._config_data.instances[old_name]
707
    del self._config_data.instances[old_name]
708
    inst.name = new_name
709

    
710
    for disk in inst.disks:
711
      if disk.dev_type == constants.LD_FILE:
712
        # rename the file paths in logical and physical id
713
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
714
        disk.physical_id = disk.logical_id = (disk.logical_id[0],
715
                                              os.path.join(file_storage_dir,
716
                                                           inst.name,
717
                                                           disk.iv_name))
718

    
719
    self._config_data.instances[inst.name] = inst
720
    self._WriteConfig()
721

    
722
  @locking.ssynchronized(_config_lock)
723
  def MarkInstanceDown(self, instance_name):
724
    """Mark the status of an instance to down in the configuration.
725

726
    """
727
    self._SetInstanceStatus(instance_name, False)
728

    
729
  def _UnlockedGetInstanceList(self):
730
    """Get the list of instances.
731

732
    This function is for internal use, when the config lock is already held.
733

734
    """
735
    return self._config_data.instances.keys()
736

    
737
  @locking.ssynchronized(_config_lock, shared=1)
738
  def GetInstanceList(self):
739
    """Get the list of instances.
740

741
    @return: array of instances, ex. ['instance2.example.com',
742
        'instance1.example.com']
743

744
    """
745
    return self._UnlockedGetInstanceList()
746

    
747
  @locking.ssynchronized(_config_lock, shared=1)
748
  def ExpandInstanceName(self, short_name):
749
    """Attempt to expand an incomplete instance name.
750

751
    """
752
    return utils.MatchNameComponent(short_name,
753
                                    self._config_data.instances.keys())
754

    
755
  def _UnlockedGetInstanceInfo(self, instance_name):
756
    """Returns informations about an instance.
757

758
    This function is for internal use, when the config lock is already held.
759

760
    """
761
    if instance_name not in self._config_data.instances:
762
      return None
763

    
764
    return self._config_data.instances[instance_name]
765

    
766
  @locking.ssynchronized(_config_lock, shared=1)
767
  def GetInstanceInfo(self, instance_name):
768
    """Returns informations about an instance.
769

770
    It takes the information from the configuration file. Other informations of
771
    an instance are taken from the live systems.
772

773
    @param instance_name: name of the instance, e.g.
774
        I{instance1.example.com}
775

776
    @rtype: L{objects.Instance}
777
    @return: the instance object
778

779
    """
780
    return self._UnlockedGetInstanceInfo(instance_name)
781

    
782
  @locking.ssynchronized(_config_lock, shared=1)
783
  def GetAllInstancesInfo(self):
784
    """Get the configuration of all instances.
785

786
    @rtype: dict
787
    @returns: dict of (instance, instance_info), where instance_info is what
788
              would GetInstanceInfo return for the node
789

790
    """
791
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
792
                    for instance in self._UnlockedGetInstanceList()])
793
    return my_dict
794

    
795
  @locking.ssynchronized(_config_lock)
796
  def AddNode(self, node):
797
    """Add a node to the configuration.
798

799
    @type node: L{objects.Node}
800
    @param node: a Node instance
801

802
    """
803
    logging.info("Adding node %s to configuration" % node.name)
804

    
805
    node.serial_no = 1
806
    self._config_data.nodes[node.name] = node
807
    self._config_data.cluster.serial_no += 1
808
    self._WriteConfig()
809

    
810
  @locking.ssynchronized(_config_lock)
811
  def RemoveNode(self, node_name):
812
    """Remove a node from the configuration.
813

814
    """
815
    logging.info("Removing node %s from configuration" % node_name)
816

    
817
    if node_name not in self._config_data.nodes:
818
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
819

    
820
    del self._config_data.nodes[node_name]
821
    self._config_data.cluster.serial_no += 1
822
    self._WriteConfig()
823

    
824
  @locking.ssynchronized(_config_lock, shared=1)
825
  def ExpandNodeName(self, short_name):
826
    """Attempt to expand an incomplete instance name.
827

828
    """
829
    return utils.MatchNameComponent(short_name,
830
                                    self._config_data.nodes.keys())
831

    
832
  def _UnlockedGetNodeInfo(self, node_name):
833
    """Get the configuration of a node, as stored in the config.
834

835
    This function is for internal use, when the config lock is already
836
    held.
837

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

840
    @rtype: L{objects.Node}
841
    @return: the node object
842

843
    """
844
    if node_name not in self._config_data.nodes:
845
      return None
846

    
847
    return self._config_data.nodes[node_name]
848

    
849

    
850
  @locking.ssynchronized(_config_lock, shared=1)
851
  def GetNodeInfo(self, node_name):
852
    """Get the configuration of a node, as stored in the config.
853

854
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
855

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

858
    @rtype: L{objects.Node}
859
    @return: the node object
860

861
    """
862
    return self._UnlockedGetNodeInfo(node_name)
863

    
864
  def _UnlockedGetNodeList(self):
865
    """Return the list of nodes which are in the configuration.
866

867
    This function is for internal use, when the config lock is already
868
    held.
869

870
    @rtype: list
871

872
    """
873
    return self._config_data.nodes.keys()
874

    
875

    
876
  @locking.ssynchronized(_config_lock, shared=1)
877
  def GetNodeList(self):
878
    """Return the list of nodes which are in the configuration.
879

880
    """
881
    return self._UnlockedGetNodeList()
882

    
883
  @locking.ssynchronized(_config_lock, shared=1)
884
  def GetOnlineNodeList(self):
885
    """Return the list of nodes which are online.
886

887
    """
888
    all_nodes = [self._UnlockedGetNodeInfo(node)
889
                 for node in self._UnlockedGetNodeList()]
890
    return [node.name for node in all_nodes if not node.offline]
891

    
892
  @locking.ssynchronized(_config_lock, shared=1)
893
  def GetAllNodesInfo(self):
894
    """Get the configuration of all nodes.
895

896
    @rtype: dict
897
    @return: dict of (node, node_info), where node_info is what
898
              would GetNodeInfo return for the node
899

900
    """
901
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
902
                    for node in self._UnlockedGetNodeList()])
903
    return my_dict
904

    
905
  def _UnlockedGetMasterCandidateStats(self):
906
    """Get the number of current and maximum desired and possible candidates.
907

908
    @rtype: tuple
909
    @return: tuple of (current, desired and possible)
910

911
    """
912
    mc_now = mc_max = 0
913
    for node in self._config_data.nodes.itervalues():
914
      if not (node.offline or node.drained):
915
        mc_max += 1
916
      if node.master_candidate:
917
        mc_now += 1
918
    mc_max = min(mc_max, self._config_data.cluster.candidate_pool_size)
919
    return (mc_now, mc_max)
920

    
921
  @locking.ssynchronized(_config_lock, shared=1)
922
  def GetMasterCandidateStats(self):
923
    """Get the number of current and maximum possible candidates.
924

925
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
926

927
    @rtype: tuple
928
    @return: tuple of (current, max)
929

930
    """
931
    return self._UnlockedGetMasterCandidateStats()
932

    
933
  @locking.ssynchronized(_config_lock)
934
  def MaintainCandidatePool(self):
935
    """Try to grow the candidate pool to the desired size.
936

937
    @rtype: list
938
    @return: list with the adjusted nodes (L{objects.Node} instances)
939

940
    """
941
    mc_now, mc_max = self._UnlockedGetMasterCandidateStats()
942
    mod_list = []
943
    if mc_now < mc_max:
944
      node_list = self._config_data.nodes.keys()
945
      random.shuffle(node_list)
946
      for name in node_list:
947
        if mc_now >= mc_max:
948
          break
949
        node = self._config_data.nodes[name]
950
        if node.master_candidate or node.offline or node.drained:
951
          continue
952
        mod_list.append(node)
953
        node.master_candidate = True
954
        node.serial_no += 1
955
        mc_now += 1
956
      if mc_now != mc_max:
957
        # this should not happen
958
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
959
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
960
      if mod_list:
961
        self._config_data.cluster.serial_no += 1
962
        self._WriteConfig()
963

    
964
    return mod_list
965

    
966
  def _BumpSerialNo(self):
967
    """Bump up the serial number of the config.
968

969
    """
970
    self._config_data.serial_no += 1
971

    
972
  def _OpenConfig(self):
973
    """Read the config data from disk.
974

975
    """
976
    f = open(self._cfg_file, 'r')
977
    try:
978
      try:
979
        data = objects.ConfigData.FromDict(serializer.Load(f.read()))
980
      except Exception, err:
981
        raise errors.ConfigurationError(err)
982
    finally:
983
      f.close()
984

    
985
    # Make sure the configuration has the right version
986
    _ValidateConfig(data)
987

    
988
    if (not hasattr(data, 'cluster') or
989
        not hasattr(data.cluster, 'rsahostkeypub')):
990
      raise errors.ConfigurationError("Incomplete configuration"
991
                                      " (missing cluster.rsahostkeypub)")
992
    self._config_data = data
993
    # reset the last serial as -1 so that the next write will cause
994
    # ssconf update
995
    self._last_cluster_serial = -1
996

    
997
  def _DistributeConfig(self):
998
    """Distribute the configuration to the other nodes.
999

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

1003
    """
1004
    if self._offline:
1005
      return True
1006
    bad = False
1007

    
1008
    node_list = []
1009
    addr_list = []
1010
    myhostname = self._my_hostname
1011
    # we can skip checking whether _UnlockedGetNodeInfo returns None
1012
    # since the node list comes from _UnlocketGetNodeList, and we are
1013
    # called with the lock held, so no modifications should take place
1014
    # in between
1015
    for node_name in self._UnlockedGetNodeList():
1016
      if node_name == myhostname:
1017
        continue
1018
      node_info = self._UnlockedGetNodeInfo(node_name)
1019
      if not node_info.master_candidate:
1020
        continue
1021
      node_list.append(node_info.name)
1022
      addr_list.append(node_info.primary_ip)
1023

    
1024
    result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
1025
                                            address_list=addr_list)
1026
    for node in node_list:
1027
      if not result[node]:
1028
        logging.error("copy of file %s to node %s failed",
1029
                      self._cfg_file, node)
1030
        bad = True
1031
    return not bad
1032

    
1033
  def _WriteConfig(self, destination=None):
1034
    """Write the configuration data to persistent storage.
1035

1036
    """
1037
    config_errors = self._UnlockedVerifyConfig()
1038
    if config_errors:
1039
      raise errors.ConfigurationError("Configuration data is not"
1040
                                      " consistent: %s" %
1041
                                      (", ".join(config_errors)))
1042
    if destination is None:
1043
      destination = self._cfg_file
1044
    self._BumpSerialNo()
1045
    txt = serializer.Dump(self._config_data.ToDict())
1046
    dir_name, file_name = os.path.split(destination)
1047
    fd, name = tempfile.mkstemp('.newconfig', file_name, dir_name)
1048
    f = os.fdopen(fd, 'w')
1049
    try:
1050
      f.write(txt)
1051
      os.fsync(f.fileno())
1052
    finally:
1053
      f.close()
1054
    # we don't need to do os.close(fd) as f.close() did it
1055
    os.rename(name, destination)
1056
    self.write_count += 1
1057

    
1058
    # and redistribute the config file to master candidates
1059
    self._DistributeConfig()
1060

    
1061
    # Write ssconf files on all nodes (including locally)
1062
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
1063
      if not self._offline:
1064
        rpc.RpcRunner.call_write_ssconf_files(self._UnlockedGetNodeList(),
1065
                                              self._UnlockedGetSsconfValues())
1066
      self._last_cluster_serial = self._config_data.cluster.serial_no
1067

    
1068
  def _UnlockedGetSsconfValues(self):
1069
    """Return the values needed by ssconf.
1070

1071
    @rtype: dict
1072
    @return: a dictionary with keys the ssconf names and values their
1073
        associated value
1074

1075
    """
1076
    fn = "\n".join
1077
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1078
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
1079
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1080

    
1081
    instance_data = fn(instance_names)
1082
    off_data = fn(node.name for node in node_info if node.offline)
1083
    on_data = fn(node.name for node in node_info if not node.offline)
1084
    mc_data = fn(node.name for node in node_info if node.master_candidate)
1085
    node_data = fn(node_names)
1086

    
1087
    cluster = self._config_data.cluster
1088
    return {
1089
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
1090
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1091
      constants.SS_MASTER_CANDIDATES: mc_data,
1092
      constants.SS_MASTER_IP: cluster.master_ip,
1093
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
1094
      constants.SS_MASTER_NODE: cluster.master_node,
1095
      constants.SS_NODE_LIST: node_data,
1096
      constants.SS_OFFLINE_NODES: off_data,
1097
      constants.SS_ONLINE_NODES: on_data,
1098
      constants.SS_INSTANCE_LIST: instance_data,
1099
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1100
      }
1101

    
1102
  @locking.ssynchronized(_config_lock)
1103
  def InitConfig(self, version, cluster_config, master_node_config):
1104
    """Create the initial cluster configuration.
1105

1106
    It will contain the current node, which will also be the master
1107
    node, and no instances.
1108

1109
    @type version: int
1110
    @param version: Configuration version
1111
    @type cluster_config: objects.Cluster
1112
    @param cluster_config: Cluster configuration
1113
    @type master_node_config: objects.Node
1114
    @param master_node_config: Master node configuration
1115

1116
    """
1117
    nodes = {
1118
      master_node_config.name: master_node_config,
1119
      }
1120

    
1121
    self._config_data = objects.ConfigData(version=version,
1122
                                           cluster=cluster_config,
1123
                                           nodes=nodes,
1124
                                           instances={},
1125
                                           serial_no=1)
1126
    self._WriteConfig()
1127

    
1128
  @locking.ssynchronized(_config_lock, shared=1)
1129
  def GetVGName(self):
1130
    """Return the volume group name.
1131

1132
    """
1133
    return self._config_data.cluster.volume_group_name
1134

    
1135
  @locking.ssynchronized(_config_lock)
1136
  def SetVGName(self, vg_name):
1137
    """Set the volume group name.
1138

1139
    """
1140
    self._config_data.cluster.volume_group_name = vg_name
1141
    self._config_data.cluster.serial_no += 1
1142
    self._WriteConfig()
1143

    
1144
  @locking.ssynchronized(_config_lock, shared=1)
1145
  def GetDefBridge(self):
1146
    """Return the default bridge.
1147

1148
    """
1149
    return self._config_data.cluster.default_bridge
1150

    
1151
  @locking.ssynchronized(_config_lock, shared=1)
1152
  def GetMACPrefix(self):
1153
    """Return the mac prefix.
1154

1155
    """
1156
    return self._config_data.cluster.mac_prefix
1157

    
1158
  @locking.ssynchronized(_config_lock, shared=1)
1159
  def GetClusterInfo(self):
1160
    """Returns informations about the cluster
1161

1162
    @rtype: L{objects.Cluster}
1163
    @return: the cluster object
1164

1165
    """
1166
    return self._config_data.cluster
1167

    
1168
  @locking.ssynchronized(_config_lock)
1169
  def Update(self, target):
1170
    """Notify function to be called after updates.
1171

1172
    This function must be called when an object (as returned by
1173
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
1174
    caller wants the modifications saved to the backing store. Note
1175
    that all modified objects will be saved, but the target argument
1176
    is the one the caller wants to ensure that it's saved.
1177

1178
    @param target: an instance of either L{objects.Cluster},
1179
        L{objects.Node} or L{objects.Instance} which is existing in
1180
        the cluster
1181

1182
    """
1183
    if self._config_data is None:
1184
      raise errors.ProgrammerError("Configuration file not read,"
1185
                                   " cannot save.")
1186
    update_serial = False
1187
    if isinstance(target, objects.Cluster):
1188
      test = target == self._config_data.cluster
1189
    elif isinstance(target, objects.Node):
1190
      test = target in self._config_data.nodes.values()
1191
      update_serial = True
1192
    elif isinstance(target, objects.Instance):
1193
      test = target in self._config_data.instances.values()
1194
    else:
1195
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
1196
                                   " ConfigWriter.Update" % type(target))
1197
    if not test:
1198
      raise errors.ConfigurationError("Configuration updated since object"
1199
                                      " has been read or unknown object")
1200
    target.serial_no += 1
1201

    
1202
    if update_serial:
1203
      # for node updates, we need to increase the cluster serial too
1204
      self._config_data.cluster.serial_no += 1
1205

    
1206
    if isinstance(target, objects.Instance):
1207
      self._UnlockedReleaseDRBDMinors(target.name)
1208

    
1209
    self._WriteConfig()