Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 5b263ed7

History | View | Annotate | Download (31.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
  if data.version != constants.CONFIG_VERSION:
53
    raise errors.ConfigurationError("Cluster configuration version"
54
                                    " mismatch, got %s instead of %s" %
55
                                    (data.version,
56
                                     constants.CONFIG_VERSION))
57

    
58

    
59
class ConfigWriter:
60
  """The interface to the cluster configuration.
61

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

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

88
    """
89
    return os.path.exists(constants.CLUSTER_CONF_FILE)
90

    
91
  @locking.ssynchronized(_config_lock, shared=1)
92
  def GenerateMAC(self):
93
    """Generate a MAC for an instance.
94

95
    This should check the current instances for duplicates.
96

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

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

118
    This only checks instances managed by this cluster, it does not
119
    check for potential collisions elsewhere.
120

121
    """
122
    self._OpenConfig()
123
    all_macs = self._AllMACs()
124
    return mac in all_macs
125

    
126
  @locking.ssynchronized(_config_lock, shared=1)
127
  def GenerateDRBDSecret(self):
128
    """Generate a DRBD secret.
129

130
    This checks the current disks for duplicates.
131

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

    
145
  def _ComputeAllLVs(self):
146
    """Compute the list of all LVs.
147

148
    """
149
    self._OpenConfig()
150
    lvnames = set()
151
    for instance in self._config_data.instances.values():
152
      node_data = instance.MapLVsByNode()
153
      for lv_list in node_data.values():
154
        lvnames.update(lv_list)
155
    return lvnames
156

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

161
    This checks the current node, instances and disk names for
162
    duplicates.
163

164
    Args:
165
      - exceptions: a list with some other names which should be checked
166
                    for uniqueness (used for example when you want to get
167
                    more than one id at one time without adding each one in
168
                    turn to the config file
169

170
    Returns: the unique id as a string
171

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

    
191
  def _AllMACs(self):
192
    """Return all MACs present in the config.
193

194
    """
195
    self._OpenConfig()
196

    
197
    result = []
198
    for instance in self._config_data.instances.values():
199
      for nic in instance.nics:
200
        result.append(nic.mac)
201

    
202
    return result
203

    
204
  def _AllDRBDSecrets(self):
205
    """Return all DRBD secrets present in the config.
206

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

    
216
    result = []
217
    for instance in self._config_data.instances.values():
218
      for disk in instance.disks:
219
        helper(disk, result)
220

    
221
    return result
222

    
223
  @locking.ssynchronized(_config_lock, shared=1)
224
  def VerifyConfig(self):
225
    """Stub verify function.
226
    """
227
    self._OpenConfig()
228

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

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

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

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

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

    
285
    return result
286

    
287
  def _UnlockedSetDiskID(self, disk, node_name):
288
    """Convert the unique ID to the ID needed on the target nodes.
289

290
    This is used only for drbd, which needs ip/port configuration.
291

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

296
    This function is for internal use, when the config lock is already held.
297

298
    """
299
    if disk.children:
300
      for child in disk.children:
301
        self._UnlockedSetDiskID(child, node_name)
302

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

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

329
    This is used only for drbd, which needs ip/port configuration.
330

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

335
    """
336
    return self._UnlockedSetDiskID(disk, node_name)
337

    
338
  @locking.ssynchronized(_config_lock)
339
  def AddTcpUdpPort(self, port):
340
    """Adds a new port to the available port pool.
341

342
    """
343
    if not isinstance(port, int):
344
      raise errors.ProgrammerError("Invalid type passed for port")
345

    
346
    self._OpenConfig()
347
    self._config_data.cluster.tcpudp_port_pool.add(port)
348
    self._WriteConfig()
349

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

354
    """
355
    self._OpenConfig()
356
    return self._config_data.cluster.tcpudp_port_pool.copy()
357

    
358
  @locking.ssynchronized(_config_lock)
359
  def AllocatePort(self):
360
    """Allocate a port.
361

362
    The port will be taken from the available port pool or from the
363
    default port range (and in this case we increase
364
    highest_used_port).
365

366
    """
367
    self._OpenConfig()
368

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

    
380
    self._WriteConfig()
381
    return port
382

    
383
  def _ComputeDRBDMap(self, instance):
384
    """Compute the used DRBD minor/nodes.
385

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

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

    
402
          used[node][port] = instance_name
403
      if disk.children:
404
        for child in disk.children:
405
          _AppendUsedPorts(instance_name, child, used)
406

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

    
415
  @locking.ssynchronized(_config_lock)
416
  def AllocateDRBDMinor(self, nodes, instance):
417
    """Allocate a drbd minor.
418

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

424
    """
425
    self._OpenConfig()
426

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

    
455
  @locking.ssynchronized(_config_lock)
456
  def ReleaseDRBDMinors(self, instance):
457
    """Release temporary drbd minors allocated for a given instance.
458

459
    This should be called on both the error paths and on the success
460
    paths (after the instance has been added or updated).
461

462
    @type instance: string
463
    @param instance: the instance for which temporary minors should be
464
                     released
465

466
    """
467
    for key, name in self._temporary_drbds.items():
468
      if name == instance:
469
        del self._temporary_drbds[key]
470

    
471
  @locking.ssynchronized(_config_lock, shared=1)
472
  def GetConfigVersion(self):
473
    """Get the configuration version.
474

475
    @return: Config version
476

477
    """
478
    return self._config_data.version
479

    
480
  @locking.ssynchronized(_config_lock, shared=1)
481
  def GetClusterName(self):
482
    """Get cluster name.
483

484
    @return: Cluster name
485

486
    """
487
    self._OpenConfig()
488
    return self._config_data.cluster.cluster_name
489

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

494
    @return: Master hostname
495

496
    """
497
    self._OpenConfig()
498
    return self._config_data.cluster.master_node
499

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

504
    @return: Master IP
505

506
    """
507
    self._OpenConfig()
508
    return self._config_data.cluster.master_ip
509

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

514
    """
515
    self._OpenConfig()
516
    return self._config_data.cluster.master_netdev
517

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

522
    """
523
    self._OpenConfig()
524
    return self._config_data.cluster.file_storage_dir
525

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

530
    """
531
    self._OpenConfig()
532
    return self._config_data.cluster.hypervisor
533

    
534
  @locking.ssynchronized(_config_lock, shared=1)
535
  def GetHostKey(self):
536
    """Return the rsa hostkey from the config.
537

538
    Args: None
539

540
    Returns: rsa hostkey
541
    """
542
    self._OpenConfig()
543
    return self._config_data.cluster.rsahostkeypub
544

    
545
  @locking.ssynchronized(_config_lock)
546
  def AddInstance(self, instance):
547
    """Add an instance to the config.
548

549
    This should be used after creating a new instance.
550

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

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

    
561
    self._OpenConfig()
562
    instance.serial_no = 1
563
    self._config_data.instances[instance.name] = instance
564
    self._config_data.cluster.serial_no += 1
565
    self._WriteConfig()
566

    
567
  def _SetInstanceStatus(self, instance_name, status):
568
    """Set the instance's status to a given value.
569

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

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

    
586
  @locking.ssynchronized(_config_lock)
587
  def MarkInstanceUp(self, instance_name):
588
    """Mark the instance status to up in the config.
589

590
    """
591
    self._SetInstanceStatus(instance_name, "up")
592

    
593
  @locking.ssynchronized(_config_lock)
594
  def RemoveInstance(self, instance_name):
595
    """Remove the instance from the configuration.
596

597
    """
598
    self._OpenConfig()
599

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

    
606
  @locking.ssynchronized(_config_lock)
607
  def RenameInstance(self, old_name, new_name):
608
    """Rename an instance.
609

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

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

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

    
631
    self._config_data.instances[inst.name] = inst
632
    self._config_data.cluster.serial_no += 1
633
    self._WriteConfig()
634

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

639
    """
640
    self._SetInstanceStatus(instance_name, "down")
641

    
642
  def _UnlockedGetInstanceList(self):
643
    """Get the list of instances.
644

645
    This function is for internal use, when the config lock is already held.
646

647
    """
648
    self._OpenConfig()
649
    return self._config_data.instances.keys()
650

    
651
  @locking.ssynchronized(_config_lock, shared=1)
652
  def GetInstanceList(self):
653
    """Get the list of instances.
654

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

659
    """
660
    return self._UnlockedGetInstanceList()
661

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

666
    """
667
    self._OpenConfig()
668

    
669
    return utils.MatchNameComponent(short_name,
670
                                    self._config_data.instances.keys())
671

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

675
    This function is for internal use, when the config lock is already held.
676

677
    """
678
    self._OpenConfig()
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
    Args:
693
      instance: name of the instance, ex instance1.example.com
694

695
    Returns:
696
      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
    Args:
719
      node: an object.Node instance
720

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

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

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

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

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

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

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

749
    """
750
    self._OpenConfig()
751

    
752
    return utils.MatchNameComponent(short_name,
753
                                    self._config_data.nodes.keys())
754

    
755
  def _UnlockedGetNodeInfo(self, node_name):
756
    """Get the configuration of a node, as stored in the config.
757

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

760
    Args: node: nodename (tuple) of the node
761

762
    Returns: the node object
763

764
    """
765
    self._OpenConfig()
766

    
767
    if node_name not in self._config_data.nodes:
768
      return None
769

    
770
    return self._config_data.nodes[node_name]
771

    
772

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

777
    Args: node: nodename (tuple) of the node
778

779
    Returns: the node object
780

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

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

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

789
    """
790
    self._OpenConfig()
791
    return self._config_data.nodes.keys()
792

    
793

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

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

    
801
  @locking.ssynchronized(_config_lock, shared=1)
802
  def GetAllNodesInfo(self):
803
    """Get the configuration of all nodes.
804

805
    @rtype: dict
806
    @returns: dict of (node, node_info), where node_info is what
807
              would GetNodeInfo return for the node
808

809
    """
810
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
811
                    for node in self._UnlockedGetNodeList()])
812
    return my_dict
813

    
814
  def _BumpSerialNo(self):
815
    """Bump up the serial number of the config.
816

817
    """
818
    self._config_data.serial_no += 1
819

    
820
  def _OpenConfig(self):
821
    """Read the config data from disk.
822

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

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

    
840
    f = open(self._cfg_file, 'r')
841
    try:
842
      try:
843
        data = objects.ConfigData.FromDict(serializer.Load(f.read()))
844
      except Exception, err:
845
        raise errors.ConfigurationError(err)
846
    finally:
847
      f.close()
848

    
849
    # Make sure the configuration has the right version
850
    _ValidateConfig(data)
851

    
852
    if (not hasattr(data, 'cluster') or
853
        not hasattr(data.cluster, 'rsahostkeypub')):
854
      raise errors.ConfigurationError("Incomplete configuration"
855
                                      " (missing cluster.rsahostkeypub)")
856
    self._config_data = data
857
    self._config_time = st.st_mtime
858
    self._config_size = st.st_size
859
    self._config_inode = st.st_ino
860

    
861
  def _DistributeConfig(self):
862
    """Distribute the configuration to the other nodes.
863

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

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

    
874
    try:
875
      nodelist.remove(myhostname)
876
    except ValueError:
877
      pass
878

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

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

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

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

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

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

931
    """
932
    nodes = {
933
      master_node_config.name: master_node_config,
934
      }
935

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

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

947
    """
948
    self._OpenConfig()
949
    return self._config_data.cluster.volume_group_name
950

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

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

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

965
    """
966
    self._OpenConfig()
967
    return self._config_data.cluster.default_bridge
968

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

973
    """
974
    self._OpenConfig()
975
    return self._config_data.cluster.mac_prefix
976

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

981
    Returns:
982
      the cluster object
983

984
    """
985
    self._OpenConfig()
986

    
987
    return self._config_data.cluster
988

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

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

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

    
1017
    self._WriteConfig()