Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 6d2e83d5

History | View | Annotate | Download (34.8 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
    """
447
    d_map = self._UnlockedComputeDRBDMap()
448
    result = []
449
    for nname in nodes:
450
      ndata = d_map[nname]
451
      if not ndata:
452
        # no minors used, we can start at 0
453
        result.append(0)
454
        ndata[0] = instance
455
        self._temporary_drbds[(nname, 0)] = instance
456
        continue
457
      keys = ndata.keys()
458
      keys.sort()
459
      ffree = utils.FirstFree(keys)
460
      if ffree is None:
461
        # return the next minor
462
        # TODO: implement high-limit check
463
        minor = keys[-1] + 1
464
      else:
465
        minor = ffree
466
      result.append(minor)
467
      ndata[minor] = instance
468
      assert (nname, minor) not in self._temporary_drbds, \
469
             "Attempt to reuse reserved DRBD minor"
470
      self._temporary_drbds[(nname, minor)] = instance
471
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
472
                  nodes, result)
473
    return result
474

    
475
  @locking.ssynchronized(_config_lock)
476
  def ReleaseDRBDMinors(self, instance):
477
    """Release temporary drbd minors allocated for a given instance.
478

479
    This should be called on both the error paths and on the success
480
    paths (after the instance has been added or updated).
481

482
    @type instance: string
483
    @param instance: the instance for which temporary minors should be
484
                     released
485

486
    """
487
    for key, name in self._temporary_drbds.items():
488
      if name == instance:
489
        del self._temporary_drbds[key]
490

    
491
  @locking.ssynchronized(_config_lock, shared=1)
492
  def GetConfigVersion(self):
493
    """Get the configuration version.
494

495
    @return: Config version
496

497
    """
498
    return self._config_data.version
499

    
500
  @locking.ssynchronized(_config_lock, shared=1)
501
  def GetClusterName(self):
502
    """Get cluster name.
503

504
    @return: Cluster name
505

506
    """
507
    return self._config_data.cluster.cluster_name
508

    
509
  @locking.ssynchronized(_config_lock, shared=1)
510
  def GetMasterNode(self):
511
    """Get the hostname of the master node for this cluster.
512

513
    @return: Master hostname
514

515
    """
516
    return self._config_data.cluster.master_node
517

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

522
    @return: Master IP
523

524
    """
525
    return self._config_data.cluster.master_ip
526

    
527
  @locking.ssynchronized(_config_lock, shared=1)
528
  def GetMasterNetdev(self):
529
    """Get the master network device for this cluster.
530

531
    """
532
    return self._config_data.cluster.master_netdev
533

    
534
  @locking.ssynchronized(_config_lock, shared=1)
535
  def GetFileStorageDir(self):
536
    """Get the file storage dir for this cluster.
537

538
    """
539
    return self._config_data.cluster.file_storage_dir
540

    
541
  @locking.ssynchronized(_config_lock, shared=1)
542
  def GetHypervisorType(self):
543
    """Get the hypervisor type for this cluster.
544

545
    """
546
    return self._config_data.cluster.default_hypervisor
547

    
548
  @locking.ssynchronized(_config_lock, shared=1)
549
  def GetHostKey(self):
550
    """Return the rsa hostkey from the config.
551

552
    @rtype: string
553
    @return: the rsa hostkey
554

555
    """
556
    return self._config_data.cluster.rsahostkeypub
557

    
558
  @locking.ssynchronized(_config_lock)
559
  def AddInstance(self, instance):
560
    """Add an instance to the config.
561

562
    This should be used after creating a new instance.
563

564
    @type instance: L{objects.Instance}
565
    @param instance: the instance object
566

567
    """
568
    if not isinstance(instance, objects.Instance):
569
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
570

    
571
    if instance.disk_template != constants.DT_DISKLESS:
572
      all_lvs = instance.MapLVsByNode()
573
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
574

    
575
    instance.serial_no = 1
576
    self._config_data.instances[instance.name] = instance
577
    self._WriteConfig()
578

    
579
  def _SetInstanceStatus(self, instance_name, status):
580
    """Set the instance's status to a given value.
581

582
    """
583
    if status not in ("up", "down"):
584
      raise errors.ProgrammerError("Invalid status '%s' passed to"
585
                                   " ConfigWriter._SetInstanceStatus()" %
586
                                   status)
587

    
588
    if instance_name not in self._config_data.instances:
589
      raise errors.ConfigurationError("Unknown instance '%s'" %
590
                                      instance_name)
591
    instance = self._config_data.instances[instance_name]
592
    if instance.status != status:
593
      instance.status = status
594
      instance.serial_no += 1
595
      self._WriteConfig()
596

    
597
  @locking.ssynchronized(_config_lock)
598
  def MarkInstanceUp(self, instance_name):
599
    """Mark the instance status to up in the config.
600

601
    """
602
    self._SetInstanceStatus(instance_name, "up")
603

    
604
  @locking.ssynchronized(_config_lock)
605
  def RemoveInstance(self, instance_name):
606
    """Remove the instance from the configuration.
607

608
    """
609
    if instance_name not in self._config_data.instances:
610
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
611
    del self._config_data.instances[instance_name]
612
    self._WriteConfig()
613

    
614
  @locking.ssynchronized(_config_lock)
615
  def RenameInstance(self, old_name, new_name):
616
    """Rename an instance.
617

618
    This needs to be done in ConfigWriter and not by RemoveInstance
619
    combined with AddInstance as only we can guarantee an atomic
620
    rename.
621

622
    """
623
    if old_name not in self._config_data.instances:
624
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
625
    inst = self._config_data.instances[old_name]
626
    del self._config_data.instances[old_name]
627
    inst.name = new_name
628

    
629
    for disk in inst.disks:
630
      if disk.dev_type == constants.LD_FILE:
631
        # rename the file paths in logical and physical id
632
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
633
        disk.physical_id = disk.logical_id = (disk.logical_id[0],
634
                                              os.path.join(file_storage_dir,
635
                                                           inst.name,
636
                                                           disk.iv_name))
637

    
638
    self._config_data.instances[inst.name] = inst
639
    self._WriteConfig()
640

    
641
  @locking.ssynchronized(_config_lock)
642
  def MarkInstanceDown(self, instance_name):
643
    """Mark the status of an instance to down in the configuration.
644

645
    """
646
    self._SetInstanceStatus(instance_name, "down")
647

    
648
  def _UnlockedGetInstanceList(self):
649
    """Get the list of instances.
650

651
    This function is for internal use, when the config lock is already held.
652

653
    """
654
    return self._config_data.instances.keys()
655

    
656
  @locking.ssynchronized(_config_lock, shared=1)
657
  def GetInstanceList(self):
658
    """Get the list of instances.
659

660
    @return: array of instances, ex. ['instance2.example.com',
661
        'instance1.example.com']
662

663
    """
664
    return self._UnlockedGetInstanceList()
665

    
666
  @locking.ssynchronized(_config_lock, shared=1)
667
  def ExpandInstanceName(self, short_name):
668
    """Attempt to expand an incomplete instance name.
669

670
    """
671
    return utils.MatchNameComponent(short_name,
672
                                    self._config_data.instances.keys())
673

    
674
  def _UnlockedGetInstanceInfo(self, instance_name):
675
    """Returns informations about an instance.
676

677
    This function is for internal use, when the config lock is already held.
678

679
    """
680
    if instance_name not in self._config_data.instances:
681
      return None
682

    
683
    return self._config_data.instances[instance_name]
684

    
685
  @locking.ssynchronized(_config_lock, shared=1)
686
  def GetInstanceInfo(self, instance_name):
687
    """Returns informations about an instance.
688

689
    It takes the information from the configuration file. Other informations of
690
    an instance are taken from the live systems.
691

692
    @param instance_name: name of the instance, e.g.
693
        I{instance1.example.com}
694

695
    @rtype: L{objects.Instance}
696
    @return: the instance object
697

698
    """
699
    return self._UnlockedGetInstanceInfo(instance_name)
700

    
701
  @locking.ssynchronized(_config_lock, shared=1)
702
  def GetAllInstancesInfo(self):
703
    """Get the configuration of all instances.
704

705
    @rtype: dict
706
    @returns: dict of (instance, instance_info), where instance_info is what
707
              would GetInstanceInfo return for the node
708

709
    """
710
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
711
                    for instance in self._UnlockedGetInstanceList()])
712
    return my_dict
713

    
714
  @locking.ssynchronized(_config_lock)
715
  def AddNode(self, node):
716
    """Add a node to the configuration.
717

718
    @type node: L{objects.Node}
719
    @param node: a Node instance
720

721
    """
722
    logging.info("Adding node %s to configuration" % node.name)
723

    
724
    node.serial_no = 1
725
    self._config_data.nodes[node.name] = node
726
    self._config_data.cluster.serial_no += 1
727
    self._WriteConfig()
728

    
729
  @locking.ssynchronized(_config_lock)
730
  def RemoveNode(self, node_name):
731
    """Remove a node from the configuration.
732

733
    """
734
    logging.info("Removing node %s from configuration" % node_name)
735

    
736
    if node_name not in self._config_data.nodes:
737
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
738

    
739
    del self._config_data.nodes[node_name]
740
    self._config_data.cluster.serial_no += 1
741
    self._WriteConfig()
742

    
743
  @locking.ssynchronized(_config_lock, shared=1)
744
  def ExpandNodeName(self, short_name):
745
    """Attempt to expand an incomplete instance name.
746

747
    """
748
    return utils.MatchNameComponent(short_name,
749
                                    self._config_data.nodes.keys())
750

    
751
  def _UnlockedGetNodeInfo(self, node_name):
752
    """Get the configuration of a node, as stored in the config.
753

754
    This function is for internal use, when the config lock is already
755
    held.
756

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

759
    @rtype: L{objects.Node}
760
    @return: the node object
761

762
    """
763
    if node_name not in self._config_data.nodes:
764
      return None
765

    
766
    return self._config_data.nodes[node_name]
767

    
768

    
769
  @locking.ssynchronized(_config_lock, shared=1)
770
  def GetNodeInfo(self, node_name):
771
    """Get the configuration of a node, as stored in the config.
772

773
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
774

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

777
    @rtype: L{objects.Node}
778
    @return: the node object
779

780
    """
781
    return self._UnlockedGetNodeInfo(node_name)
782

    
783
  def _UnlockedGetNodeList(self):
784
    """Return the list of nodes which are in the configuration.
785

786
    This function is for internal use, when the config lock is already
787
    held.
788

789
    @rtype: list
790

791
    """
792
    return self._config_data.nodes.keys()
793

    
794

    
795
  @locking.ssynchronized(_config_lock, shared=1)
796
  def GetNodeList(self):
797
    """Return the list of nodes which are in the configuration.
798

799
    """
800
    return self._UnlockedGetNodeList()
801

    
802
  @locking.ssynchronized(_config_lock, shared=1)
803
  def GetOnlineNodeList(self):
804
    """Return the list of nodes which are online.
805

806
    """
807
    all_nodes = [self._UnlockedGetNodeInfo(node)
808
                 for node in self._UnlockedGetNodeList()]
809
    return [node.name for node in all_nodes if not node.offline]
810

    
811
  @locking.ssynchronized(_config_lock, shared=1)
812
  def GetAllNodesInfo(self):
813
    """Get the configuration of all nodes.
814

815
    @rtype: dict
816
    @return: dict of (node, node_info), where node_info is what
817
              would GetNodeInfo return for the node
818

819
    """
820
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
821
                    for node in self._UnlockedGetNodeList()])
822
    return my_dict
823

    
824
  def _UnlockedGetMasterCandidateStats(self):
825
    """Get the number of current and maximum desired and possible candidates.
826

827
    @rtype: tuple
828
    @return: tuple of (current, desired and possible)
829

830
    """
831
    mc_now = mc_max = 0
832
    for node in self._config_data.nodes.itervalues():
833
      if not node.offline:
834
        mc_max += 1
835
      if node.master_candidate:
836
        mc_now += 1
837
    mc_max = min(mc_max, self._config_data.cluster.candidate_pool_size)
838
    return (mc_now, mc_max)
839

    
840
  @locking.ssynchronized(_config_lock, shared=1)
841
  def GetMasterCandidateStats(self):
842
    """Get the number of current and maximum possible candidates.
843

844
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
845

846
    @rtype: tuple
847
    @return: tuple of (current, max)
848

849
    """
850
    return self._UnlockedGetMasterCandidateStats()
851

    
852
  @locking.ssynchronized(_config_lock)
853
  def MaintainCandidatePool(self):
854
    """Try to grow the candidate pool to the desired size.
855

856
    @rtype: list
857
    @return: list with the adjusted nodes (L{objects.Node} instances)
858

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

    
883
    return mod_list
884

    
885
  def _BumpSerialNo(self):
886
    """Bump up the serial number of the config.
887

888
    """
889
    self._config_data.serial_no += 1
890

    
891
  def _OpenConfig(self):
892
    """Read the config data from disk.
893

894
    """
895
    f = open(self._cfg_file, 'r')
896
    try:
897
      try:
898
        data = objects.ConfigData.FromDict(serializer.Load(f.read()))
899
      except Exception, err:
900
        raise errors.ConfigurationError(err)
901
    finally:
902
      f.close()
903

    
904
    # Make sure the configuration has the right version
905
    _ValidateConfig(data)
906

    
907
    if (not hasattr(data, 'cluster') or
908
        not hasattr(data.cluster, 'rsahostkeypub')):
909
      raise errors.ConfigurationError("Incomplete configuration"
910
                                      " (missing cluster.rsahostkeypub)")
911
    self._config_data = data
912
    # reset the last serial as -1 so that the next write will cause
913
    # ssconf update
914
    self._last_cluster_serial = -1
915

    
916
  def _DistributeConfig(self):
917
    """Distribute the configuration to the other nodes.
918

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

922
    """
923
    if self._offline:
924
      return True
925
    bad = False
926

    
927
    node_list = []
928
    addr_list = []
929
    myhostname = self._my_hostname
930
    # we can skip checking whether _UnlockedGetNodeInfo returns None
931
    # since the node list comes from _UnlocketGetNodeList, and we are
932
    # called with the lock held, so no modifications should take place
933
    # in between
934
    for node_name in self._UnlockedGetNodeList():
935
      if node_name == myhostname:
936
        continue
937
      node_info = self._UnlockedGetNodeInfo(node_name)
938
      if not node_info.master_candidate:
939
        continue
940
      node_list.append(node_info.name)
941
      addr_list.append(node_info.primary_ip)
942

    
943
    result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
944
                                            address_list=addr_list)
945
    for node in node_list:
946
      if not result[node]:
947
        logging.error("copy of file %s to node %s failed",
948
                      self._cfg_file, node)
949
        bad = True
950
    return not bad
951

    
952
  def _WriteConfig(self, destination=None):
953
    """Write the configuration data to persistent storage.
954

955
    """
956
    if destination is None:
957
      destination = self._cfg_file
958
    self._BumpSerialNo()
959
    txt = serializer.Dump(self._config_data.ToDict())
960
    dir_name, file_name = os.path.split(destination)
961
    fd, name = tempfile.mkstemp('.newconfig', file_name, dir_name)
962
    f = os.fdopen(fd, 'w')
963
    try:
964
      f.write(txt)
965
      os.fsync(f.fileno())
966
    finally:
967
      f.close()
968
    # we don't need to do os.close(fd) as f.close() did it
969
    os.rename(name, destination)
970
    self.write_count += 1
971

    
972
    # and redistribute the config file to master candidates
973
    self._DistributeConfig()
974

    
975
    # Write ssconf files on all nodes (including locally)
976
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
977
      if not self._offline:
978
        rpc.RpcRunner.call_write_ssconf_files(self._UnlockedGetNodeList(),
979
                                              self._UnlockedGetSsconfValues())
980
      self._last_cluster_serial = self._config_data.cluster.serial_no
981

    
982
  def _UnlockedGetSsconfValues(self):
983
    """Return the values needed by ssconf.
984

985
    @rtype: dict
986
    @return: a dictionary with keys the ssconf names and values their
987
        associated value
988

989
    """
990
    fn = "\n".join
991
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
992
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
993

    
994
    off_data = fn(node.name for node in node_info if node.offline)
995
    mc_data = fn(node.name for node in node_info if node.master_candidate)
996
    node_data = fn(node_names)
997

    
998
    cluster = self._config_data.cluster
999
    return {
1000
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
1001
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1002
      constants.SS_MASTER_CANDIDATES: mc_data,
1003
      constants.SS_MASTER_IP: cluster.master_ip,
1004
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
1005
      constants.SS_MASTER_NODE: cluster.master_node,
1006
      constants.SS_NODE_LIST: node_data,
1007
      constants.SS_OFFLINE_NODES: off_data,
1008
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1009
      }
1010

    
1011
  @locking.ssynchronized(_config_lock)
1012
  def InitConfig(self, version, cluster_config, master_node_config):
1013
    """Create the initial cluster configuration.
1014

1015
    It will contain the current node, which will also be the master
1016
    node, and no instances.
1017

1018
    @type version: int
1019
    @param version: Configuration version
1020
    @type cluster_config: objects.Cluster
1021
    @param cluster_config: Cluster configuration
1022
    @type master_node_config: objects.Node
1023
    @param master_node_config: Master node configuration
1024

1025
    """
1026
    nodes = {
1027
      master_node_config.name: master_node_config,
1028
      }
1029

    
1030
    self._config_data = objects.ConfigData(version=version,
1031
                                           cluster=cluster_config,
1032
                                           nodes=nodes,
1033
                                           instances={},
1034
                                           serial_no=1)
1035
    self._WriteConfig()
1036

    
1037
  @locking.ssynchronized(_config_lock, shared=1)
1038
  def GetVGName(self):
1039
    """Return the volume group name.
1040

1041
    """
1042
    return self._config_data.cluster.volume_group_name
1043

    
1044
  @locking.ssynchronized(_config_lock)
1045
  def SetVGName(self, vg_name):
1046
    """Set the volume group name.
1047

1048
    """
1049
    self._config_data.cluster.volume_group_name = vg_name
1050
    self._config_data.cluster.serial_no += 1
1051
    self._WriteConfig()
1052

    
1053
  @locking.ssynchronized(_config_lock, shared=1)
1054
  def GetDefBridge(self):
1055
    """Return the default bridge.
1056

1057
    """
1058
    return self._config_data.cluster.default_bridge
1059

    
1060
  @locking.ssynchronized(_config_lock, shared=1)
1061
  def GetMACPrefix(self):
1062
    """Return the mac prefix.
1063

1064
    """
1065
    return self._config_data.cluster.mac_prefix
1066

    
1067
  @locking.ssynchronized(_config_lock, shared=1)
1068
  def GetClusterInfo(self):
1069
    """Returns informations about the cluster
1070

1071
    @rtype: L{objects.Cluster}
1072
    @return: the cluster object
1073

1074
    """
1075
    return self._config_data.cluster
1076

    
1077
  @locking.ssynchronized(_config_lock)
1078
  def Update(self, target):
1079
    """Notify function to be called after updates.
1080

1081
    This function must be called when an object (as returned by
1082
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
1083
    caller wants the modifications saved to the backing store. Note
1084
    that all modified objects will be saved, but the target argument
1085
    is the one the caller wants to ensure that it's saved.
1086

1087
    @param target: an instance of either L{objects.Cluster},
1088
        L{objects.Node} or L{objects.Instance} which is existing in
1089
        the cluster
1090

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

    
1111
    if update_serial:
1112
      # for node updates, we need to increase the cluster serial too
1113
      self._config_data.cluster.serial_no += 1
1114

    
1115
    self._WriteConfig()