Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ ae5849b5

History | View | Annotate | Download (31.2 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
from ganeti import ssconf
47

    
48

    
49
_config_lock = locking.SharedLock()
50

    
51

    
52
def ValidateConfig():
53
  sstore = ssconf.SimpleStore()
54

    
55
  if sstore.GetConfigVersion() != constants.CONFIG_VERSION:
56
    raise errors.ConfigurationError("Cluster configuration version"
57
                                    " mismatch, got %s instead of %s" %
58
                                    (sstore.GetConfigVersion(),
59
                                     constants.CONFIG_VERSION))
60

    
61

    
62
class ConfigWriter:
63
  """The interface to the cluster configuration.
64

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

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

91
    """
92
    return os.path.exists(constants.CLUSTER_CONF_FILE)
93

    
94
  @locking.ssynchronized(_config_lock, shared=1)
95
  def GenerateMAC(self):
96
    """Generate a MAC for an instance.
97

98
    This should check the current instances for duplicates.
99

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

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

121
    This only checks instances managed by this cluster, it does not
122
    check for potential collisions elsewhere.
123

124
    """
125
    self._OpenConfig()
126
    all_macs = self._AllMACs()
127
    return mac in all_macs
128

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

133
    This checks the current disks for duplicates.
134

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

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

151
    """
152
    self._OpenConfig()
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
    Args:
168
      - exceptions: a list with some other names which should be checked
169
                    for uniqueness (used for example when you want to get
170
                    more than one id at one time without adding each one in
171
                    turn to the config file
172

173
    Returns: the unique id as a string
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
    """
198
    self._OpenConfig()
199

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

    
205
    return result
206

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

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

    
219
    result = []
220
    for instance in self._config_data.instances.values():
221
      for disk in instance.disks:
222
        helper(disk, result)
223

    
224
    return result
225

    
226
  @locking.ssynchronized(_config_lock, shared=1)
227
  def VerifyConfig(self):
228
    """Stub verify function.
229
    """
230
    self._OpenConfig()
231

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

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

    
266
    # cluster-wide pool of free ports
267
    for free_port in self._config_data.cluster.tcpudp_port_pool:
268
      if free_port not in ports:
269
        ports[free_port] = []
270
      ports[free_port].append(("cluster", "port marked as free"))
271

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

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

    
288
    return result
289

    
290
  def _UnlockedSetDiskID(self, disk, node_name):
291
    """Convert the unique ID to the ID needed on the target nodes.
292

293
    This is used only for drbd, which needs ip/port configuration.
294

295
    The routine descends down and updates its children also, because
296
    this helps when the only the top device is passed to the remote
297
    node.
298

299
    This function is for internal use, when the config lock is already held.
300

301
    """
302
    if disk.children:
303
      for child in disk.children:
304
        self._UnlockedSetDiskID(child, node_name)
305

    
306
    if disk.logical_id is None and disk.physical_id is not None:
307
      return
308
    if disk.dev_type == constants.LD_DRBD8:
309
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
310
      if node_name not in (pnode, snode):
311
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
312
                                        node_name)
313
      pnode_info = self._UnlockedGetNodeInfo(pnode)
314
      snode_info = self._UnlockedGetNodeInfo(snode)
315
      if pnode_info is None or snode_info is None:
316
        raise errors.ConfigurationError("Can't find primary or secondary node"
317
                                        " for %s" % str(disk))
318
      p_data = (pnode_info.secondary_ip, port)
319
      s_data = (snode_info.secondary_ip, port)
320
      if pnode == node_name:
321
        disk.physical_id = p_data + s_data + (pminor, secret)
322
      else: # it must be secondary, we tested above
323
        disk.physical_id = s_data + p_data + (sminor, secret)
324
    else:
325
      disk.physical_id = disk.logical_id
326
    return
327

    
328
  @locking.ssynchronized(_config_lock)
329
  def SetDiskID(self, disk, node_name):
330
    """Convert the unique ID to the ID needed on the target nodes.
331

332
    This is used only for drbd, which needs ip/port configuration.
333

334
    The routine descends down and updates its children also, because
335
    this helps when the only the top device is passed to the remote
336
    node.
337

338
    """
339
    return self._UnlockedSetDiskID(disk, node_name)
340

    
341
  @locking.ssynchronized(_config_lock)
342
  def AddTcpUdpPort(self, port):
343
    """Adds a new port to the available port pool.
344

345
    """
346
    if not isinstance(port, int):
347
      raise errors.ProgrammerError("Invalid type passed for port")
348

    
349
    self._OpenConfig()
350
    self._config_data.cluster.tcpudp_port_pool.add(port)
351
    self._WriteConfig()
352

    
353
  @locking.ssynchronized(_config_lock, shared=1)
354
  def GetPortList(self):
355
    """Returns a copy of the current port list.
356

357
    """
358
    self._OpenConfig()
359
    return self._config_data.cluster.tcpudp_port_pool.copy()
360

    
361
  @locking.ssynchronized(_config_lock)
362
  def AllocatePort(self):
363
    """Allocate a port.
364

365
    The port will be taken from the available port pool or from the
366
    default port range (and in this case we increase
367
    highest_used_port).
368

369
    """
370
    self._OpenConfig()
371

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

    
383
    self._WriteConfig()
384
    return port
385

    
386
  def _ComputeDRBDMap(self, instance):
387
    """Compute the used DRBD minor/nodes.
388

389
    Return: dictionary of node_name: dict of minor: instance_name. The
390
    returned dict will have all the nodes in it (even if with an empty
391
    list).
392

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

    
405
          used[node][port] = instance_name
406
      if disk.children:
407
        for child in disk.children:
408
          _AppendUsedPorts(instance_name, child, used)
409

    
410
    my_dict = dict((node, {}) for node in self._config_data.nodes)
411
    for (node, minor), instance in self._temporary_drbds.iteritems():
412
      my_dict[node][minor] = instance
413
    for instance in self._config_data.instances.itervalues():
414
      for disk in instance.disks:
415
        _AppendUsedPorts(instance.name, disk, my_dict)
416
    return my_dict
417

    
418
  @locking.ssynchronized(_config_lock)
419
  def AllocateDRBDMinor(self, nodes, instance):
420
    """Allocate a drbd minor.
421

422
    The free minor will be automatically computed from the existing
423
    devices. A node can be given multiple times in order to allocate
424
    multiple minors. The result is the list of minors, in the same
425
    order as the passed nodes.
426

427
    """
428
    self._OpenConfig()
429

    
430
    d_map = self._ComputeDRBDMap(instance)
431
    result = []
432
    for nname in nodes:
433
      ndata = d_map[nname]
434
      if not ndata:
435
        # no minors used, we can start at 0
436
        result.append(0)
437
        ndata[0] = instance
438
        self._temporary_drbds[(nname, 0)] = instance
439
        continue
440
      keys = ndata.keys()
441
      keys.sort()
442
      ffree = utils.FirstFree(keys)
443
      if ffree is None:
444
        # return the next minor
445
        # TODO: implement high-limit check
446
        minor = keys[-1] + 1
447
      else:
448
        minor = ffree
449
      result.append(minor)
450
      ndata[minor] = instance
451
      assert (nname, minor) not in self._temporary_drbds, \
452
             "Attempt to reuse reserved DRBD minor"
453
      self._temporary_drbds[(nname, minor)] = instance
454
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
455
                  nodes, result)
456
    return result
457

    
458
  @locking.ssynchronized(_config_lock)
459
  def ReleaseDRBDMinors(self, instance):
460
    """Release temporary drbd minors allocated for a given instance.
461

462
    This should be called on both the error paths and on the success
463
    paths (after the instance has been added or updated).
464

465
    @type instance: string
466
    @param instance: the instance for which temporary minors should be
467
                     released
468

469
    """
470
    for key, name in self._temporary_drbds.items():
471
      if name == instance:
472
        del self._temporary_drbds[key]
473

    
474
  @locking.ssynchronized(_config_lock, shared=1)
475
  def GetConfigVersion(self):
476
    """Get the configuration version.
477

478
    @return: Config version
479

480
    """
481
    return self._config_data.version
482

    
483
  @locking.ssynchronized(_config_lock, shared=1)
484
  def GetClusterName(self):
485
    """Get cluster name.
486

487
    @return: Cluster name
488

489
    """
490
    self._OpenConfig()
491
    return self._config_data.cluster.cluster_name
492

    
493
  @locking.ssynchronized(_config_lock, shared=1)
494
  def GetMasterNode(self):
495
    """Get the hostname of the master node for this cluster.
496

497
    @return: Master hostname
498

499
    """
500
    self._OpenConfig()
501
    return self._config_data.cluster.master_node
502

    
503
  @locking.ssynchronized(_config_lock, shared=1)
504
  def GetMasterIP(self):
505
    """Get the IP of the master node for this cluster.
506

507
    @return: Master IP
508

509
    """
510
    self._OpenConfig()
511
    return self._config_data.cluster.master_ip
512

    
513
  @locking.ssynchronized(_config_lock, shared=1)
514
  def GetMasterNetdev(self):
515
    """Get the master network device for this cluster.
516

517
    """
518
    self._OpenConfig()
519
    return self._config_data.cluster.master_netdev
520

    
521
  @locking.ssynchronized(_config_lock, shared=1)
522
  def GetFileStorageDir(self):
523
    """Get the file storage dir for this cluster.
524

525
    """
526
    self._OpenConfig()
527
    return self._config_data.cluster.file_storage_dir
528

    
529
  @locking.ssynchronized(_config_lock, shared=1)
530
  def GetHypervisorType(self):
531
    """Get the hypervisor type for this cluster.
532

533
    """
534
    self._OpenConfig()
535
    return self._config_data.cluster.hypervisor
536

    
537
  @locking.ssynchronized(_config_lock, shared=1)
538
  def GetHostKey(self):
539
    """Return the rsa hostkey from the config.
540

541
    Args: None
542

543
    Returns: rsa hostkey
544
    """
545
    self._OpenConfig()
546
    return self._config_data.cluster.rsahostkeypub
547

    
548
  @locking.ssynchronized(_config_lock)
549
  def AddInstance(self, instance):
550
    """Add an instance to the config.
551

552
    This should be used after creating a new instance.
553

554
    Args:
555
      instance: the instance object
556
    """
557
    if not isinstance(instance, objects.Instance):
558
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
559

    
560
    if instance.disk_template != constants.DT_DISKLESS:
561
      all_lvs = instance.MapLVsByNode()
562
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
563

    
564
    self._OpenConfig()
565
    instance.serial_no = 1
566
    self._config_data.instances[instance.name] = instance
567
    self._config_data.cluster.serial_no += 1
568
    self._WriteConfig()
569

    
570
  def _SetInstanceStatus(self, instance_name, status):
571
    """Set the instance's status to a given value.
572

573
    """
574
    if status not in ("up", "down"):
575
      raise errors.ProgrammerError("Invalid status '%s' passed to"
576
                                   " ConfigWriter._SetInstanceStatus()" %
577
                                   status)
578
    self._OpenConfig()
579

    
580
    if instance_name not in self._config_data.instances:
581
      raise errors.ConfigurationError("Unknown instance '%s'" %
582
                                      instance_name)
583
    instance = self._config_data.instances[instance_name]
584
    if instance.status != status:
585
      instance.status = status
586
      instance.serial_no += 1
587
      self._WriteConfig()
588

    
589
  @locking.ssynchronized(_config_lock)
590
  def MarkInstanceUp(self, instance_name):
591
    """Mark the instance status to up in the config.
592

593
    """
594
    self._SetInstanceStatus(instance_name, "up")
595

    
596
  @locking.ssynchronized(_config_lock)
597
  def RemoveInstance(self, instance_name):
598
    """Remove the instance from the configuration.
599

600
    """
601
    self._OpenConfig()
602

    
603
    if instance_name not in self._config_data.instances:
604
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
605
    del self._config_data.instances[instance_name]
606
    self._config_data.cluster.serial_no += 1
607
    self._WriteConfig()
608

    
609
  @locking.ssynchronized(_config_lock)
610
  def RenameInstance(self, old_name, new_name):
611
    """Rename an instance.
612

613
    This needs to be done in ConfigWriter and not by RemoveInstance
614
    combined with AddInstance as only we can guarantee an atomic
615
    rename.
616

617
    """
618
    self._OpenConfig()
619
    if old_name not in self._config_data.instances:
620
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
621
    inst = self._config_data.instances[old_name]
622
    del self._config_data.instances[old_name]
623
    inst.name = new_name
624

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

    
634
    self._config_data.instances[inst.name] = inst
635
    self._config_data.cluster.serial_no += 1
636
    self._WriteConfig()
637

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

642
    """
643
    self._SetInstanceStatus(instance_name, "down")
644

    
645
  def _UnlockedGetInstanceList(self):
646
    """Get the list of instances.
647

648
    This function is for internal use, when the config lock is already held.
649

650
    """
651
    self._OpenConfig()
652
    return self._config_data.instances.keys()
653

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

658
    Returns:
659
      array of instances, ex. ['instance2.example.com','instance1.example.com']
660
      these contains all the instances, also the ones in Admin_down state
661

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

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

669
    """
670
    self._OpenConfig()
671

    
672
    return utils.MatchNameComponent(short_name,
673
                                    self._config_data.instances.keys())
674

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

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

680
    """
681
    self._OpenConfig()
682

    
683
    if instance_name not in self._config_data.instances:
684
      return None
685

    
686
    return self._config_data.instances[instance_name]
687

    
688
  @locking.ssynchronized(_config_lock, shared=1)
689
  def GetInstanceInfo(self, instance_name):
690
    """Returns informations about an instance.
691

692
    It takes the information from the configuration file. Other informations of
693
    an instance are taken from the live systems.
694

695
    Args:
696
      instance: name of the instance, ex instance1.example.com
697

698
    Returns:
699
      the instance object
700

701
    """
702
    return self._UnlockedGetInstanceInfo(instance_name)
703

    
704
  @locking.ssynchronized(_config_lock, shared=1)
705
  def GetAllInstancesInfo(self):
706
    """Get the configuration of all instances.
707

708
    @rtype: dict
709
    @returns: dict of (instance, instance_info), where instance_info is what
710
              would GetInstanceInfo return for the node
711

712
    """
713
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
714
                    for instance in self._UnlockedGetInstanceList()])
715
    return my_dict
716

    
717
  @locking.ssynchronized(_config_lock)
718
  def AddNode(self, node):
719
    """Add a node to the configuration.
720

721
    Args:
722
      node: an object.Node instance
723

724
    """
725
    logging.info("Adding node %s to configuration" % node.name)
726

    
727
    self._OpenConfig()
728
    node.serial_no = 1
729
    self._config_data.nodes[node.name] = node
730
    self._config_data.cluster.serial_no += 1
731
    self._WriteConfig()
732

    
733
  @locking.ssynchronized(_config_lock)
734
  def RemoveNode(self, node_name):
735
    """Remove a node from the configuration.
736

737
    """
738
    logging.info("Removing node %s from configuration" % node_name)
739

    
740
    self._OpenConfig()
741
    if node_name not in self._config_data.nodes:
742
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
743

    
744
    del self._config_data.nodes[node_name]
745
    self._config_data.cluster.serial_no += 1
746
    self._WriteConfig()
747

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

752
    """
753
    self._OpenConfig()
754

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

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

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

763
    Args: node: nodename (tuple) of the node
764

765
    Returns: the node object
766

767
    """
768
    self._OpenConfig()
769

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

    
773
    return self._config_data.nodes[node_name]
774

    
775

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

780
    Args: node: nodename (tuple) of the node
781

782
    Returns: the node object
783

784
    """
785
    return self._UnlockedGetNodeInfo(node_name)
786

    
787
  def _UnlockedGetNodeList(self):
788
    """Return the list of nodes which are in the configuration.
789

790
    This function is for internal use, when the config lock is already held.
791

792
    """
793
    self._OpenConfig()
794
    return self._config_data.nodes.keys()
795

    
796

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

801
    """
802
    return self._UnlockedGetNodeList()
803

    
804
  @locking.ssynchronized(_config_lock, shared=1)
805
  def GetAllNodesInfo(self):
806
    """Get the configuration of all nodes.
807

808
    @rtype: dict
809
    @returns: dict of (node, node_info), where node_info is what
810
              would GetNodeInfo return for the node
811

812
    """
813
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
814
                    for node in self._UnlockedGetNodeList()])
815
    return my_dict
816

    
817
  def _BumpSerialNo(self):
818
    """Bump up the serial number of the config.
819

820
    """
821
    self._config_data.serial_no += 1
822

    
823
  def _OpenConfig(self):
824
    """Read the config data from disk.
825

826
    In case we already have configuration data and the config file has
827
    the same mtime as when we read it, we skip the parsing of the
828
    file, since de-serialisation could be slow.
829

830
    """
831
    try:
832
      st = os.stat(self._cfg_file)
833
    except OSError, err:
834
      raise errors.ConfigurationError("Can't stat config file: %s" % err)
835
    if (self._config_data is not None and
836
        self._config_time is not None and
837
        self._config_time == st.st_mtime and
838
        self._config_size == st.st_size and
839
        self._config_inode == st.st_ino):
840
      # data is current, so skip loading of config file
841
      return
842

    
843
    # Make sure the configuration has the right version
844
    ValidateConfig()
845

    
846
    f = open(self._cfg_file, 'r')
847
    try:
848
      try:
849
        data = objects.ConfigData.FromDict(serializer.Load(f.read()))
850
      except Exception, err:
851
        raise errors.ConfigurationError(err)
852
    finally:
853
      f.close()
854
    if (not hasattr(data, 'cluster') or
855
        not hasattr(data.cluster, 'rsahostkeypub')):
856
      raise errors.ConfigurationError("Incomplete configuration"
857
                                      " (missing cluster.rsahostkeypub)")
858
    self._config_data = data
859
    self._config_time = st.st_mtime
860
    self._config_size = st.st_size
861
    self._config_inode = st.st_ino
862

    
863
  def _DistributeConfig(self):
864
    """Distribute the configuration to the other nodes.
865

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

869
    """
870
    if self._offline:
871
      return True
872
    bad = False
873
    nodelist = self._UnlockedGetNodeList()
874
    myhostname = self._my_hostname
875

    
876
    try:
877
      nodelist.remove(myhostname)
878
    except ValueError:
879
      pass
880

    
881
    result = rpc.call_upload_file(nodelist, self._cfg_file)
882
    for node in nodelist:
883
      if not result[node]:
884
        logging.error("copy of file %s to node %s failed",
885
                      self._cfg_file, node)
886
        bad = True
887
    return not bad
888

    
889
  def _WriteConfig(self, destination=None):
890
    """Write the configuration data to persistent storage.
891

892
    """
893
    if destination is None:
894
      destination = self._cfg_file
895
    self._BumpSerialNo()
896
    txt = serializer.Dump(self._config_data.ToDict())
897
    dir_name, file_name = os.path.split(destination)
898
    fd, name = tempfile.mkstemp('.newconfig', file_name, dir_name)
899
    f = os.fdopen(fd, 'w')
900
    try:
901
      f.write(txt)
902
      os.fsync(f.fileno())
903
    finally:
904
      f.close()
905
    # we don't need to do os.close(fd) as f.close() did it
906
    os.rename(name, destination)
907
    self.write_count += 1
908
    # re-set our cache as not to re-read the config file
909
    try:
910
      st = os.stat(destination)
911
    except OSError, err:
912
      raise errors.ConfigurationError("Can't stat config file: %s" % err)
913
    self._config_time = st.st_mtime
914
    self._config_size = st.st_size
915
    self._config_inode = st.st_ino
916
    # and redistribute the config file
917
    self._DistributeConfig()
918

    
919
  @locking.ssynchronized(_config_lock)
920
  def InitConfig(self, version, cluster_config, master_node_config):
921
    """Create the initial cluster configuration.
922

923
    It will contain the current node, which will also be the master
924
    node, and no instances.
925

926
    @type version: int
927
    @param version: Configuration version
928
    @type cluster_config: objects.Cluster
929
    @param cluster_config: Cluster configuration
930
    @type master_node_config: objects.Node
931
    @param master_node_config: Master node configuration
932

933
    """
934
    nodes = {
935
      master_node_config.name: master_node_config,
936
      }
937

    
938
    self._config_data = objects.ConfigData(version=version,
939
                                           cluster=cluster_config,
940
                                           nodes=nodes,
941
                                           instances={},
942
                                           serial_no=1)
943
    self._WriteConfig()
944

    
945
  @locking.ssynchronized(_config_lock, shared=1)
946
  def GetVGName(self):
947
    """Return the volume group name.
948

949
    """
950
    self._OpenConfig()
951
    return self._config_data.cluster.volume_group_name
952

    
953
  @locking.ssynchronized(_config_lock)
954
  def SetVGName(self, vg_name):
955
    """Set the volume group name.
956

957
    """
958
    self._OpenConfig()
959
    self._config_data.cluster.volume_group_name = vg_name
960
    self._config_data.cluster.serial_no += 1
961
    self._WriteConfig()
962

    
963
  @locking.ssynchronized(_config_lock, shared=1)
964
  def GetDefBridge(self):
965
    """Return the default bridge.
966

967
    """
968
    self._OpenConfig()
969
    return self._config_data.cluster.default_bridge
970

    
971
  @locking.ssynchronized(_config_lock, shared=1)
972
  def GetMACPrefix(self):
973
    """Return the mac prefix.
974

975
    """
976
    self._OpenConfig()
977
    return self._config_data.cluster.mac_prefix
978

    
979
  @locking.ssynchronized(_config_lock, shared=1)
980
  def GetClusterInfo(self):
981
    """Returns informations about the cluster
982

983
    Returns:
984
      the cluster object
985

986
    """
987
    self._OpenConfig()
988

    
989
    return self._config_data.cluster
990

    
991
  @locking.ssynchronized(_config_lock)
992
  def Update(self, target):
993
    """Notify function to be called after updates.
994

995
    This function must be called when an object (as returned by
996
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
997
    caller wants the modifications saved to the backing store. Note
998
    that all modified objects will be saved, but the target argument
999
    is the one the caller wants to ensure that it's saved.
1000

1001
    """
1002
    if self._config_data is None:
1003
      raise errors.ProgrammerError("Configuration file not read,"
1004
                                   " cannot save.")
1005
    if isinstance(target, objects.Cluster):
1006
      test = target == self._config_data.cluster
1007
    elif isinstance(target, objects.Node):
1008
      test = target in self._config_data.nodes.values()
1009
    elif isinstance(target, objects.Instance):
1010
      test = target in self._config_data.instances.values()
1011
    else:
1012
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
1013
                                   " ConfigWriter.Update" % type(target))
1014
    if not test:
1015
      raise errors.ConfigurationError("Configuration updated since object"
1016
                                      " has been read or unknown object")
1017
    target.serial_no += 1
1018

    
1019
    self._WriteConfig()