Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 32388e6d

History | View | Annotate | Download (35.1 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
  @locking.ssynchronized(_config_lock, shared=1)
231
  def VerifyConfig(self):
232
    """Verify function.
233

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

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

    
269
    # cluster-wide pool of free ports
270
    for free_port in data.cluster.tcpudp_port_pool:
271
      if free_port not in ports:
272
        ports[free_port] = []
273
      ports[free_port].append(("cluster", "port marked as free"))
274

    
275
    # compute tcp/udp duplicate ports
276
    keys = ports.keys()
277
    keys.sort()
278
    for pnum in keys:
279
      pdata = ports[pnum]
280
      if len(pdata) > 1:
281
        txt = ", ".join(["%s/%s" % val for val in pdata])
282
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
283

    
284
    # highest used tcp port check
285
    if keys:
286
      if keys[-1] > data.cluster.highest_used_port:
287
        result.append("Highest used port mismatch, saved %s, computed %s" %
288
                      (data.cluster.highest_used_port, keys[-1]))
289

    
290
    if not data.nodes[data.cluster.master_node].master_candidate:
291
      result.append("Master node is not a master candidate")
292

    
293
    mc_now, mc_max = self._UnlockedGetMasterCandidateStats()
294
    if mc_now < mc_max:
295
      result.append("Not enough master candidates: actual %d, target %d" %
296
                    (mc_now, mc_max))
297

    
298
    return result
299

    
300
  def _UnlockedSetDiskID(self, disk, node_name):
301
    """Convert the unique ID to the ID needed on the target nodes.
302

303
    This is used only for drbd, which needs ip/port configuration.
304

305
    The routine descends down and updates its children also, because
306
    this helps when the only the top device is passed to the remote
307
    node.
308

309
    This function is for internal use, when the config lock is already held.
310

311
    """
312
    if disk.children:
313
      for child in disk.children:
314
        self._UnlockedSetDiskID(child, node_name)
315

    
316
    if disk.logical_id is None and disk.physical_id is not None:
317
      return
318
    if disk.dev_type == constants.LD_DRBD8:
319
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
320
      if node_name not in (pnode, snode):
321
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
322
                                        node_name)
323
      pnode_info = self._UnlockedGetNodeInfo(pnode)
324
      snode_info = self._UnlockedGetNodeInfo(snode)
325
      if pnode_info is None or snode_info is None:
326
        raise errors.ConfigurationError("Can't find primary or secondary node"
327
                                        " for %s" % str(disk))
328
      p_data = (pnode_info.secondary_ip, port)
329
      s_data = (snode_info.secondary_ip, port)
330
      if pnode == node_name:
331
        disk.physical_id = p_data + s_data + (pminor, secret)
332
      else: # it must be secondary, we tested above
333
        disk.physical_id = s_data + p_data + (sminor, secret)
334
    else:
335
      disk.physical_id = disk.logical_id
336
    return
337

    
338
  @locking.ssynchronized(_config_lock)
339
  def SetDiskID(self, disk, node_name):
340
    """Convert the unique ID to the ID needed on the target nodes.
341

342
    This is used only for drbd, which needs ip/port configuration.
343

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

348
    """
349
    return self._UnlockedSetDiskID(disk, node_name)
350

    
351
  @locking.ssynchronized(_config_lock)
352
  def AddTcpUdpPort(self, port):
353
    """Adds a new port to the available port pool.
354

355
    """
356
    if not isinstance(port, int):
357
      raise errors.ProgrammerError("Invalid type passed for port")
358

    
359
    self._config_data.cluster.tcpudp_port_pool.add(port)
360
    self._WriteConfig()
361

    
362
  @locking.ssynchronized(_config_lock, shared=1)
363
  def GetPortList(self):
364
    """Returns a copy of the current port list.
365

366
    """
367
    return self._config_data.cluster.tcpudp_port_pool.copy()
368

    
369
  @locking.ssynchronized(_config_lock)
370
  def AllocatePort(self):
371
    """Allocate a port.
372

373
    The port will be taken from the available port pool or from the
374
    default port range (and in this case we increase
375
    highest_used_port).
376

377
    """
378
    # If there are TCP/IP ports configured, we use them first.
379
    if self._config_data.cluster.tcpudp_port_pool:
380
      port = self._config_data.cluster.tcpudp_port_pool.pop()
381
    else:
382
      port = self._config_data.cluster.highest_used_port + 1
383
      if port >= constants.LAST_DRBD_PORT:
384
        raise errors.ConfigurationError("The highest used port is greater"
385
                                        " than %s. Aborting." %
386
                                        constants.LAST_DRBD_PORT)
387
      self._config_data.cluster.highest_used_port = port
388

    
389
    self._WriteConfig()
390
    return port
391

    
392
  def _UnlockedComputeDRBDMap(self):
393
    """Compute the used DRBD minor/nodes.
394

395
    @return: dictionary of node_name: dict of minor: instance_name;
396
        the returned dict will have all the nodes in it (even if with
397
        an empty list).
398

399
    """
400
    def _AppendUsedPorts(instance_name, disk, used):
401
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
402
        nodeA, nodeB, dummy, minorA, minorB = disk.logical_id[:5]
403
        for node, port in ((nodeA, minorA), (nodeB, minorB)):
404
          assert node in used, "Instance node not found in node list"
405
          if port in used[node]:
406
            raise errors.ProgrammerError("DRBD minor already used:"
407
                                         " %s/%s, %s/%s" %
408
                                         (node, port, instance_name,
409
                                          used[node][port]))
410

    
411
          used[node][port] = instance_name
412
      if disk.children:
413
        for child in disk.children:
414
          _AppendUsedPorts(instance_name, child, used)
415

    
416
    my_dict = dict((node, {}) for node in self._config_data.nodes)
417
    for (node, minor), instance in self._temporary_drbds.iteritems():
418
      my_dict[node][minor] = instance
419
    for instance in self._config_data.instances.itervalues():
420
      for disk in instance.disks:
421
        _AppendUsedPorts(instance.name, disk, my_dict)
422
    return my_dict
423

    
424
  @locking.ssynchronized(_config_lock)
425
  def ComputeDRBDMap(self):
426
    """Compute the used DRBD minor/nodes.
427

428
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
429

430
    @return: dictionary of node_name: dict of minor: instance_name;
431
        the returned dict will have all the nodes in it (even if with
432
        an empty list).
433

434
    """
435
    return self._UnlockedComputeDRBDMap()
436

    
437
  @locking.ssynchronized(_config_lock)
438
  def AllocateDRBDMinor(self, nodes, instance):
439
    """Allocate a drbd minor.
440

441
    The free minor will be automatically computed from the existing
442
    devices. A node can be given multiple times in order to allocate
443
    multiple minors. The result is the list of minors, in the same
444
    order as the passed nodes.
445

446
    @type instance: string
447
    @param instance: the instance for which we allocate minors
448

449
    """
450
    assert isinstance(instance, basestring), \
451
           "Invalid argument passed to AllocateDRBDMinor"
452

    
453
    d_map = self._UnlockedComputeDRBDMap()
454
    result = []
455
    for nname in nodes:
456
      ndata = d_map[nname]
457
      if not ndata:
458
        # no minors used, we can start at 0
459
        result.append(0)
460
        ndata[0] = instance
461
        self._temporary_drbds[(nname, 0)] = instance
462
        continue
463
      keys = ndata.keys()
464
      keys.sort()
465
      ffree = utils.FirstFree(keys)
466
      if ffree is None:
467
        # return the next minor
468
        # TODO: implement high-limit check
469
        minor = keys[-1] + 1
470
      else:
471
        minor = ffree
472
      result.append(minor)
473
      ndata[minor] = instance
474
      assert (nname, minor) not in self._temporary_drbds, \
475
             "Attempt to reuse reserved DRBD minor"
476
      self._temporary_drbds[(nname, minor)] = instance
477
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
478
                  nodes, result)
479
    return result
480

    
481
  @locking.ssynchronized(_config_lock)
482
  def ReleaseDRBDMinors(self, instance):
483
    """Release temporary drbd minors allocated for a given instance.
484

485
    This should be called on both the error paths and on the success
486
    paths (after the instance has been added or updated).
487

488
    @type instance: string
489
    @param instance: the instance for which temporary minors should be
490
                     released
491

492
    """
493
    assert isinstance(instance, basestring), \
494
           "Invalid argument passed to ReleaseDRBDMinors"
495
    for key, name in self._temporary_drbds.items():
496
      if name == instance:
497
        del self._temporary_drbds[key]
498

    
499
  @locking.ssynchronized(_config_lock, shared=1)
500
  def GetConfigVersion(self):
501
    """Get the configuration version.
502

503
    @return: Config version
504

505
    """
506
    return self._config_data.version
507

    
508
  @locking.ssynchronized(_config_lock, shared=1)
509
  def GetClusterName(self):
510
    """Get cluster name.
511

512
    @return: Cluster name
513

514
    """
515
    return self._config_data.cluster.cluster_name
516

    
517
  @locking.ssynchronized(_config_lock, shared=1)
518
  def GetMasterNode(self):
519
    """Get the hostname of the master node for this cluster.
520

521
    @return: Master hostname
522

523
    """
524
    return self._config_data.cluster.master_node
525

    
526
  @locking.ssynchronized(_config_lock, shared=1)
527
  def GetMasterIP(self):
528
    """Get the IP of the master node for this cluster.
529

530
    @return: Master IP
531

532
    """
533
    return self._config_data.cluster.master_ip
534

    
535
  @locking.ssynchronized(_config_lock, shared=1)
536
  def GetMasterNetdev(self):
537
    """Get the master network device for this cluster.
538

539
    """
540
    return self._config_data.cluster.master_netdev
541

    
542
  @locking.ssynchronized(_config_lock, shared=1)
543
  def GetFileStorageDir(self):
544
    """Get the file storage dir for this cluster.
545

546
    """
547
    return self._config_data.cluster.file_storage_dir
548

    
549
  @locking.ssynchronized(_config_lock, shared=1)
550
  def GetHypervisorType(self):
551
    """Get the hypervisor type for this cluster.
552

553
    """
554
    return self._config_data.cluster.default_hypervisor
555

    
556
  @locking.ssynchronized(_config_lock, shared=1)
557
  def GetHostKey(self):
558
    """Return the rsa hostkey from the config.
559

560
    @rtype: string
561
    @return: the rsa hostkey
562

563
    """
564
    return self._config_data.cluster.rsahostkeypub
565

    
566
  @locking.ssynchronized(_config_lock)
567
  def AddInstance(self, instance):
568
    """Add an instance to the config.
569

570
    This should be used after creating a new instance.
571

572
    @type instance: L{objects.Instance}
573
    @param instance: the instance object
574

575
    """
576
    if not isinstance(instance, objects.Instance):
577
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
578

    
579
    if instance.disk_template != constants.DT_DISKLESS:
580
      all_lvs = instance.MapLVsByNode()
581
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
582

    
583
    instance.serial_no = 1
584
    self._config_data.instances[instance.name] = instance
585
    self._WriteConfig()
586

    
587
  def _SetInstanceStatus(self, instance_name, status):
588
    """Set the instance's status to a given value.
589

590
    """
591
    if status not in ("up", "down"):
592
      raise errors.ProgrammerError("Invalid status '%s' passed to"
593
                                   " ConfigWriter._SetInstanceStatus()" %
594
                                   status)
595

    
596
    if instance_name not in self._config_data.instances:
597
      raise errors.ConfigurationError("Unknown instance '%s'" %
598
                                      instance_name)
599
    instance = self._config_data.instances[instance_name]
600
    if instance.status != status:
601
      instance.status = status
602
      instance.serial_no += 1
603
      self._WriteConfig()
604

    
605
  @locking.ssynchronized(_config_lock)
606
  def MarkInstanceUp(self, instance_name):
607
    """Mark the instance status to up in the config.
608

609
    """
610
    self._SetInstanceStatus(instance_name, "up")
611

    
612
  @locking.ssynchronized(_config_lock)
613
  def RemoveInstance(self, instance_name):
614
    """Remove the instance from the configuration.
615

616
    """
617
    if instance_name not in self._config_data.instances:
618
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
619
    del self._config_data.instances[instance_name]
620
    self._WriteConfig()
621

    
622
  @locking.ssynchronized(_config_lock)
623
  def RenameInstance(self, old_name, new_name):
624
    """Rename an instance.
625

626
    This needs to be done in ConfigWriter and not by RemoveInstance
627
    combined with AddInstance as only we can guarantee an atomic
628
    rename.
629

630
    """
631
    if old_name not in self._config_data.instances:
632
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
633
    inst = self._config_data.instances[old_name]
634
    del self._config_data.instances[old_name]
635
    inst.name = new_name
636

    
637
    for disk in inst.disks:
638
      if disk.dev_type == constants.LD_FILE:
639
        # rename the file paths in logical and physical id
640
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
641
        disk.physical_id = disk.logical_id = (disk.logical_id[0],
642
                                              os.path.join(file_storage_dir,
643
                                                           inst.name,
644
                                                           disk.iv_name))
645

    
646
    self._config_data.instances[inst.name] = inst
647
    self._WriteConfig()
648

    
649
  @locking.ssynchronized(_config_lock)
650
  def MarkInstanceDown(self, instance_name):
651
    """Mark the status of an instance to down in the configuration.
652

653
    """
654
    self._SetInstanceStatus(instance_name, "down")
655

    
656
  def _UnlockedGetInstanceList(self):
657
    """Get the list of instances.
658

659
    This function is for internal use, when the config lock is already held.
660

661
    """
662
    return self._config_data.instances.keys()
663

    
664
  @locking.ssynchronized(_config_lock, shared=1)
665
  def GetInstanceList(self):
666
    """Get the list of instances.
667

668
    @return: array of instances, ex. ['instance2.example.com',
669
        'instance1.example.com']
670

671
    """
672
    return self._UnlockedGetInstanceList()
673

    
674
  @locking.ssynchronized(_config_lock, shared=1)
675
  def ExpandInstanceName(self, short_name):
676
    """Attempt to expand an incomplete instance name.
677

678
    """
679
    return utils.MatchNameComponent(short_name,
680
                                    self._config_data.instances.keys())
681

    
682
  def _UnlockedGetInstanceInfo(self, instance_name):
683
    """Returns informations about an instance.
684

685
    This function is for internal use, when the config lock is already held.
686

687
    """
688
    if instance_name not in self._config_data.instances:
689
      return None
690

    
691
    return self._config_data.instances[instance_name]
692

    
693
  @locking.ssynchronized(_config_lock, shared=1)
694
  def GetInstanceInfo(self, instance_name):
695
    """Returns informations about an instance.
696

697
    It takes the information from the configuration file. Other informations of
698
    an instance are taken from the live systems.
699

700
    @param instance_name: name of the instance, e.g.
701
        I{instance1.example.com}
702

703
    @rtype: L{objects.Instance}
704
    @return: the instance object
705

706
    """
707
    return self._UnlockedGetInstanceInfo(instance_name)
708

    
709
  @locking.ssynchronized(_config_lock, shared=1)
710
  def GetAllInstancesInfo(self):
711
    """Get the configuration of all instances.
712

713
    @rtype: dict
714
    @returns: dict of (instance, instance_info), where instance_info is what
715
              would GetInstanceInfo return for the node
716

717
    """
718
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
719
                    for instance in self._UnlockedGetInstanceList()])
720
    return my_dict
721

    
722
  @locking.ssynchronized(_config_lock)
723
  def AddNode(self, node):
724
    """Add a node to the configuration.
725

726
    @type node: L{objects.Node}
727
    @param node: a Node instance
728

729
    """
730
    logging.info("Adding node %s to configuration" % node.name)
731

    
732
    node.serial_no = 1
733
    self._config_data.nodes[node.name] = node
734
    self._config_data.cluster.serial_no += 1
735
    self._WriteConfig()
736

    
737
  @locking.ssynchronized(_config_lock)
738
  def RemoveNode(self, node_name):
739
    """Remove a node from the configuration.
740

741
    """
742
    logging.info("Removing node %s from configuration" % node_name)
743

    
744
    if node_name not in self._config_data.nodes:
745
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
746

    
747
    del self._config_data.nodes[node_name]
748
    self._config_data.cluster.serial_no += 1
749
    self._WriteConfig()
750

    
751
  @locking.ssynchronized(_config_lock, shared=1)
752
  def ExpandNodeName(self, short_name):
753
    """Attempt to expand an incomplete instance name.
754

755
    """
756
    return utils.MatchNameComponent(short_name,
757
                                    self._config_data.nodes.keys())
758

    
759
  def _UnlockedGetNodeInfo(self, node_name):
760
    """Get the configuration of a node, as stored in the config.
761

762
    This function is for internal use, when the config lock is already
763
    held.
764

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

767
    @rtype: L{objects.Node}
768
    @return: the node object
769

770
    """
771
    if node_name not in self._config_data.nodes:
772
      return None
773

    
774
    return self._config_data.nodes[node_name]
775

    
776

    
777
  @locking.ssynchronized(_config_lock, shared=1)
778
  def GetNodeInfo(self, node_name):
779
    """Get the configuration of a node, as stored in the config.
780

781
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
782

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

785
    @rtype: L{objects.Node}
786
    @return: the node object
787

788
    """
789
    return self._UnlockedGetNodeInfo(node_name)
790

    
791
  def _UnlockedGetNodeList(self):
792
    """Return the list of nodes which are in the configuration.
793

794
    This function is for internal use, when the config lock is already
795
    held.
796

797
    @rtype: list
798

799
    """
800
    return self._config_data.nodes.keys()
801

    
802

    
803
  @locking.ssynchronized(_config_lock, shared=1)
804
  def GetNodeList(self):
805
    """Return the list of nodes which are in the configuration.
806

807
    """
808
    return self._UnlockedGetNodeList()
809

    
810
  @locking.ssynchronized(_config_lock, shared=1)
811
  def GetOnlineNodeList(self):
812
    """Return the list of nodes which are online.
813

814
    """
815
    all_nodes = [self._UnlockedGetNodeInfo(node)
816
                 for node in self._UnlockedGetNodeList()]
817
    return [node.name for node in all_nodes if not node.offline]
818

    
819
  @locking.ssynchronized(_config_lock, shared=1)
820
  def GetAllNodesInfo(self):
821
    """Get the configuration of all nodes.
822

823
    @rtype: dict
824
    @return: dict of (node, node_info), where node_info is what
825
              would GetNodeInfo return for the node
826

827
    """
828
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
829
                    for node in self._UnlockedGetNodeList()])
830
    return my_dict
831

    
832
  def _UnlockedGetMasterCandidateStats(self):
833
    """Get the number of current and maximum desired and possible candidates.
834

835
    @rtype: tuple
836
    @return: tuple of (current, desired and possible)
837

838
    """
839
    mc_now = mc_max = 0
840
    for node in self._config_data.nodes.itervalues():
841
      if not node.offline:
842
        mc_max += 1
843
      if node.master_candidate:
844
        mc_now += 1
845
    mc_max = min(mc_max, self._config_data.cluster.candidate_pool_size)
846
    return (mc_now, mc_max)
847

    
848
  @locking.ssynchronized(_config_lock, shared=1)
849
  def GetMasterCandidateStats(self):
850
    """Get the number of current and maximum possible candidates.
851

852
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
853

854
    @rtype: tuple
855
    @return: tuple of (current, max)
856

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

    
860
  @locking.ssynchronized(_config_lock)
861
  def MaintainCandidatePool(self):
862
    """Try to grow the candidate pool to the desired size.
863

864
    @rtype: list
865
    @return: list with the adjusted nodes (L{objects.Node} instances)
866

867
    """
868
    mc_now, mc_max = self._UnlockedGetMasterCandidateStats()
869
    mod_list = []
870
    if mc_now < mc_max:
871
      node_list = self._config_data.nodes.keys()
872
      random.shuffle(node_list)
873
      for name in node_list:
874
        if mc_now >= mc_max:
875
          break
876
        node = self._config_data.nodes[name]
877
        if node.master_candidate or node.offline:
878
          continue
879
        mod_list.append(node)
880
        node.master_candidate = True
881
        node.serial_no += 1
882
        mc_now += 1
883
      if mc_now != mc_max:
884
        # this should not happen
885
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
886
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
887
      if mod_list:
888
        self._config_data.cluster.serial_no += 1
889
        self._WriteConfig()
890

    
891
    return mod_list
892

    
893
  def _BumpSerialNo(self):
894
    """Bump up the serial number of the config.
895

896
    """
897
    self._config_data.serial_no += 1
898

    
899
  def _OpenConfig(self):
900
    """Read the config data from disk.
901

902
    """
903
    f = open(self._cfg_file, 'r')
904
    try:
905
      try:
906
        data = objects.ConfigData.FromDict(serializer.Load(f.read()))
907
      except Exception, err:
908
        raise errors.ConfigurationError(err)
909
    finally:
910
      f.close()
911

    
912
    # Make sure the configuration has the right version
913
    _ValidateConfig(data)
914

    
915
    if (not hasattr(data, 'cluster') or
916
        not hasattr(data.cluster, 'rsahostkeypub')):
917
      raise errors.ConfigurationError("Incomplete configuration"
918
                                      " (missing cluster.rsahostkeypub)")
919
    self._config_data = data
920
    # reset the last serial as -1 so that the next write will cause
921
    # ssconf update
922
    self._last_cluster_serial = -1
923

    
924
  def _DistributeConfig(self):
925
    """Distribute the configuration to the other nodes.
926

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

930
    """
931
    if self._offline:
932
      return True
933
    bad = False
934

    
935
    node_list = []
936
    addr_list = []
937
    myhostname = self._my_hostname
938
    # we can skip checking whether _UnlockedGetNodeInfo returns None
939
    # since the node list comes from _UnlocketGetNodeList, and we are
940
    # called with the lock held, so no modifications should take place
941
    # in between
942
    for node_name in self._UnlockedGetNodeList():
943
      if node_name == myhostname:
944
        continue
945
      node_info = self._UnlockedGetNodeInfo(node_name)
946
      if not node_info.master_candidate:
947
        continue
948
      node_list.append(node_info.name)
949
      addr_list.append(node_info.primary_ip)
950

    
951
    result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
952
                                            address_list=addr_list)
953
    for node in node_list:
954
      if not result[node]:
955
        logging.error("copy of file %s to node %s failed",
956
                      self._cfg_file, node)
957
        bad = True
958
    return not bad
959

    
960
  def _WriteConfig(self, destination=None):
961
    """Write the configuration data to persistent storage.
962

963
    """
964
    if destination is None:
965
      destination = self._cfg_file
966
    self._BumpSerialNo()
967
    txt = serializer.Dump(self._config_data.ToDict())
968
    dir_name, file_name = os.path.split(destination)
969
    fd, name = tempfile.mkstemp('.newconfig', file_name, dir_name)
970
    f = os.fdopen(fd, 'w')
971
    try:
972
      f.write(txt)
973
      os.fsync(f.fileno())
974
    finally:
975
      f.close()
976
    # we don't need to do os.close(fd) as f.close() did it
977
    os.rename(name, destination)
978
    self.write_count += 1
979

    
980
    # and redistribute the config file to master candidates
981
    self._DistributeConfig()
982

    
983
    # Write ssconf files on all nodes (including locally)
984
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
985
      if not self._offline:
986
        rpc.RpcRunner.call_write_ssconf_files(self._UnlockedGetNodeList(),
987
                                              self._UnlockedGetSsconfValues())
988
      self._last_cluster_serial = self._config_data.cluster.serial_no
989

    
990
  def _UnlockedGetSsconfValues(self):
991
    """Return the values needed by ssconf.
992

993
    @rtype: dict
994
    @return: a dictionary with keys the ssconf names and values their
995
        associated value
996

997
    """
998
    fn = "\n".join
999
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
1000
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1001

    
1002
    off_data = fn(node.name for node in node_info if node.offline)
1003
    mc_data = fn(node.name for node in node_info if node.master_candidate)
1004
    node_data = fn(node_names)
1005

    
1006
    cluster = self._config_data.cluster
1007
    return {
1008
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
1009
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1010
      constants.SS_MASTER_CANDIDATES: mc_data,
1011
      constants.SS_MASTER_IP: cluster.master_ip,
1012
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
1013
      constants.SS_MASTER_NODE: cluster.master_node,
1014
      constants.SS_NODE_LIST: node_data,
1015
      constants.SS_OFFLINE_NODES: off_data,
1016
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1017
      }
1018

    
1019
  @locking.ssynchronized(_config_lock)
1020
  def InitConfig(self, version, cluster_config, master_node_config):
1021
    """Create the initial cluster configuration.
1022

1023
    It will contain the current node, which will also be the master
1024
    node, and no instances.
1025

1026
    @type version: int
1027
    @param version: Configuration version
1028
    @type cluster_config: objects.Cluster
1029
    @param cluster_config: Cluster configuration
1030
    @type master_node_config: objects.Node
1031
    @param master_node_config: Master node configuration
1032

1033
    """
1034
    nodes = {
1035
      master_node_config.name: master_node_config,
1036
      }
1037

    
1038
    self._config_data = objects.ConfigData(version=version,
1039
                                           cluster=cluster_config,
1040
                                           nodes=nodes,
1041
                                           instances={},
1042
                                           serial_no=1)
1043
    self._WriteConfig()
1044

    
1045
  @locking.ssynchronized(_config_lock, shared=1)
1046
  def GetVGName(self):
1047
    """Return the volume group name.
1048

1049
    """
1050
    return self._config_data.cluster.volume_group_name
1051

    
1052
  @locking.ssynchronized(_config_lock)
1053
  def SetVGName(self, vg_name):
1054
    """Set the volume group name.
1055

1056
    """
1057
    self._config_data.cluster.volume_group_name = vg_name
1058
    self._config_data.cluster.serial_no += 1
1059
    self._WriteConfig()
1060

    
1061
  @locking.ssynchronized(_config_lock, shared=1)
1062
  def GetDefBridge(self):
1063
    """Return the default bridge.
1064

1065
    """
1066
    return self._config_data.cluster.default_bridge
1067

    
1068
  @locking.ssynchronized(_config_lock, shared=1)
1069
  def GetMACPrefix(self):
1070
    """Return the mac prefix.
1071

1072
    """
1073
    return self._config_data.cluster.mac_prefix
1074

    
1075
  @locking.ssynchronized(_config_lock, shared=1)
1076
  def GetClusterInfo(self):
1077
    """Returns informations about the cluster
1078

1079
    @rtype: L{objects.Cluster}
1080
    @return: the cluster object
1081

1082
    """
1083
    return self._config_data.cluster
1084

    
1085
  @locking.ssynchronized(_config_lock)
1086
  def Update(self, target):
1087
    """Notify function to be called after updates.
1088

1089
    This function must be called when an object (as returned by
1090
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
1091
    caller wants the modifications saved to the backing store. Note
1092
    that all modified objects will be saved, but the target argument
1093
    is the one the caller wants to ensure that it's saved.
1094

1095
    @param target: an instance of either L{objects.Cluster},
1096
        L{objects.Node} or L{objects.Instance} which is existing in
1097
        the cluster
1098

1099
    """
1100
    if self._config_data is None:
1101
      raise errors.ProgrammerError("Configuration file not read,"
1102
                                   " cannot save.")
1103
    update_serial = False
1104
    if isinstance(target, objects.Cluster):
1105
      test = target == self._config_data.cluster
1106
    elif isinstance(target, objects.Node):
1107
      test = target in self._config_data.nodes.values()
1108
      update_serial = True
1109
    elif isinstance(target, objects.Instance):
1110
      test = target in self._config_data.instances.values()
1111
    else:
1112
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
1113
                                   " ConfigWriter.Update" % type(target))
1114
    if not test:
1115
      raise errors.ConfigurationError("Configuration updated since object"
1116
                                      " has been read or unknown object")
1117
    target.serial_no += 1
1118

    
1119
    if update_serial:
1120
      # for node updates, we need to increase the cluster serial too
1121
      self._config_data.cluster.serial_no += 1
1122

    
1123
    self._WriteConfig()