Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 34d657ba

History | View | Annotate | Download (41.5 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
import time
39

    
40
from ganeti import errors
41
from ganeti import locking
42
from ganeti import utils
43
from ganeti import constants
44
from ganeti import rpc
45
from ganeti import objects
46
from ganeti import serializer
47

    
48

    
49
_config_lock = locking.SharedLock()
50

    
51

    
52
def _ValidateConfig(data):
53
  """Verifies that a configuration objects looks valid.
54

55
  This only verifies the version of the configuration.
56

57
  @raise errors.ConfigurationError: if the version differs from what
58
      we expect
59

60
  """
61
  if data.version != constants.CONFIG_VERSION:
62
    raise errors.ConfigurationError("Cluster configuration version"
63
                                    " mismatch, got %s instead of %s" %
64
                                    (data.version,
65
                                     constants.CONFIG_VERSION))
66

    
67

    
68
class ConfigWriter:
69
  """The interface to the cluster configuration.
70

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

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

97
    """
98
    return os.path.exists(constants.CLUSTER_CONF_FILE)
99

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

104
    This should check the current instances for duplicates.
105

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

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

127
    This only checks instances managed by this cluster, it does not
128
    check for potential collisions elsewhere.
129

130
    """
131
    all_macs = self._AllMACs()
132
    return mac in all_macs or mac in self._temporary_macs
133

    
134
  @locking.ssynchronized(_config_lock, shared=1)
135
  def GenerateDRBDSecret(self):
136
    """Generate a DRBD secret.
137

138
    This checks the current disks for duplicates.
139

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

    
152
  def _AllLVs(self):
153
    """Compute the list of all LVs.
154

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

    
163
  def _AllIDs(self, include_temporary):
164
    """Compute the list of all UUIDs and names we have.
165

166
    @type include_temporary: boolean
167
    @param include_temporary: whether to include the _temporary_ids set
168
    @rtype: set
169
    @return: a set of IDs
170

171
    """
172
    existing = set()
173
    if include_temporary:
174
      existing.update(self._temporary_ids)
175
    existing.update(self._AllLVs())
176
    existing.update(self._config_data.instances.keys())
177
    existing.update(self._config_data.nodes.keys())
178
    return existing
179

    
180
  @locking.ssynchronized(_config_lock, shared=1)
181
  def GenerateUniqueID(self, exceptions=None):
182
    """Generate an unique disk name.
183

184
    This checks the current node, instances and disk names for
185
    duplicates.
186

187
    @param exceptions: a list with some other names which should be checked
188
        for uniqueness (used for example when you want to get
189
        more than one id at one time without adding each one in
190
        turn to the config file)
191

192
    @rtype: string
193
    @return: the unique id
194

195
    """
196
    existing = self._AllIDs(include_temporary=True)
197
    if exceptions is not None:
198
      existing.update(exceptions)
199
    retries = 64
200
    while retries > 0:
201
      unique_id = utils.NewUUID()
202
      if unique_id not in existing and unique_id is not None:
203
        break
204
    else:
205
      raise errors.ConfigurationError("Not able generate an unique ID"
206
                                      " (last tried ID: %s" % unique_id)
207
    self._temporary_ids.add(unique_id)
208
    return unique_id
209

    
210
  def _CleanupTemporaryIDs(self):
211
    """Cleanups the _temporary_ids structure.
212

213
    """
214
    existing = self._AllIDs(include_temporary=False)
215
    self._temporary_ids = self._temporary_ids - existing
216

    
217
  def _AllMACs(self):
218
    """Return all MACs present in the config.
219

220
    @rtype: list
221
    @return: the list of all MACs
222

223
    """
224
    result = []
225
    for instance in self._config_data.instances.values():
226
      for nic in instance.nics:
227
        result.append(nic.mac)
228

    
229
    return result
230

    
231
  def _AllDRBDSecrets(self):
232
    """Return all DRBD secrets present in the config.
233

234
    @rtype: list
235
    @return: the list of all DRBD secrets
236

237
    """
238
    def helper(disk, result):
239
      """Recursively gather secrets from this disk."""
240
      if disk.dev_type == constants.DT_DRBD8:
241
        result.append(disk.logical_id[5])
242
      if disk.children:
243
        for child in disk.children:
244
          helper(child, result)
245

    
246
    result = []
247
    for instance in self._config_data.instances.values():
248
      for disk in instance.disks:
249
        helper(disk, result)
250

    
251
    return result
252

    
253
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
254
    """Compute duplicate disk IDs
255

256
    @type disk: L{objects.Disk}
257
    @param disk: the disk at which to start searching
258
    @type l_ids: list
259
    @param l_ids: list of current logical ids
260
    @type p_ids: list
261
    @param p_ids: list of current physical ids
262
    @rtype: list
263
    @return: a list of error messages
264

265
    """
266
    result = []
267
    if disk.logical_id is not None:
268
      if disk.logical_id in l_ids:
269
        result.append("duplicate logical id %s" % str(disk.logical_id))
270
      else:
271
        l_ids.append(disk.logical_id)
272
    if disk.physical_id is not None:
273
      if disk.physical_id in p_ids:
274
        result.append("duplicate physical id %s" % str(disk.physical_id))
275
      else:
276
        p_ids.append(disk.physical_id)
277

    
278
    if disk.children:
279
      for child in disk.children:
280
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
281
    return result
282

    
283
  def _UnlockedVerifyConfig(self):
284
    """Verify function.
285

286
    @rtype: list
287
    @return: a list of error messages; a non-empty list signifies
288
        configuration errors
289

290
    """
291
    result = []
292
    seen_macs = []
293
    ports = {}
294
    data = self._config_data
295
    seen_lids = []
296
    seen_pids = []
297

    
298
    # global cluster checks
299
    if not data.cluster.enabled_hypervisors:
300
      result.append("enabled hypervisors list doesn't have any entries")
301
    invalid_hvs = set(data.cluster.enabled_hypervisors) - constants.HYPER_TYPES
302
    if invalid_hvs:
303
      result.append("enabled hypervisors contains invalid entries: %s" %
304
                    invalid_hvs)
305

    
306
    if data.cluster.master_node not in data.nodes:
307
      result.append("cluster has invalid primary node '%s'" %
308
                    data.cluster.master_node)
309

    
310
    # per-instance checks
311
    for instance_name in data.instances:
312
      instance = data.instances[instance_name]
313
      if instance.primary_node not in data.nodes:
314
        result.append("instance '%s' has invalid primary node '%s'" %
315
                      (instance_name, instance.primary_node))
316
      for snode in instance.secondary_nodes:
317
        if snode not in data.nodes:
318
          result.append("instance '%s' has invalid secondary node '%s'" %
319
                        (instance_name, snode))
320
      for idx, nic in enumerate(instance.nics):
321
        if nic.mac in seen_macs:
322
          result.append("instance '%s' has NIC %d mac %s duplicate" %
323
                        (instance_name, idx, nic.mac))
324
        else:
325
          seen_macs.append(nic.mac)
326

    
327
      # gather the drbd ports for duplicate checks
328
      for dsk in instance.disks:
329
        if dsk.dev_type in constants.LDS_DRBD:
330
          tcp_port = dsk.logical_id[2]
331
          if tcp_port not in ports:
332
            ports[tcp_port] = []
333
          ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
334
      # gather network port reservation
335
      net_port = getattr(instance, "network_port", None)
336
      if net_port is not None:
337
        if net_port not in ports:
338
          ports[net_port] = []
339
        ports[net_port].append((instance.name, "network port"))
340

    
341
      # instance disk verify
342
      for idx, disk in enumerate(instance.disks):
343
        result.extend(["instance '%s' disk %d error: %s" %
344
                       (instance.name, idx, msg) for msg in disk.Verify()])
345
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
346

    
347
    # cluster-wide pool of free ports
348
    for free_port in data.cluster.tcpudp_port_pool:
349
      if free_port not in ports:
350
        ports[free_port] = []
351
      ports[free_port].append(("cluster", "port marked as free"))
352

    
353
    # compute tcp/udp duplicate ports
354
    keys = ports.keys()
355
    keys.sort()
356
    for pnum in keys:
357
      pdata = ports[pnum]
358
      if len(pdata) > 1:
359
        txt = ", ".join(["%s/%s" % val for val in pdata])
360
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
361

    
362
    # highest used tcp port check
363
    if keys:
364
      if keys[-1] > data.cluster.highest_used_port:
365
        result.append("Highest used port mismatch, saved %s, computed %s" %
366
                      (data.cluster.highest_used_port, keys[-1]))
367

    
368
    if not data.nodes[data.cluster.master_node].master_candidate:
369
      result.append("Master node is not a master candidate")
370

    
371
    # master candidate checks
372
    mc_now, mc_max = self._UnlockedGetMasterCandidateStats()
373
    if mc_now < mc_max:
374
      result.append("Not enough master candidates: actual %d, target %d" %
375
                    (mc_now, mc_max))
376

    
377
    # node checks
378
    for node in data.nodes.values():
379
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
380
        result.append("Node %s state is invalid: master_candidate=%s,"
381
                      " drain=%s, offline=%s" %
382
                      (node.name, node.master_candidate, node.drain,
383
                       node.offline))
384

    
385
    # drbd minors check
386
    d_map, duplicates = self._UnlockedComputeDRBDMap()
387
    for node, minor, instance_a, instance_b in duplicates:
388
      result.append("DRBD minor %d on node %s is assigned twice to instances"
389
                    " %s and %s" % (minor, node, instance_a, instance_b))
390

    
391
    return result
392

    
393
  @locking.ssynchronized(_config_lock, shared=1)
394
  def VerifyConfig(self):
395
    """Verify function.
396

397
    This is just a wrapper over L{_UnlockedVerifyConfig}.
398

399
    @rtype: list
400
    @return: a list of error messages; a non-empty list signifies
401
        configuration errors
402

403
    """
404
    return self._UnlockedVerifyConfig()
405

    
406
  def _UnlockedSetDiskID(self, disk, node_name):
407
    """Convert the unique ID to the ID needed on the target nodes.
408

409
    This is used only for drbd, which needs ip/port configuration.
410

411
    The routine descends down and updates its children also, because
412
    this helps when the only the top device is passed to the remote
413
    node.
414

415
    This function is for internal use, when the config lock is already held.
416

417
    """
418
    if disk.children:
419
      for child in disk.children:
420
        self._UnlockedSetDiskID(child, node_name)
421

    
422
    if disk.logical_id is None and disk.physical_id is not None:
423
      return
424
    if disk.dev_type == constants.LD_DRBD8:
425
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
426
      if node_name not in (pnode, snode):
427
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
428
                                        node_name)
429
      pnode_info = self._UnlockedGetNodeInfo(pnode)
430
      snode_info = self._UnlockedGetNodeInfo(snode)
431
      if pnode_info is None or snode_info is None:
432
        raise errors.ConfigurationError("Can't find primary or secondary node"
433
                                        " for %s" % str(disk))
434
      p_data = (pnode_info.secondary_ip, port)
435
      s_data = (snode_info.secondary_ip, port)
436
      if pnode == node_name:
437
        disk.physical_id = p_data + s_data + (pminor, secret)
438
      else: # it must be secondary, we tested above
439
        disk.physical_id = s_data + p_data + (sminor, secret)
440
    else:
441
      disk.physical_id = disk.logical_id
442
    return
443

    
444
  @locking.ssynchronized(_config_lock)
445
  def SetDiskID(self, disk, node_name):
446
    """Convert the unique ID to the ID needed on the target nodes.
447

448
    This is used only for drbd, which needs ip/port configuration.
449

450
    The routine descends down and updates its children also, because
451
    this helps when the only the top device is passed to the remote
452
    node.
453

454
    """
455
    return self._UnlockedSetDiskID(disk, node_name)
456

    
457
  @locking.ssynchronized(_config_lock)
458
  def AddTcpUdpPort(self, port):
459
    """Adds a new port to the available port pool.
460

461
    """
462
    if not isinstance(port, int):
463
      raise errors.ProgrammerError("Invalid type passed for port")
464

    
465
    self._config_data.cluster.tcpudp_port_pool.add(port)
466
    self._WriteConfig()
467

    
468
  @locking.ssynchronized(_config_lock, shared=1)
469
  def GetPortList(self):
470
    """Returns a copy of the current port list.
471

472
    """
473
    return self._config_data.cluster.tcpudp_port_pool.copy()
474

    
475
  @locking.ssynchronized(_config_lock)
476
  def AllocatePort(self):
477
    """Allocate a port.
478

479
    The port will be taken from the available port pool or from the
480
    default port range (and in this case we increase
481
    highest_used_port).
482

483
    """
484
    # If there are TCP/IP ports configured, we use them first.
485
    if self._config_data.cluster.tcpudp_port_pool:
486
      port = self._config_data.cluster.tcpudp_port_pool.pop()
487
    else:
488
      port = self._config_data.cluster.highest_used_port + 1
489
      if port >= constants.LAST_DRBD_PORT:
490
        raise errors.ConfigurationError("The highest used port is greater"
491
                                        " than %s. Aborting." %
492
                                        constants.LAST_DRBD_PORT)
493
      self._config_data.cluster.highest_used_port = port
494

    
495
    self._WriteConfig()
496
    return port
497

    
498
  def _UnlockedComputeDRBDMap(self):
499
    """Compute the used DRBD minor/nodes.
500

501
    @rtype: (dict, list)
502
    @return: dictionary of node_name: dict of minor: instance_name;
503
        the returned dict will have all the nodes in it (even if with
504
        an empty list), and a list of duplicates; if the duplicates
505
        list is not empty, the configuration is corrupted and its caller
506
        should raise an exception
507

508
    """
509
    def _AppendUsedPorts(instance_name, disk, used):
510
      duplicates = []
511
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
512
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
513
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
514
          assert node in used, ("Node '%s' of instance '%s' not found"
515
                                " in node list" % (node, instance_name))
516
          if port in used[node]:
517
            duplicates.append((node, port, instance_name, used[node][port]))
518
          else:
519
            used[node][port] = instance_name
520
      if disk.children:
521
        for child in disk.children:
522
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
523
      return duplicates
524

    
525
    duplicates = []
526
    my_dict = dict((node, {}) for node in self._config_data.nodes)
527
    for instance in self._config_data.instances.itervalues():
528
      for disk in instance.disks:
529
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
530
    for (node, minor), instance in self._temporary_drbds.iteritems():
531
      if minor in my_dict[node] and my_dict[node][minor] != instance:
532
        duplicates.append((node, minor, instance, my_dict[node][minor]))
533
      else:
534
        my_dict[node][minor] = instance
535
    return my_dict, duplicates
536

    
537
  @locking.ssynchronized(_config_lock)
538
  def ComputeDRBDMap(self):
539
    """Compute the used DRBD minor/nodes.
540

541
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
542

543
    @return: dictionary of node_name: dict of minor: instance_name;
544
        the returned dict will have all the nodes in it (even if with
545
        an empty list).
546

547
    """
548
    d_map, duplicates = self._UnlockedComputeDRBDMap()
549
    if duplicates:
550
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
551
                                      str(duplicates))
552
    return d_map
553

    
554
  @locking.ssynchronized(_config_lock)
555
  def AllocateDRBDMinor(self, nodes, instance):
556
    """Allocate a drbd minor.
557

558
    The free minor will be automatically computed from the existing
559
    devices. A node can be given multiple times in order to allocate
560
    multiple minors. The result is the list of minors, in the same
561
    order as the passed nodes.
562

563
    @type instance: string
564
    @param instance: the instance for which we allocate minors
565

566
    """
567
    assert isinstance(instance, basestring), \
568
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
569

    
570
    d_map, duplicates = self._UnlockedComputeDRBDMap()
571
    if duplicates:
572
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
573
                                      str(duplicates))
574
    result = []
575
    for nname in nodes:
576
      ndata = d_map[nname]
577
      if not ndata:
578
        # no minors used, we can start at 0
579
        result.append(0)
580
        ndata[0] = instance
581
        self._temporary_drbds[(nname, 0)] = instance
582
        continue
583
      keys = ndata.keys()
584
      keys.sort()
585
      ffree = utils.FirstFree(keys)
586
      if ffree is None:
587
        # return the next minor
588
        # TODO: implement high-limit check
589
        minor = keys[-1] + 1
590
      else:
591
        minor = ffree
592
      # double-check minor against current instances
593
      assert minor not in d_map[nname], \
594
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
595
              " already allocated to instance %s" %
596
              (minor, nname, d_map[nname][minor]))
597
      ndata[minor] = instance
598
      # double-check minor against reservation
599
      r_key = (nname, minor)
600
      assert r_key not in self._temporary_drbds, \
601
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
602
              " reserved for instance %s" %
603
              (minor, nname, self._temporary_drbds[r_key]))
604
      self._temporary_drbds[r_key] = instance
605
      result.append(minor)
606
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
607
                  nodes, result)
608
    return result
609

    
610
  def _UnlockedReleaseDRBDMinors(self, instance):
611
    """Release temporary drbd minors allocated for a given instance.
612

613
    @type instance: string
614
    @param instance: the instance for which temporary minors should be
615
                     released
616

617
    """
618
    assert isinstance(instance, basestring), \
619
           "Invalid argument passed to ReleaseDRBDMinors"
620
    for key, name in self._temporary_drbds.items():
621
      if name == instance:
622
        del self._temporary_drbds[key]
623

    
624
  @locking.ssynchronized(_config_lock)
625
  def ReleaseDRBDMinors(self, instance):
626
    """Release temporary drbd minors allocated for a given instance.
627

628
    This should be called on the error paths, on the success paths
629
    it's automatically called by the ConfigWriter add and update
630
    functions.
631

632
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
633

634
    @type instance: string
635
    @param instance: the instance for which temporary minors should be
636
                     released
637

638
    """
639
    self._UnlockedReleaseDRBDMinors(instance)
640

    
641
  @locking.ssynchronized(_config_lock, shared=1)
642
  def GetConfigVersion(self):
643
    """Get the configuration version.
644

645
    @return: Config version
646

647
    """
648
    return self._config_data.version
649

    
650
  @locking.ssynchronized(_config_lock, shared=1)
651
  def GetClusterName(self):
652
    """Get cluster name.
653

654
    @return: Cluster name
655

656
    """
657
    return self._config_data.cluster.cluster_name
658

    
659
  @locking.ssynchronized(_config_lock, shared=1)
660
  def GetMasterNode(self):
661
    """Get the hostname of the master node for this cluster.
662

663
    @return: Master hostname
664

665
    """
666
    return self._config_data.cluster.master_node
667

    
668
  @locking.ssynchronized(_config_lock, shared=1)
669
  def GetMasterIP(self):
670
    """Get the IP of the master node for this cluster.
671

672
    @return: Master IP
673

674
    """
675
    return self._config_data.cluster.master_ip
676

    
677
  @locking.ssynchronized(_config_lock, shared=1)
678
  def GetMasterNetdev(self):
679
    """Get the master network device for this cluster.
680

681
    """
682
    return self._config_data.cluster.master_netdev
683

    
684
  @locking.ssynchronized(_config_lock, shared=1)
685
  def GetFileStorageDir(self):
686
    """Get the file storage dir for this cluster.
687

688
    """
689
    return self._config_data.cluster.file_storage_dir
690

    
691
  @locking.ssynchronized(_config_lock, shared=1)
692
  def GetHypervisorType(self):
693
    """Get the hypervisor type for this cluster.
694

695
    """
696
    return self._config_data.cluster.enabled_hypervisors[0]
697

    
698
  @locking.ssynchronized(_config_lock, shared=1)
699
  def GetHostKey(self):
700
    """Return the rsa hostkey from the config.
701

702
    @rtype: string
703
    @return: the rsa hostkey
704

705
    """
706
    return self._config_data.cluster.rsahostkeypub
707

    
708
  @locking.ssynchronized(_config_lock)
709
  def AddInstance(self, instance):
710
    """Add an instance to the config.
711

712
    This should be used after creating a new instance.
713

714
    @type instance: L{objects.Instance}
715
    @param instance: the instance object
716

717
    """
718
    if not isinstance(instance, objects.Instance):
719
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
720

    
721
    if instance.disk_template != constants.DT_DISKLESS:
722
      all_lvs = instance.MapLVsByNode()
723
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
724

    
725
    all_macs = self._AllMACs()
726
    for nic in instance.nics:
727
      if nic.mac in all_macs:
728
        raise errors.ConfigurationError("Cannot add instance %s:"
729
          " MAC address '%s' already in use." % (instance.name, nic.mac))
730

    
731
    instance.serial_no = 1
732
    instance.ctime = instance.mtime = time.time()
733
    self._config_data.instances[instance.name] = instance
734
    self._config_data.cluster.serial_no += 1
735
    self._UnlockedReleaseDRBDMinors(instance.name)
736
    for nic in instance.nics:
737
      self._temporary_macs.discard(nic.mac)
738
    self._WriteConfig()
739

    
740
  def _SetInstanceStatus(self, instance_name, status):
741
    """Set the instance's status to a given value.
742

743
    """
744
    assert isinstance(status, bool), \
745
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
746

    
747
    if instance_name not in self._config_data.instances:
748
      raise errors.ConfigurationError("Unknown instance '%s'" %
749
                                      instance_name)
750
    instance = self._config_data.instances[instance_name]
751
    if instance.admin_up != status:
752
      instance.admin_up = status
753
      instance.serial_no += 1
754
      instance.mtime = time.time()
755
      self._WriteConfig()
756

    
757
  @locking.ssynchronized(_config_lock)
758
  def MarkInstanceUp(self, instance_name):
759
    """Mark the instance status to up in the config.
760

761
    """
762
    self._SetInstanceStatus(instance_name, True)
763

    
764
  @locking.ssynchronized(_config_lock)
765
  def RemoveInstance(self, instance_name):
766
    """Remove the instance from the configuration.
767

768
    """
769
    if instance_name not in self._config_data.instances:
770
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
771
    del self._config_data.instances[instance_name]
772
    self._config_data.cluster.serial_no += 1
773
    self._WriteConfig()
774

    
775
  @locking.ssynchronized(_config_lock)
776
  def RenameInstance(self, old_name, new_name):
777
    """Rename an instance.
778

779
    This needs to be done in ConfigWriter and not by RemoveInstance
780
    combined with AddInstance as only we can guarantee an atomic
781
    rename.
782

783
    """
784
    if old_name not in self._config_data.instances:
785
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
786
    inst = self._config_data.instances[old_name]
787
    del self._config_data.instances[old_name]
788
    inst.name = new_name
789

    
790
    for disk in inst.disks:
791
      if disk.dev_type == constants.LD_FILE:
792
        # rename the file paths in logical and physical id
793
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
794
        disk.physical_id = disk.logical_id = (disk.logical_id[0],
795
                                              os.path.join(file_storage_dir,
796
                                                           inst.name,
797
                                                           disk.iv_name))
798

    
799
    self._config_data.instances[inst.name] = inst
800
    self._WriteConfig()
801

    
802
  @locking.ssynchronized(_config_lock)
803
  def MarkInstanceDown(self, instance_name):
804
    """Mark the status of an instance to down in the configuration.
805

806
    """
807
    self._SetInstanceStatus(instance_name, False)
808

    
809
  def _UnlockedGetInstanceList(self):
810
    """Get the list of instances.
811

812
    This function is for internal use, when the config lock is already held.
813

814
    """
815
    return self._config_data.instances.keys()
816

    
817
  @locking.ssynchronized(_config_lock, shared=1)
818
  def GetInstanceList(self):
819
    """Get the list of instances.
820

821
    @return: array of instances, ex. ['instance2.example.com',
822
        'instance1.example.com']
823

824
    """
825
    return self._UnlockedGetInstanceList()
826

    
827
  @locking.ssynchronized(_config_lock, shared=1)
828
  def ExpandInstanceName(self, short_name):
829
    """Attempt to expand an incomplete instance name.
830

831
    """
832
    return utils.MatchNameComponent(short_name,
833
                                    self._config_data.instances.keys())
834

    
835
  def _UnlockedGetInstanceInfo(self, instance_name):
836
    """Returns information about an instance.
837

838
    This function is for internal use, when the config lock is already held.
839

840
    """
841
    if instance_name not in self._config_data.instances:
842
      return None
843

    
844
    return self._config_data.instances[instance_name]
845

    
846
  @locking.ssynchronized(_config_lock, shared=1)
847
  def GetInstanceInfo(self, instance_name):
848
    """Returns information about an instance.
849

850
    It takes the information from the configuration file. Other information of
851
    an instance are taken from the live systems.
852

853
    @param instance_name: name of the instance, e.g.
854
        I{instance1.example.com}
855

856
    @rtype: L{objects.Instance}
857
    @return: the instance object
858

859
    """
860
    return self._UnlockedGetInstanceInfo(instance_name)
861

    
862
  @locking.ssynchronized(_config_lock, shared=1)
863
  def GetAllInstancesInfo(self):
864
    """Get the configuration of all instances.
865

866
    @rtype: dict
867
    @return: dict of (instance, instance_info), where instance_info is what
868
              would GetInstanceInfo return for the node
869

870
    """
871
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
872
                    for instance in self._UnlockedGetInstanceList()])
873
    return my_dict
874

    
875
  @locking.ssynchronized(_config_lock)
876
  def AddNode(self, node):
877
    """Add a node to the configuration.
878

879
    @type node: L{objects.Node}
880
    @param node: a Node instance
881

882
    """
883
    logging.info("Adding node %s to configuration" % node.name)
884

    
885
    node.serial_no = 1
886
    node.ctime = node.mtime = time.time()
887
    self._config_data.nodes[node.name] = node
888
    self._config_data.cluster.serial_no += 1
889
    self._WriteConfig()
890

    
891
  @locking.ssynchronized(_config_lock)
892
  def RemoveNode(self, node_name):
893
    """Remove a node from the configuration.
894

895
    """
896
    logging.info("Removing node %s from configuration" % node_name)
897

    
898
    if node_name not in self._config_data.nodes:
899
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
900

    
901
    del self._config_data.nodes[node_name]
902
    self._config_data.cluster.serial_no += 1
903
    self._WriteConfig()
904

    
905
  @locking.ssynchronized(_config_lock, shared=1)
906
  def ExpandNodeName(self, short_name):
907
    """Attempt to expand an incomplete instance name.
908

909
    """
910
    return utils.MatchNameComponent(short_name,
911
                                    self._config_data.nodes.keys())
912

    
913
  def _UnlockedGetNodeInfo(self, node_name):
914
    """Get the configuration of a node, as stored in the config.
915

916
    This function is for internal use, when the config lock is already
917
    held.
918

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

921
    @rtype: L{objects.Node}
922
    @return: the node object
923

924
    """
925
    if node_name not in self._config_data.nodes:
926
      return None
927

    
928
    return self._config_data.nodes[node_name]
929

    
930

    
931
  @locking.ssynchronized(_config_lock, shared=1)
932
  def GetNodeInfo(self, node_name):
933
    """Get the configuration of a node, as stored in the config.
934

935
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
936

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

939
    @rtype: L{objects.Node}
940
    @return: the node object
941

942
    """
943
    return self._UnlockedGetNodeInfo(node_name)
944

    
945
  def _UnlockedGetNodeList(self):
946
    """Return the list of nodes which are in the configuration.
947

948
    This function is for internal use, when the config lock is already
949
    held.
950

951
    @rtype: list
952

953
    """
954
    return self._config_data.nodes.keys()
955

    
956

    
957
  @locking.ssynchronized(_config_lock, shared=1)
958
  def GetNodeList(self):
959
    """Return the list of nodes which are in the configuration.
960

961
    """
962
    return self._UnlockedGetNodeList()
963

    
964
  @locking.ssynchronized(_config_lock, shared=1)
965
  def GetOnlineNodeList(self):
966
    """Return the list of nodes which are online.
967

968
    """
969
    all_nodes = [self._UnlockedGetNodeInfo(node)
970
                 for node in self._UnlockedGetNodeList()]
971
    return [node.name for node in all_nodes if not node.offline]
972

    
973
  @locking.ssynchronized(_config_lock, shared=1)
974
  def GetAllNodesInfo(self):
975
    """Get the configuration of all nodes.
976

977
    @rtype: dict
978
    @return: dict of (node, node_info), where node_info is what
979
              would GetNodeInfo return for the node
980

981
    """
982
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
983
                    for node in self._UnlockedGetNodeList()])
984
    return my_dict
985

    
986
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
987
    """Get the number of current and maximum desired and possible candidates.
988

989
    @type exceptions: list
990
    @param exceptions: if passed, list of nodes that should be ignored
991
    @rtype: tuple
992
    @return: tuple of (current, desired and possible)
993

994
    """
995
    mc_now = mc_max = 0
996
    for node in self._config_data.nodes.values():
997
      if exceptions and node.name in exceptions:
998
        continue
999
      if not (node.offline or node.drained):
1000
        mc_max += 1
1001
      if node.master_candidate:
1002
        mc_now += 1
1003
    mc_max = min(mc_max, self._config_data.cluster.candidate_pool_size)
1004
    return (mc_now, mc_max)
1005

    
1006
  @locking.ssynchronized(_config_lock, shared=1)
1007
  def GetMasterCandidateStats(self, exceptions=None):
1008
    """Get the number of current and maximum possible candidates.
1009

1010
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1011

1012
    @type exceptions: list
1013
    @param exceptions: if passed, list of nodes that should be ignored
1014
    @rtype: tuple
1015
    @return: tuple of (current, max)
1016

1017
    """
1018
    return self._UnlockedGetMasterCandidateStats(exceptions)
1019

    
1020
  @locking.ssynchronized(_config_lock)
1021
  def MaintainCandidatePool(self):
1022
    """Try to grow the candidate pool to the desired size.
1023

1024
    @rtype: list
1025
    @return: list with the adjusted nodes (L{objects.Node} instances)
1026

1027
    """
1028
    mc_now, mc_max = self._UnlockedGetMasterCandidateStats()
1029
    mod_list = []
1030
    if mc_now < mc_max:
1031
      node_list = self._config_data.nodes.keys()
1032
      random.shuffle(node_list)
1033
      for name in node_list:
1034
        if mc_now >= mc_max:
1035
          break
1036
        node = self._config_data.nodes[name]
1037
        if node.master_candidate or node.offline or node.drained:
1038
          continue
1039
        mod_list.append(node)
1040
        node.master_candidate = True
1041
        node.serial_no += 1
1042
        mc_now += 1
1043
      if mc_now != mc_max:
1044
        # this should not happen
1045
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1046
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1047
      if mod_list:
1048
        self._config_data.cluster.serial_no += 1
1049
        self._WriteConfig()
1050

    
1051
    return mod_list
1052

    
1053
  def _BumpSerialNo(self):
1054
    """Bump up the serial number of the config.
1055

1056
    """
1057
    self._config_data.serial_no += 1
1058
    self._config_data.mtime = time.time()
1059

    
1060
  def _OpenConfig(self):
1061
    """Read the config data from disk.
1062

1063
    """
1064
    raw_data = utils.ReadFile(self._cfg_file)
1065

    
1066
    try:
1067
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1068
    except Exception, err:
1069
      raise errors.ConfigurationError(err)
1070

    
1071
    # Make sure the configuration has the right version
1072
    _ValidateConfig(data)
1073

    
1074
    if (not hasattr(data, 'cluster') or
1075
        not hasattr(data.cluster, 'rsahostkeypub')):
1076
      raise errors.ConfigurationError("Incomplete configuration"
1077
                                      " (missing cluster.rsahostkeypub)")
1078

    
1079
    # Upgrade configuration if needed
1080
    data.UpgradeConfig()
1081

    
1082
    self._config_data = data
1083
    # reset the last serial as -1 so that the next write will cause
1084
    # ssconf update
1085
    self._last_cluster_serial = -1
1086

    
1087
  def _DistributeConfig(self):
1088
    """Distribute the configuration to the other nodes.
1089

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

1093
    """
1094
    if self._offline:
1095
      return True
1096
    bad = False
1097

    
1098
    node_list = []
1099
    addr_list = []
1100
    myhostname = self._my_hostname
1101
    # we can skip checking whether _UnlockedGetNodeInfo returns None
1102
    # since the node list comes from _UnlocketGetNodeList, and we are
1103
    # called with the lock held, so no modifications should take place
1104
    # in between
1105
    for node_name in self._UnlockedGetNodeList():
1106
      if node_name == myhostname:
1107
        continue
1108
      node_info = self._UnlockedGetNodeInfo(node_name)
1109
      if not node_info.master_candidate:
1110
        continue
1111
      node_list.append(node_info.name)
1112
      addr_list.append(node_info.primary_ip)
1113

    
1114
    result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
1115
                                            address_list=addr_list)
1116
    for to_node, to_result in result.items():
1117
      msg = to_result.fail_msg
1118
      if msg:
1119
        msg = ("Copy of file %s to node %s failed: %s" %
1120
               (self._cfg_file, to_node, msg))
1121
        logging.error(msg)
1122
        bad = True
1123
    return not bad
1124

    
1125
  def _WriteConfig(self, destination=None):
1126
    """Write the configuration data to persistent storage.
1127

1128
    """
1129
    # first, cleanup the _temporary_ids set, if an ID is now in the
1130
    # other objects it should be discarded to prevent unbounded growth
1131
    # of that structure
1132
    self._CleanupTemporaryIDs()
1133
    config_errors = self._UnlockedVerifyConfig()
1134
    if config_errors:
1135
      raise errors.ConfigurationError("Configuration data is not"
1136
                                      " consistent: %s" %
1137
                                      (", ".join(config_errors)))
1138
    if destination is None:
1139
      destination = self._cfg_file
1140
    self._BumpSerialNo()
1141
    txt = serializer.Dump(self._config_data.ToDict())
1142

    
1143
    utils.WriteFile(destination, data=txt)
1144

    
1145
    self.write_count += 1
1146

    
1147
    # and redistribute the config file to master candidates
1148
    self._DistributeConfig()
1149

    
1150
    # Write ssconf files on all nodes (including locally)
1151
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
1152
      if not self._offline:
1153
        result = rpc.RpcRunner.call_write_ssconf_files(\
1154
          self._UnlockedGetNodeList(),
1155
          self._UnlockedGetSsconfValues())
1156
        for nname, nresu in result.items():
1157
          msg = nresu.fail_msg
1158
          if msg:
1159
            logging.warning("Error while uploading ssconf files to"
1160
                            " node %s: %s", nname, msg)
1161
      self._last_cluster_serial = self._config_data.cluster.serial_no
1162

    
1163
  def _UnlockedGetSsconfValues(self):
1164
    """Return the values needed by ssconf.
1165

1166
    @rtype: dict
1167
    @return: a dictionary with keys the ssconf names and values their
1168
        associated value
1169

1170
    """
1171
    fn = "\n".join
1172
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1173
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
1174
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1175
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
1176
                    for ninfo in node_info]
1177
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
1178
                    for ninfo in node_info]
1179

    
1180
    instance_data = fn(instance_names)
1181
    off_data = fn(node.name for node in node_info if node.offline)
1182
    on_data = fn(node.name for node in node_info if not node.offline)
1183
    mc_data = fn(node.name for node in node_info if node.master_candidate)
1184
    mc_ips_data = fn(node.primary_ip for node in node_info
1185
                     if node.master_candidate)
1186
    node_data = fn(node_names)
1187
    node_pri_ips_data = fn(node_pri_ips)
1188
    node_snd_ips_data = fn(node_snd_ips)
1189

    
1190
    cluster = self._config_data.cluster
1191
    cluster_tags = fn(cluster.GetTags())
1192
    return {
1193
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
1194
      constants.SS_CLUSTER_TAGS: cluster_tags,
1195
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1196
      constants.SS_MASTER_CANDIDATES: mc_data,
1197
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
1198
      constants.SS_MASTER_IP: cluster.master_ip,
1199
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
1200
      constants.SS_MASTER_NODE: cluster.master_node,
1201
      constants.SS_NODE_LIST: node_data,
1202
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
1203
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
1204
      constants.SS_OFFLINE_NODES: off_data,
1205
      constants.SS_ONLINE_NODES: on_data,
1206
      constants.SS_INSTANCE_LIST: instance_data,
1207
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1208
      }
1209

    
1210
  @locking.ssynchronized(_config_lock, shared=1)
1211
  def GetVGName(self):
1212
    """Return the volume group name.
1213

1214
    """
1215
    return self._config_data.cluster.volume_group_name
1216

    
1217
  @locking.ssynchronized(_config_lock)
1218
  def SetVGName(self, vg_name):
1219
    """Set the volume group name.
1220

1221
    """
1222
    self._config_data.cluster.volume_group_name = vg_name
1223
    self._config_data.cluster.serial_no += 1
1224
    self._WriteConfig()
1225

    
1226
  @locking.ssynchronized(_config_lock, shared=1)
1227
  def GetMACPrefix(self):
1228
    """Return the mac prefix.
1229

1230
    """
1231
    return self._config_data.cluster.mac_prefix
1232

    
1233
  @locking.ssynchronized(_config_lock, shared=1)
1234
  def GetClusterInfo(self):
1235
    """Returns information about the cluster
1236

1237
    @rtype: L{objects.Cluster}
1238
    @return: the cluster object
1239

1240
    """
1241
    return self._config_data.cluster
1242

    
1243
  @locking.ssynchronized(_config_lock)
1244
  def Update(self, target):
1245
    """Notify function to be called after updates.
1246

1247
    This function must be called when an object (as returned by
1248
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
1249
    caller wants the modifications saved to the backing store. Note
1250
    that all modified objects will be saved, but the target argument
1251
    is the one the caller wants to ensure that it's saved.
1252

1253
    @param target: an instance of either L{objects.Cluster},
1254
        L{objects.Node} or L{objects.Instance} which is existing in
1255
        the cluster
1256

1257
    """
1258
    if self._config_data is None:
1259
      raise errors.ProgrammerError("Configuration file not read,"
1260
                                   " cannot save.")
1261
    update_serial = False
1262
    if isinstance(target, objects.Cluster):
1263
      test = target == self._config_data.cluster
1264
    elif isinstance(target, objects.Node):
1265
      test = target in self._config_data.nodes.values()
1266
      update_serial = True
1267
    elif isinstance(target, objects.Instance):
1268
      test = target in self._config_data.instances.values()
1269
    else:
1270
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
1271
                                   " ConfigWriter.Update" % type(target))
1272
    if not test:
1273
      raise errors.ConfigurationError("Configuration updated since object"
1274
                                      " has been read or unknown object")
1275
    target.serial_no += 1
1276
    target.mtime = now = time.time()
1277

    
1278
    if update_serial:
1279
      # for node updates, we need to increase the cluster serial too
1280
      self._config_data.cluster.serial_no += 1
1281
      self._config_data.cluster.mtime = now
1282

    
1283
    if isinstance(target, objects.Instance):
1284
      self._UnlockedReleaseDRBDMinors(target.name)
1285
      for nic in target.nics:
1286
        self._temporary_macs.discard(nic.mac)
1287

    
1288
    self._WriteConfig()