Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ dac59ac5

History | View | Annotate | Download (59.5 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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
# pylint: disable-msg=R0904
35
# R0904: Too many public methods
36

    
37
import os
38
import random
39
import logging
40
import time
41

    
42
from ganeti import errors
43
from ganeti import locking
44
from ganeti import utils
45
from ganeti import constants
46
from ganeti import rpc
47
from ganeti import objects
48
from ganeti import serializer
49
from ganeti import uidpool
50
from ganeti import netutils
51
from ganeti import runtime
52

    
53

    
54
_config_lock = locking.SharedLock("ConfigWriter")
55

    
56
# job id used for resource management at config upgrade time
57
_UPGRADE_CONFIG_JID = "jid-cfg-upgrade"
58

    
59

    
60
def _ValidateConfig(data):
61
  """Verifies that a configuration objects looks valid.
62

63
  This only verifies the version of the configuration.
64

65
  @raise errors.ConfigurationError: if the version differs from what
66
      we expect
67

68
  """
69
  if data.version != constants.CONFIG_VERSION:
70
    raise errors.ConfigVersionMismatch(constants.CONFIG_VERSION, data.version)
71

    
72

    
73
class TemporaryReservationManager:
74
  """A temporary resource reservation manager.
75

76
  This is used to reserve resources in a job, before using them, making sure
77
  other jobs cannot get them in the meantime.
78

79
  """
80
  def __init__(self):
81
    self._ec_reserved = {}
82

    
83
  def Reserved(self, resource):
84
    for holder_reserved in self._ec_reserved.values():
85
      if resource in holder_reserved:
86
        return True
87
    return False
88

    
89
  def Reserve(self, ec_id, resource):
90
    if self.Reserved(resource):
91
      raise errors.ReservationError("Duplicate reservation for resource '%s'"
92
                                    % str(resource))
93
    if ec_id not in self._ec_reserved:
94
      self._ec_reserved[ec_id] = set([resource])
95
    else:
96
      self._ec_reserved[ec_id].add(resource)
97

    
98
  def DropECReservations(self, ec_id):
99
    if ec_id in self._ec_reserved:
100
      del self._ec_reserved[ec_id]
101

    
102
  def GetReserved(self):
103
    all_reserved = set()
104
    for holder_reserved in self._ec_reserved.values():
105
      all_reserved.update(holder_reserved)
106
    return all_reserved
107

    
108
  def Generate(self, existing, generate_one_fn, ec_id):
109
    """Generate a new resource of this type
110

111
    """
112
    assert callable(generate_one_fn)
113

    
114
    all_elems = self.GetReserved()
115
    all_elems.update(existing)
116
    retries = 64
117
    while retries > 0:
118
      new_resource = generate_one_fn()
119
      if new_resource is not None and new_resource not in all_elems:
120
        break
121
    else:
122
      raise errors.ConfigurationError("Not able generate new resource"
123
                                      " (last tried: %s)" % new_resource)
124
    self.Reserve(ec_id, new_resource)
125
    return new_resource
126

    
127

    
128
class ConfigWriter:
129
  """The interface to the cluster configuration.
130

131
  @ivar _temporary_lvs: reservation manager for temporary LVs
132
  @ivar _all_rms: a list of all temporary reservation managers
133

134
  """
135
  def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts,
136
               accept_foreign=False):
137
    self.write_count = 0
138
    self._lock = _config_lock
139
    self._config_data = None
140
    self._offline = offline
141
    if cfg_file is None:
142
      self._cfg_file = constants.CLUSTER_CONF_FILE
143
    else:
144
      self._cfg_file = cfg_file
145
    self._getents = _getents
146
    self._temporary_ids = TemporaryReservationManager()
147
    self._temporary_drbds = {}
148
    self._temporary_macs = TemporaryReservationManager()
149
    self._temporary_secrets = TemporaryReservationManager()
150
    self._temporary_lvs = TemporaryReservationManager()
151
    self._all_rms = [self._temporary_ids, self._temporary_macs,
152
                     self._temporary_secrets, self._temporary_lvs]
153
    # Note: in order to prevent errors when resolving our name in
154
    # _DistributeConfig, we compute it here once and reuse it; it's
155
    # better to raise an error before starting to modify the config
156
    # file than after it was modified
157
    self._my_hostname = netutils.Hostname.GetSysName()
158
    self._last_cluster_serial = -1
159
    self._cfg_id = None
160
    self._OpenConfig(accept_foreign)
161

    
162
  # this method needs to be static, so that we can call it on the class
163
  @staticmethod
164
  def IsCluster():
165
    """Check if the cluster is configured.
166

167
    """
168
    return os.path.exists(constants.CLUSTER_CONF_FILE)
169

    
170
  def _GenerateOneMAC(self):
171
    """Generate one mac address
172

173
    """
174
    prefix = self._config_data.cluster.mac_prefix
175
    byte1 = random.randrange(0, 256)
176
    byte2 = random.randrange(0, 256)
177
    byte3 = random.randrange(0, 256)
178
    mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
179
    return mac
180

    
181
  @locking.ssynchronized(_config_lock, shared=1)
182
  def GetNdParams(self, node):
183
    """Get the node params populated with cluster defaults.
184

185
    @type node: L{object.Node}
186
    @param node: The node we want to know the params for
187
    @return: A dict with the filled in node params
188

189
    """
190
    nodegroup = self._UnlockedGetNodeGroup(node.group)
191
    return self._config_data.cluster.FillND(node, nodegroup)
192

    
193
  @locking.ssynchronized(_config_lock, shared=1)
194
  def GenerateMAC(self, ec_id):
195
    """Generate a MAC for an instance.
196

197
    This should check the current instances for duplicates.
198

199
    """
200
    existing = self._AllMACs()
201
    return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
202

    
203
  @locking.ssynchronized(_config_lock, shared=1)
204
  def ReserveMAC(self, mac, ec_id):
205
    """Reserve a MAC for an instance.
206

207
    This only checks instances managed by this cluster, it does not
208
    check for potential collisions elsewhere.
209

210
    """
211
    all_macs = self._AllMACs()
212
    if mac in all_macs:
213
      raise errors.ReservationError("mac already in use")
214
    else:
215
      self._temporary_macs.Reserve(mac, ec_id)
216

    
217
  @locking.ssynchronized(_config_lock, shared=1)
218
  def ReserveLV(self, lv_name, ec_id):
219
    """Reserve an VG/LV pair for an instance.
220

221
    @type lv_name: string
222
    @param lv_name: the logical volume name to reserve
223

224
    """
225
    all_lvs = self._AllLVs()
226
    if lv_name in all_lvs:
227
      raise errors.ReservationError("LV already in use")
228
    else:
229
      self._temporary_lvs.Reserve(lv_name, ec_id)
230

    
231
  @locking.ssynchronized(_config_lock, shared=1)
232
  def GenerateDRBDSecret(self, ec_id):
233
    """Generate a DRBD secret.
234

235
    This checks the current disks for duplicates.
236

237
    """
238
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
239
                                            utils.GenerateSecret,
240
                                            ec_id)
241

    
242
  def _AllLVs(self):
243
    """Compute the list of all LVs.
244

245
    """
246
    lvnames = set()
247
    for instance in self._config_data.instances.values():
248
      node_data = instance.MapLVsByNode()
249
      for lv_list in node_data.values():
250
        lvnames.update(lv_list)
251
    return lvnames
252

    
253
  def _AllIDs(self, include_temporary):
254
    """Compute the list of all UUIDs and names we have.
255

256
    @type include_temporary: boolean
257
    @param include_temporary: whether to include the _temporary_ids set
258
    @rtype: set
259
    @return: a set of IDs
260

261
    """
262
    existing = set()
263
    if include_temporary:
264
      existing.update(self._temporary_ids.GetReserved())
265
    existing.update(self._AllLVs())
266
    existing.update(self._config_data.instances.keys())
267
    existing.update(self._config_data.nodes.keys())
268
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
269
    return existing
270

    
271
  def _GenerateUniqueID(self, ec_id):
272
    """Generate an unique UUID.
273

274
    This checks the current node, instances and disk names for
275
    duplicates.
276

277
    @rtype: string
278
    @return: the unique id
279

280
    """
281
    existing = self._AllIDs(include_temporary=False)
282
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
283

    
284
  @locking.ssynchronized(_config_lock, shared=1)
285
  def GenerateUniqueID(self, ec_id):
286
    """Generate an unique ID.
287

288
    This is just a wrapper over the unlocked version.
289

290
    @type ec_id: string
291
    @param ec_id: unique id for the job to reserve the id to
292

293
    """
294
    return self._GenerateUniqueID(ec_id)
295

    
296
  def _AllMACs(self):
297
    """Return all MACs present in the config.
298

299
    @rtype: list
300
    @return: the list of all MACs
301

302
    """
303
    result = []
304
    for instance in self._config_data.instances.values():
305
      for nic in instance.nics:
306
        result.append(nic.mac)
307

    
308
    return result
309

    
310
  def _AllDRBDSecrets(self):
311
    """Return all DRBD secrets present in the config.
312

313
    @rtype: list
314
    @return: the list of all DRBD secrets
315

316
    """
317
    def helper(disk, result):
318
      """Recursively gather secrets from this disk."""
319
      if disk.dev_type == constants.DT_DRBD8:
320
        result.append(disk.logical_id[5])
321
      if disk.children:
322
        for child in disk.children:
323
          helper(child, result)
324

    
325
    result = []
326
    for instance in self._config_data.instances.values():
327
      for disk in instance.disks:
328
        helper(disk, result)
329

    
330
    return result
331

    
332
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
333
    """Compute duplicate disk IDs
334

335
    @type disk: L{objects.Disk}
336
    @param disk: the disk at which to start searching
337
    @type l_ids: list
338
    @param l_ids: list of current logical ids
339
    @type p_ids: list
340
    @param p_ids: list of current physical ids
341
    @rtype: list
342
    @return: a list of error messages
343

344
    """
345
    result = []
346
    if disk.logical_id is not None:
347
      if disk.logical_id in l_ids:
348
        result.append("duplicate logical id %s" % str(disk.logical_id))
349
      else:
350
        l_ids.append(disk.logical_id)
351
    if disk.physical_id is not None:
352
      if disk.physical_id in p_ids:
353
        result.append("duplicate physical id %s" % str(disk.physical_id))
354
      else:
355
        p_ids.append(disk.physical_id)
356

    
357
    if disk.children:
358
      for child in disk.children:
359
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
360
    return result
361

    
362
  def _UnlockedVerifyConfig(self):
363
    """Verify function.
364

365
    @rtype: list
366
    @return: a list of error messages; a non-empty list signifies
367
        configuration errors
368

369
    """
370
    result = []
371
    seen_macs = []
372
    ports = {}
373
    data = self._config_data
374
    seen_lids = []
375
    seen_pids = []
376

    
377
    # global cluster checks
378
    if not data.cluster.enabled_hypervisors:
379
      result.append("enabled hypervisors list doesn't have any entries")
380
    invalid_hvs = set(data.cluster.enabled_hypervisors) - constants.HYPER_TYPES
381
    if invalid_hvs:
382
      result.append("enabled hypervisors contains invalid entries: %s" %
383
                    invalid_hvs)
384
    missing_hvp = (set(data.cluster.enabled_hypervisors) -
385
                   set(data.cluster.hvparams.keys()))
386
    if missing_hvp:
387
      result.append("hypervisor parameters missing for the enabled"
388
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
389

    
390
    if data.cluster.master_node not in data.nodes:
391
      result.append("cluster has invalid primary node '%s'" %
392
                    data.cluster.master_node)
393

    
394
    # per-instance checks
395
    for instance_name in data.instances:
396
      instance = data.instances[instance_name]
397
      if instance.name != instance_name:
398
        result.append("instance '%s' is indexed by wrong name '%s'" %
399
                      (instance.name, instance_name))
400
      if instance.primary_node not in data.nodes:
401
        result.append("instance '%s' has invalid primary node '%s'" %
402
                      (instance_name, instance.primary_node))
403
      for snode in instance.secondary_nodes:
404
        if snode not in data.nodes:
405
          result.append("instance '%s' has invalid secondary node '%s'" %
406
                        (instance_name, snode))
407
      for idx, nic in enumerate(instance.nics):
408
        if nic.mac in seen_macs:
409
          result.append("instance '%s' has NIC %d mac %s duplicate" %
410
                        (instance_name, idx, nic.mac))
411
        else:
412
          seen_macs.append(nic.mac)
413

    
414
      # gather the drbd ports for duplicate checks
415
      for dsk in instance.disks:
416
        if dsk.dev_type in constants.LDS_DRBD:
417
          tcp_port = dsk.logical_id[2]
418
          if tcp_port not in ports:
419
            ports[tcp_port] = []
420
          ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
421
      # gather network port reservation
422
      net_port = getattr(instance, "network_port", None)
423
      if net_port is not None:
424
        if net_port not in ports:
425
          ports[net_port] = []
426
        ports[net_port].append((instance.name, "network port"))
427

    
428
      # instance disk verify
429
      for idx, disk in enumerate(instance.disks):
430
        result.extend(["instance '%s' disk %d error: %s" %
431
                       (instance.name, idx, msg) for msg in disk.Verify()])
432
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
433

    
434
    # cluster-wide pool of free ports
435
    for free_port in data.cluster.tcpudp_port_pool:
436
      if free_port not in ports:
437
        ports[free_port] = []
438
      ports[free_port].append(("cluster", "port marked as free"))
439

    
440
    # compute tcp/udp duplicate ports
441
    keys = ports.keys()
442
    keys.sort()
443
    for pnum in keys:
444
      pdata = ports[pnum]
445
      if len(pdata) > 1:
446
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
447
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
448

    
449
    # highest used tcp port check
450
    if keys:
451
      if keys[-1] > data.cluster.highest_used_port:
452
        result.append("Highest used port mismatch, saved %s, computed %s" %
453
                      (data.cluster.highest_used_port, keys[-1]))
454

    
455
    if not data.nodes[data.cluster.master_node].master_candidate:
456
      result.append("Master node is not a master candidate")
457

    
458
    # master candidate checks
459
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
460
    if mc_now < mc_max:
461
      result.append("Not enough master candidates: actual %d, target %d" %
462
                    (mc_now, mc_max))
463

    
464
    # node checks
465
    for node_name, node in data.nodes.items():
466
      if node.name != node_name:
467
        result.append("Node '%s' is indexed by wrong name '%s'" %
468
                      (node.name, node_name))
469
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
470
        result.append("Node %s state is invalid: master_candidate=%s,"
471
                      " drain=%s, offline=%s" %
472
                      (node.name, node.master_candidate, node.drained,
473
                       node.offline))
474

    
475
    # nodegroups checks
476
    nodegroups_names = set()
477
    for nodegroup_uuid in data.nodegroups:
478
      nodegroup = data.nodegroups[nodegroup_uuid]
479
      if nodegroup.uuid != nodegroup_uuid:
480
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
481
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
482
      if utils.UUID_RE.match(nodegroup.name.lower()):
483
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
484
                      (nodegroup.name, nodegroup.uuid))
485
      if nodegroup.name in nodegroups_names:
486
        result.append("duplicate node group name '%s'" % nodegroup.name)
487
      else:
488
        nodegroups_names.add(nodegroup.name)
489

    
490
    # drbd minors check
491
    _, duplicates = self._UnlockedComputeDRBDMap()
492
    for node, minor, instance_a, instance_b in duplicates:
493
      result.append("DRBD minor %d on node %s is assigned twice to instances"
494
                    " %s and %s" % (minor, node, instance_a, instance_b))
495

    
496
    # IP checks
497
    default_nicparams = data.cluster.nicparams[constants.PP_DEFAULT]
498
    ips = {}
499

    
500
    def _AddIpAddress(ip, name):
501
      ips.setdefault(ip, []).append(name)
502

    
503
    _AddIpAddress(data.cluster.master_ip, "cluster_ip")
504

    
505
    for node in data.nodes.values():
506
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
507
      if node.secondary_ip != node.primary_ip:
508
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
509

    
510
    for instance in data.instances.values():
511
      for idx, nic in enumerate(instance.nics):
512
        if nic.ip is None:
513
          continue
514

    
515
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
516
        nic_mode = nicparams[constants.NIC_MODE]
517
        nic_link = nicparams[constants.NIC_LINK]
518

    
519
        if nic_mode == constants.NIC_MODE_BRIDGED:
520
          link = "bridge:%s" % nic_link
521
        elif nic_mode == constants.NIC_MODE_ROUTED:
522
          link = "route:%s" % nic_link
523
        else:
524
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
525

    
526
        _AddIpAddress("%s/%s" % (link, nic.ip),
527
                      "instance:%s/nic:%d" % (instance.name, idx))
528

    
529
    for ip, owners in ips.items():
530
      if len(owners) > 1:
531
        result.append("IP address %s is used by multiple owners: %s" %
532
                      (ip, utils.CommaJoin(owners)))
533

    
534
    return result
535

    
536
  @locking.ssynchronized(_config_lock, shared=1)
537
  def VerifyConfig(self):
538
    """Verify function.
539

540
    This is just a wrapper over L{_UnlockedVerifyConfig}.
541

542
    @rtype: list
543
    @return: a list of error messages; a non-empty list signifies
544
        configuration errors
545

546
    """
547
    return self._UnlockedVerifyConfig()
548

    
549
  def _UnlockedSetDiskID(self, disk, node_name):
550
    """Convert the unique ID to the ID needed on the target nodes.
551

552
    This is used only for drbd, which needs ip/port configuration.
553

554
    The routine descends down and updates its children also, because
555
    this helps when the only the top device is passed to the remote
556
    node.
557

558
    This function is for internal use, when the config lock is already held.
559

560
    """
561
    if disk.children:
562
      for child in disk.children:
563
        self._UnlockedSetDiskID(child, node_name)
564

    
565
    if disk.logical_id is None and disk.physical_id is not None:
566
      return
567
    if disk.dev_type == constants.LD_DRBD8:
568
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
569
      if node_name not in (pnode, snode):
570
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
571
                                        node_name)
572
      pnode_info = self._UnlockedGetNodeInfo(pnode)
573
      snode_info = self._UnlockedGetNodeInfo(snode)
574
      if pnode_info is None or snode_info is None:
575
        raise errors.ConfigurationError("Can't find primary or secondary node"
576
                                        " for %s" % str(disk))
577
      p_data = (pnode_info.secondary_ip, port)
578
      s_data = (snode_info.secondary_ip, port)
579
      if pnode == node_name:
580
        disk.physical_id = p_data + s_data + (pminor, secret)
581
      else: # it must be secondary, we tested above
582
        disk.physical_id = s_data + p_data + (sminor, secret)
583
    else:
584
      disk.physical_id = disk.logical_id
585
    return
586

    
587
  @locking.ssynchronized(_config_lock)
588
  def SetDiskID(self, disk, node_name):
589
    """Convert the unique ID to the ID needed on the target nodes.
590

591
    This is used only for drbd, which needs ip/port configuration.
592

593
    The routine descends down and updates its children also, because
594
    this helps when the only the top device is passed to the remote
595
    node.
596

597
    """
598
    return self._UnlockedSetDiskID(disk, node_name)
599

    
600
  @locking.ssynchronized(_config_lock)
601
  def AddTcpUdpPort(self, port):
602
    """Adds a new port to the available port pool.
603

604
    """
605
    if not isinstance(port, int):
606
      raise errors.ProgrammerError("Invalid type passed for port")
607

    
608
    self._config_data.cluster.tcpudp_port_pool.add(port)
609
    self._WriteConfig()
610

    
611
  @locking.ssynchronized(_config_lock, shared=1)
612
  def GetPortList(self):
613
    """Returns a copy of the current port list.
614

615
    """
616
    return self._config_data.cluster.tcpudp_port_pool.copy()
617

    
618
  @locking.ssynchronized(_config_lock)
619
  def AllocatePort(self):
620
    """Allocate a port.
621

622
    The port will be taken from the available port pool or from the
623
    default port range (and in this case we increase
624
    highest_used_port).
625

626
    """
627
    # If there are TCP/IP ports configured, we use them first.
628
    if self._config_data.cluster.tcpudp_port_pool:
629
      port = self._config_data.cluster.tcpudp_port_pool.pop()
630
    else:
631
      port = self._config_data.cluster.highest_used_port + 1
632
      if port >= constants.LAST_DRBD_PORT:
633
        raise errors.ConfigurationError("The highest used port is greater"
634
                                        " than %s. Aborting." %
635
                                        constants.LAST_DRBD_PORT)
636
      self._config_data.cluster.highest_used_port = port
637

    
638
    self._WriteConfig()
639
    return port
640

    
641
  def _UnlockedComputeDRBDMap(self):
642
    """Compute the used DRBD minor/nodes.
643

644
    @rtype: (dict, list)
645
    @return: dictionary of node_name: dict of minor: instance_name;
646
        the returned dict will have all the nodes in it (even if with
647
        an empty list), and a list of duplicates; if the duplicates
648
        list is not empty, the configuration is corrupted and its caller
649
        should raise an exception
650

651
    """
652
    def _AppendUsedPorts(instance_name, disk, used):
653
      duplicates = []
654
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
655
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
656
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
657
          assert node in used, ("Node '%s' of instance '%s' not found"
658
                                " in node list" % (node, instance_name))
659
          if port in used[node]:
660
            duplicates.append((node, port, instance_name, used[node][port]))
661
          else:
662
            used[node][port] = instance_name
663
      if disk.children:
664
        for child in disk.children:
665
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
666
      return duplicates
667

    
668
    duplicates = []
669
    my_dict = dict((node, {}) for node in self._config_data.nodes)
670
    for instance in self._config_data.instances.itervalues():
671
      for disk in instance.disks:
672
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
673
    for (node, minor), instance in self._temporary_drbds.iteritems():
674
      if minor in my_dict[node] and my_dict[node][minor] != instance:
675
        duplicates.append((node, minor, instance, my_dict[node][minor]))
676
      else:
677
        my_dict[node][minor] = instance
678
    return my_dict, duplicates
679

    
680
  @locking.ssynchronized(_config_lock)
681
  def ComputeDRBDMap(self):
682
    """Compute the used DRBD minor/nodes.
683

684
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
685

686
    @return: dictionary of node_name: dict of minor: instance_name;
687
        the returned dict will have all the nodes in it (even if with
688
        an empty list).
689

690
    """
691
    d_map, duplicates = self._UnlockedComputeDRBDMap()
692
    if duplicates:
693
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
694
                                      str(duplicates))
695
    return d_map
696

    
697
  @locking.ssynchronized(_config_lock)
698
  def AllocateDRBDMinor(self, nodes, instance):
699
    """Allocate a drbd minor.
700

701
    The free minor will be automatically computed from the existing
702
    devices. A node can be given multiple times in order to allocate
703
    multiple minors. The result is the list of minors, in the same
704
    order as the passed nodes.
705

706
    @type instance: string
707
    @param instance: the instance for which we allocate minors
708

709
    """
710
    assert isinstance(instance, basestring), \
711
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
712

    
713
    d_map, duplicates = self._UnlockedComputeDRBDMap()
714
    if duplicates:
715
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
716
                                      str(duplicates))
717
    result = []
718
    for nname in nodes:
719
      ndata = d_map[nname]
720
      if not ndata:
721
        # no minors used, we can start at 0
722
        result.append(0)
723
        ndata[0] = instance
724
        self._temporary_drbds[(nname, 0)] = instance
725
        continue
726
      keys = ndata.keys()
727
      keys.sort()
728
      ffree = utils.FirstFree(keys)
729
      if ffree is None:
730
        # return the next minor
731
        # TODO: implement high-limit check
732
        minor = keys[-1] + 1
733
      else:
734
        minor = ffree
735
      # double-check minor against current instances
736
      assert minor not in d_map[nname], \
737
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
738
              " already allocated to instance %s" %
739
              (minor, nname, d_map[nname][minor]))
740
      ndata[minor] = instance
741
      # double-check minor against reservation
742
      r_key = (nname, minor)
743
      assert r_key not in self._temporary_drbds, \
744
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
745
              " reserved for instance %s" %
746
              (minor, nname, self._temporary_drbds[r_key]))
747
      self._temporary_drbds[r_key] = instance
748
      result.append(minor)
749
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
750
                  nodes, result)
751
    return result
752

    
753
  def _UnlockedReleaseDRBDMinors(self, instance):
754
    """Release temporary drbd minors allocated for a given instance.
755

756
    @type instance: string
757
    @param instance: the instance for which temporary minors should be
758
                     released
759

760
    """
761
    assert isinstance(instance, basestring), \
762
           "Invalid argument passed to ReleaseDRBDMinors"
763
    for key, name in self._temporary_drbds.items():
764
      if name == instance:
765
        del self._temporary_drbds[key]
766

    
767
  @locking.ssynchronized(_config_lock)
768
  def ReleaseDRBDMinors(self, instance):
769
    """Release temporary drbd minors allocated for a given instance.
770

771
    This should be called on the error paths, on the success paths
772
    it's automatically called by the ConfigWriter add and update
773
    functions.
774

775
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
776

777
    @type instance: string
778
    @param instance: the instance for which temporary minors should be
779
                     released
780

781
    """
782
    self._UnlockedReleaseDRBDMinors(instance)
783

    
784
  @locking.ssynchronized(_config_lock, shared=1)
785
  def GetConfigVersion(self):
786
    """Get the configuration version.
787

788
    @return: Config version
789

790
    """
791
    return self._config_data.version
792

    
793
  @locking.ssynchronized(_config_lock, shared=1)
794
  def GetClusterName(self):
795
    """Get cluster name.
796

797
    @return: Cluster name
798

799
    """
800
    return self._config_data.cluster.cluster_name
801

    
802
  @locking.ssynchronized(_config_lock, shared=1)
803
  def GetMasterNode(self):
804
    """Get the hostname of the master node for this cluster.
805

806
    @return: Master hostname
807

808
    """
809
    return self._config_data.cluster.master_node
810

    
811
  @locking.ssynchronized(_config_lock, shared=1)
812
  def GetMasterIP(self):
813
    """Get the IP of the master node for this cluster.
814

815
    @return: Master IP
816

817
    """
818
    return self._config_data.cluster.master_ip
819

    
820
  @locking.ssynchronized(_config_lock, shared=1)
821
  def GetMasterNetdev(self):
822
    """Get the master network device for this cluster.
823

824
    """
825
    return self._config_data.cluster.master_netdev
826

    
827
  @locking.ssynchronized(_config_lock, shared=1)
828
  def GetFileStorageDir(self):
829
    """Get the file storage dir for this cluster.
830

831
    """
832
    return self._config_data.cluster.file_storage_dir
833

    
834
  @locking.ssynchronized(_config_lock, shared=1)
835
  def GetHypervisorType(self):
836
    """Get the hypervisor type for this cluster.
837

838
    """
839
    return self._config_data.cluster.enabled_hypervisors[0]
840

    
841
  @locking.ssynchronized(_config_lock, shared=1)
842
  def GetHostKey(self):
843
    """Return the rsa hostkey from the config.
844

845
    @rtype: string
846
    @return: the rsa hostkey
847

848
    """
849
    return self._config_data.cluster.rsahostkeypub
850

    
851
  @locking.ssynchronized(_config_lock, shared=1)
852
  def GetDefaultIAllocator(self):
853
    """Get the default instance allocator for this cluster.
854

855
    """
856
    return self._config_data.cluster.default_iallocator
857

    
858
  @locking.ssynchronized(_config_lock, shared=1)
859
  def GetPrimaryIPFamily(self):
860
    """Get cluster primary ip family.
861

862
    @return: primary ip family
863

864
    """
865
    return self._config_data.cluster.primary_ip_family
866

    
867
  @locking.ssynchronized(_config_lock)
868
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
869
    """Add a node group to the configuration.
870

871
    This method calls group.UpgradeConfig() to fill any missing attributes
872
    according to their default values.
873

874
    @type group: L{objects.NodeGroup}
875
    @param group: the NodeGroup object to add
876
    @type ec_id: string
877
    @param ec_id: unique id for the job to use when creating a missing UUID
878
    @type check_uuid: bool
879
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
880
                       it does, ensure that it does not exist in the
881
                       configuration already
882

883
    """
884
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
885
    self._WriteConfig()
886

    
887
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
888
    """Add a node group to the configuration.
889

890
    """
891
    logging.info("Adding node group %s to configuration", group.name)
892

    
893
    # Some code might need to add a node group with a pre-populated UUID
894
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
895
    # the "does this UUID" exist already check.
896
    if check_uuid:
897
      self._EnsureUUID(group, ec_id)
898

    
899
    group.serial_no = 1
900
    group.ctime = group.mtime = time.time()
901
    group.UpgradeConfig()
902

    
903
    self._config_data.nodegroups[group.uuid] = group
904
    self._config_data.cluster.serial_no += 1
905

    
906
  @locking.ssynchronized(_config_lock)
907
  def RemoveNodeGroup(self, group_uuid):
908
    """Remove a node group from the configuration.
909

910
    @type group_uuid: string
911
    @param group_uuid: the UUID of the node group to remove
912

913
    """
914
    logging.info("Removing node group %s from configuration", group_uuid)
915

    
916
    if group_uuid not in self._config_data.nodegroups:
917
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
918

    
919
    del self._config_data.nodegroups[group_uuid]
920
    self._config_data.cluster.serial_no += 1
921
    self._WriteConfig()
922

    
923
  @locking.ssynchronized(_config_lock, shared=1)
924
  def LookupNodeGroup(self, target):
925
    """Lookup a node group's UUID.
926

927
    @type target: string or None
928
    @param target: group name or UUID or None to look for the default
929
    @rtype: string
930
    @return: nodegroup UUID
931
    @raises errors.OpPrereqError: when the target group cannot be found
932

933
    """
934
    if target is None:
935
      if len(self._config_data.nodegroups) != 1:
936
        raise errors.OpPrereqError("More than one node group exists. Target"
937
                                   " group must be specified explicitely.")
938
      else:
939
        return self._config_data.nodegroups.keys()[0]
940
    if target in self._config_data.nodegroups:
941
      return target
942
    for nodegroup in self._config_data.nodegroups.values():
943
      if nodegroup.name == target:
944
        return nodegroup.uuid
945
    raise errors.OpPrereqError("Node group '%s' not found" % target,
946
                               errors.ECODE_NOENT)
947

    
948
  def _UnlockedGetNodeGroup(self, uuid):
949
    """Lookup a node group.
950

951
    @type uuid: string
952
    @param uuid: group UUID
953
    @rtype: L{objects.NodeGroup} or None
954
    @return: nodegroup object, or None if not found
955

956
    """
957
    if uuid not in self._config_data.nodegroups:
958
      return None
959

    
960
    return self._config_data.nodegroups[uuid]
961

    
962
  @locking.ssynchronized(_config_lock, shared=1)
963
  def GetNodeGroup(self, uuid):
964
    """Lookup a node group.
965

966
    @type uuid: string
967
    @param uuid: group UUID
968
    @rtype: L{objects.NodeGroup} or None
969
    @return: nodegroup object, or None if not found
970

971
    """
972
    return self._UnlockedGetNodeGroup(uuid)
973

    
974
  @locking.ssynchronized(_config_lock, shared=1)
975
  def GetAllNodeGroupsInfo(self):
976
    """Get the configuration of all node groups.
977

978
    """
979
    return dict(self._config_data.nodegroups)
980

    
981
  @locking.ssynchronized(_config_lock, shared=1)
982
  def GetNodeGroupList(self):
983
    """Get a list of node groups.
984

985
    """
986
    return self._config_data.nodegroups.keys()
987

    
988
  @locking.ssynchronized(_config_lock)
989
  def AddInstance(self, instance, ec_id):
990
    """Add an instance to the config.
991

992
    This should be used after creating a new instance.
993

994
    @type instance: L{objects.Instance}
995
    @param instance: the instance object
996

997
    """
998
    if not isinstance(instance, objects.Instance):
999
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1000

    
1001
    if instance.disk_template != constants.DT_DISKLESS:
1002
      all_lvs = instance.MapLVsByNode()
1003
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1004

    
1005
    all_macs = self._AllMACs()
1006
    for nic in instance.nics:
1007
      if nic.mac in all_macs:
1008
        raise errors.ConfigurationError("Cannot add instance %s:"
1009
                                        " MAC address '%s' already in use." %
1010
                                        (instance.name, nic.mac))
1011

    
1012
    self._EnsureUUID(instance, ec_id)
1013

    
1014
    instance.serial_no = 1
1015
    instance.ctime = instance.mtime = time.time()
1016
    self._config_data.instances[instance.name] = instance
1017
    self._config_data.cluster.serial_no += 1
1018
    self._UnlockedReleaseDRBDMinors(instance.name)
1019
    self._WriteConfig()
1020

    
1021
  def _EnsureUUID(self, item, ec_id):
1022
    """Ensures a given object has a valid UUID.
1023

1024
    @param item: the instance or node to be checked
1025
    @param ec_id: the execution context id for the uuid reservation
1026

1027
    """
1028
    if not item.uuid:
1029
      item.uuid = self._GenerateUniqueID(ec_id)
1030
    elif item.uuid in self._AllIDs(include_temporary=True):
1031
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1032
                                      " in use" % (item.name, item.uuid))
1033

    
1034
  def _SetInstanceStatus(self, instance_name, status):
1035
    """Set the instance's status to a given value.
1036

1037
    """
1038
    assert isinstance(status, bool), \
1039
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1040

    
1041
    if instance_name not in self._config_data.instances:
1042
      raise errors.ConfigurationError("Unknown instance '%s'" %
1043
                                      instance_name)
1044
    instance = self._config_data.instances[instance_name]
1045
    if instance.admin_up != status:
1046
      instance.admin_up = status
1047
      instance.serial_no += 1
1048
      instance.mtime = time.time()
1049
      self._WriteConfig()
1050

    
1051
  @locking.ssynchronized(_config_lock)
1052
  def MarkInstanceUp(self, instance_name):
1053
    """Mark the instance status to up in the config.
1054

1055
    """
1056
    self._SetInstanceStatus(instance_name, True)
1057

    
1058
  @locking.ssynchronized(_config_lock)
1059
  def RemoveInstance(self, instance_name):
1060
    """Remove the instance from the configuration.
1061

1062
    """
1063
    if instance_name not in self._config_data.instances:
1064
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1065
    del self._config_data.instances[instance_name]
1066
    self._config_data.cluster.serial_no += 1
1067
    self._WriteConfig()
1068

    
1069
  @locking.ssynchronized(_config_lock)
1070
  def RenameInstance(self, old_name, new_name):
1071
    """Rename an instance.
1072

1073
    This needs to be done in ConfigWriter and not by RemoveInstance
1074
    combined with AddInstance as only we can guarantee an atomic
1075
    rename.
1076

1077
    """
1078
    if old_name not in self._config_data.instances:
1079
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1080
    inst = self._config_data.instances[old_name]
1081
    del self._config_data.instances[old_name]
1082
    inst.name = new_name
1083

    
1084
    for disk in inst.disks:
1085
      if disk.dev_type == constants.LD_FILE:
1086
        # rename the file paths in logical and physical id
1087
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1088
        disk_fname = "disk%s" % disk.iv_name.split("/")[1]
1089
        disk.physical_id = disk.logical_id = (disk.logical_id[0],
1090
                                              utils.PathJoin(file_storage_dir,
1091
                                                             inst.name,
1092
                                                             disk_fname))
1093

    
1094
    # Force update of ssconf files
1095
    self._config_data.cluster.serial_no += 1
1096

    
1097
    self._config_data.instances[inst.name] = inst
1098
    self._WriteConfig()
1099

    
1100
  @locking.ssynchronized(_config_lock)
1101
  def MarkInstanceDown(self, instance_name):
1102
    """Mark the status of an instance to down in the configuration.
1103

1104
    """
1105
    self._SetInstanceStatus(instance_name, False)
1106

    
1107
  def _UnlockedGetInstanceList(self):
1108
    """Get the list of instances.
1109

1110
    This function is for internal use, when the config lock is already held.
1111

1112
    """
1113
    return self._config_data.instances.keys()
1114

    
1115
  @locking.ssynchronized(_config_lock, shared=1)
1116
  def GetInstanceList(self):
1117
    """Get the list of instances.
1118

1119
    @return: array of instances, ex. ['instance2.example.com',
1120
        'instance1.example.com']
1121

1122
    """
1123
    return self._UnlockedGetInstanceList()
1124

    
1125
  @locking.ssynchronized(_config_lock, shared=1)
1126
  def ExpandInstanceName(self, short_name):
1127
    """Attempt to expand an incomplete instance name.
1128

1129
    """
1130
    return utils.MatchNameComponent(short_name,
1131
                                    self._config_data.instances.keys(),
1132
                                    case_sensitive=False)
1133

    
1134
  def _UnlockedGetInstanceInfo(self, instance_name):
1135
    """Returns information about an instance.
1136

1137
    This function is for internal use, when the config lock is already held.
1138

1139
    """
1140
    if instance_name not in self._config_data.instances:
1141
      return None
1142

    
1143
    return self._config_data.instances[instance_name]
1144

    
1145
  @locking.ssynchronized(_config_lock, shared=1)
1146
  def GetInstanceInfo(self, instance_name):
1147
    """Returns information about an instance.
1148

1149
    It takes the information from the configuration file. Other information of
1150
    an instance are taken from the live systems.
1151

1152
    @param instance_name: name of the instance, e.g.
1153
        I{instance1.example.com}
1154

1155
    @rtype: L{objects.Instance}
1156
    @return: the instance object
1157

1158
    """
1159
    return self._UnlockedGetInstanceInfo(instance_name)
1160

    
1161
  @locking.ssynchronized(_config_lock, shared=1)
1162
  def GetAllInstancesInfo(self):
1163
    """Get the configuration of all instances.
1164

1165
    @rtype: dict
1166
    @return: dict of (instance, instance_info), where instance_info is what
1167
              would GetInstanceInfo return for the node
1168

1169
    """
1170
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1171
                    for instance in self._UnlockedGetInstanceList()])
1172
    return my_dict
1173

    
1174
  @locking.ssynchronized(_config_lock)
1175
  def AddNode(self, node, ec_id):
1176
    """Add a node to the configuration.
1177

1178
    @type node: L{objects.Node}
1179
    @param node: a Node instance
1180

1181
    """
1182
    logging.info("Adding node %s to configuration", node.name)
1183

    
1184
    self._EnsureUUID(node, ec_id)
1185

    
1186
    node.serial_no = 1
1187
    node.ctime = node.mtime = time.time()
1188
    self._UnlockedAddNodeToGroup(node.name, node.group)
1189
    self._config_data.nodes[node.name] = node
1190
    self._config_data.cluster.serial_no += 1
1191
    self._WriteConfig()
1192

    
1193
  @locking.ssynchronized(_config_lock)
1194
  def RemoveNode(self, node_name):
1195
    """Remove a node from the configuration.
1196

1197
    """
1198
    logging.info("Removing node %s from configuration", node_name)
1199

    
1200
    if node_name not in self._config_data.nodes:
1201
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1202

    
1203
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1204
    del self._config_data.nodes[node_name]
1205
    self._config_data.cluster.serial_no += 1
1206
    self._WriteConfig()
1207

    
1208
  @locking.ssynchronized(_config_lock, shared=1)
1209
  def ExpandNodeName(self, short_name):
1210
    """Attempt to expand an incomplete instance name.
1211

1212
    """
1213
    return utils.MatchNameComponent(short_name,
1214
                                    self._config_data.nodes.keys(),
1215
                                    case_sensitive=False)
1216

    
1217
  def _UnlockedGetNodeInfo(self, node_name):
1218
    """Get the configuration of a node, as stored in the config.
1219

1220
    This function is for internal use, when the config lock is already
1221
    held.
1222

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

1225
    @rtype: L{objects.Node}
1226
    @return: the node object
1227

1228
    """
1229
    if node_name not in self._config_data.nodes:
1230
      return None
1231

    
1232
    return self._config_data.nodes[node_name]
1233

    
1234
  @locking.ssynchronized(_config_lock, shared=1)
1235
  def GetNodeInfo(self, node_name):
1236
    """Get the configuration of a node, as stored in the config.
1237

1238
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1239

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

1242
    @rtype: L{objects.Node}
1243
    @return: the node object
1244

1245
    """
1246
    return self._UnlockedGetNodeInfo(node_name)
1247

    
1248
  @locking.ssynchronized(_config_lock, shared=1)
1249
  def GetNodeInstances(self, node_name):
1250
    """Get the instances of a node, as stored in the config.
1251

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

1254
    @rtype: (list, list)
1255
    @return: a tuple with two lists: the primary and the secondary instances
1256

1257
    """
1258
    pri = []
1259
    sec = []
1260
    for inst in self._config_data.instances.values():
1261
      if inst.primary_node == node_name:
1262
        pri.append(inst.name)
1263
      if node_name in inst.secondary_nodes:
1264
        sec.append(inst.name)
1265
    return (pri, sec)
1266

    
1267
  def _UnlockedGetNodeList(self):
1268
    """Return the list of nodes which are in the configuration.
1269

1270
    This function is for internal use, when the config lock is already
1271
    held.
1272

1273
    @rtype: list
1274

1275
    """
1276
    return self._config_data.nodes.keys()
1277

    
1278
  @locking.ssynchronized(_config_lock, shared=1)
1279
  def GetNodeList(self):
1280
    """Return the list of nodes which are in the configuration.
1281

1282
    """
1283
    return self._UnlockedGetNodeList()
1284

    
1285
  def _UnlockedGetOnlineNodeList(self):
1286
    """Return the list of nodes which are online.
1287

1288
    """
1289
    all_nodes = [self._UnlockedGetNodeInfo(node)
1290
                 for node in self._UnlockedGetNodeList()]
1291
    return [node.name for node in all_nodes if not node.offline]
1292

    
1293
  @locking.ssynchronized(_config_lock, shared=1)
1294
  def GetOnlineNodeList(self):
1295
    """Return the list of nodes which are online.
1296

1297
    """
1298
    return self._UnlockedGetOnlineNodeList()
1299

    
1300
  @locking.ssynchronized(_config_lock, shared=1)
1301
  def GetVmCapableNodeList(self):
1302
    """Return the list of nodes which are not vm capable.
1303

1304
    """
1305
    all_nodes = [self._UnlockedGetNodeInfo(node)
1306
                 for node in self._UnlockedGetNodeList()]
1307
    return [node.name for node in all_nodes if node.vm_capable]
1308

    
1309
  @locking.ssynchronized(_config_lock, shared=1)
1310
  def GetNonVmCapableNodeList(self):
1311
    """Return the list of nodes which are not vm capable.
1312

1313
    """
1314
    all_nodes = [self._UnlockedGetNodeInfo(node)
1315
                 for node in self._UnlockedGetNodeList()]
1316
    return [node.name for node in all_nodes if not node.vm_capable]
1317

    
1318
  @locking.ssynchronized(_config_lock, shared=1)
1319
  def GetAllNodesInfo(self):
1320
    """Get the configuration of all nodes.
1321

1322
    @rtype: dict
1323
    @return: dict of (node, node_info), where node_info is what
1324
              would GetNodeInfo return for the node
1325

1326
    """
1327
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
1328
                    for node in self._UnlockedGetNodeList()])
1329
    return my_dict
1330

    
1331
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1332
    """Get the number of current and maximum desired and possible candidates.
1333

1334
    @type exceptions: list
1335
    @param exceptions: if passed, list of nodes that should be ignored
1336
    @rtype: tuple
1337
    @return: tuple of (current, desired and possible, possible)
1338

1339
    """
1340
    mc_now = mc_should = mc_max = 0
1341
    for node in self._config_data.nodes.values():
1342
      if exceptions and node.name in exceptions:
1343
        continue
1344
      if not (node.offline or node.drained) and node.master_capable:
1345
        mc_max += 1
1346
      if node.master_candidate:
1347
        mc_now += 1
1348
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1349
    return (mc_now, mc_should, mc_max)
1350

    
1351
  @locking.ssynchronized(_config_lock, shared=1)
1352
  def GetMasterCandidateStats(self, exceptions=None):
1353
    """Get the number of current and maximum possible candidates.
1354

1355
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1356

1357
    @type exceptions: list
1358
    @param exceptions: if passed, list of nodes that should be ignored
1359
    @rtype: tuple
1360
    @return: tuple of (current, max)
1361

1362
    """
1363
    return self._UnlockedGetMasterCandidateStats(exceptions)
1364

    
1365
  @locking.ssynchronized(_config_lock)
1366
  def MaintainCandidatePool(self, exceptions):
1367
    """Try to grow the candidate pool to the desired size.
1368

1369
    @type exceptions: list
1370
    @param exceptions: if passed, list of nodes that should be ignored
1371
    @rtype: list
1372
    @return: list with the adjusted nodes (L{objects.Node} instances)
1373

1374
    """
1375
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1376
    mod_list = []
1377
    if mc_now < mc_max:
1378
      node_list = self._config_data.nodes.keys()
1379
      random.shuffle(node_list)
1380
      for name in node_list:
1381
        if mc_now >= mc_max:
1382
          break
1383
        node = self._config_data.nodes[name]
1384
        if (node.master_candidate or node.offline or node.drained or
1385
            node.name in exceptions or not node.master_capable):
1386
          continue
1387
        mod_list.append(node)
1388
        node.master_candidate = True
1389
        node.serial_no += 1
1390
        mc_now += 1
1391
      if mc_now != mc_max:
1392
        # this should not happen
1393
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1394
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1395
      if mod_list:
1396
        self._config_data.cluster.serial_no += 1
1397
        self._WriteConfig()
1398

    
1399
    return mod_list
1400

    
1401
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1402
    """Add a given node to the specified group.
1403

1404
    """
1405
    if nodegroup_uuid not in self._config_data.nodegroups:
1406
      # This can happen if a node group gets deleted between its lookup and
1407
      # when we're adding the first node to it, since we don't keep a lock in
1408
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1409
      # is not found anymore.
1410
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1411
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1412
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1413

    
1414
  def _UnlockedRemoveNodeFromGroup(self, node):
1415
    """Remove a given node from its group.
1416

1417
    """
1418
    nodegroup = node.group
1419
    if nodegroup not in self._config_data.nodegroups:
1420
      logging.warning("Warning: node '%s' has unknown node group '%s'"
1421
                      " (while being removed from it)", node.name, nodegroup)
1422
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1423
    if node.name not in nodegroup_obj.members:
1424
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
1425
                      " (while being removed from it)", node.name, nodegroup)
1426
    else:
1427
      nodegroup_obj.members.remove(node.name)
1428

    
1429
  def _BumpSerialNo(self):
1430
    """Bump up the serial number of the config.
1431

1432
    """
1433
    self._config_data.serial_no += 1
1434
    self._config_data.mtime = time.time()
1435

    
1436
  def _AllUUIDObjects(self):
1437
    """Returns all objects with uuid attributes.
1438

1439
    """
1440
    return (self._config_data.instances.values() +
1441
            self._config_data.nodes.values() +
1442
            self._config_data.nodegroups.values() +
1443
            [self._config_data.cluster])
1444

    
1445
  def _OpenConfig(self, accept_foreign):
1446
    """Read the config data from disk.
1447

1448
    """
1449
    raw_data = utils.ReadFile(self._cfg_file)
1450

    
1451
    try:
1452
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1453
    except Exception, err:
1454
      raise errors.ConfigurationError(err)
1455

    
1456
    # Make sure the configuration has the right version
1457
    _ValidateConfig(data)
1458

    
1459
    if (not hasattr(data, 'cluster') or
1460
        not hasattr(data.cluster, 'rsahostkeypub')):
1461
      raise errors.ConfigurationError("Incomplete configuration"
1462
                                      " (missing cluster.rsahostkeypub)")
1463

    
1464
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
1465
      msg = ("The configuration denotes node %s as master, while my"
1466
             " hostname is %s; opening a foreign configuration is only"
1467
             " possible in accept_foreign mode" %
1468
             (data.cluster.master_node, self._my_hostname))
1469
      raise errors.ConfigurationError(msg)
1470

    
1471
    # Upgrade configuration if needed
1472
    data.UpgradeConfig()
1473

    
1474
    self._config_data = data
1475
    # reset the last serial as -1 so that the next write will cause
1476
    # ssconf update
1477
    self._last_cluster_serial = -1
1478

    
1479
    # And finally run our (custom) config upgrade sequence
1480
    self._UpgradeConfig()
1481

    
1482
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
1483

    
1484
  def _UpgradeConfig(self):
1485
    """Run upgrade steps that cannot be done purely in the objects.
1486

1487
    This is because some data elements need uniqueness across the
1488
    whole configuration, etc.
1489

1490
    @warning: this function will call L{_WriteConfig()}, but also
1491
        L{DropECReservations} so it needs to be called only from a
1492
        "safe" place (the constructor). If one wanted to call it with
1493
        the lock held, a DropECReservationUnlocked would need to be
1494
        created first, to avoid causing deadlock.
1495

1496
    """
1497
    modified = False
1498
    for item in self._AllUUIDObjects():
1499
      if item.uuid is None:
1500
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1501
        modified = True
1502
    if not self._config_data.nodegroups:
1503
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
1504
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
1505
                                            members=[])
1506
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
1507
      modified = True
1508
    for node in self._config_data.nodes.values():
1509
      if not node.group:
1510
        node.group = self.LookupNodeGroup(None)
1511
        modified = True
1512
      # This is technically *not* an upgrade, but needs to be done both when
1513
      # nodegroups are being added, and upon normally loading the config,
1514
      # because the members list of a node group is discarded upon
1515
      # serializing/deserializing the object.
1516
      self._UnlockedAddNodeToGroup(node.name, node.group)
1517
    if modified:
1518
      self._WriteConfig()
1519
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
1520
      # only called at config init time, without the lock held
1521
      self.DropECReservations(_UPGRADE_CONFIG_JID)
1522

    
1523
  def _DistributeConfig(self, feedback_fn):
1524
    """Distribute the configuration to the other nodes.
1525

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

1529
    """
1530
    if self._offline:
1531
      return True
1532

    
1533
    bad = False
1534

    
1535
    node_list = []
1536
    addr_list = []
1537
    myhostname = self._my_hostname
1538
    # we can skip checking whether _UnlockedGetNodeInfo returns None
1539
    # since the node list comes from _UnlocketGetNodeList, and we are
1540
    # called with the lock held, so no modifications should take place
1541
    # in between
1542
    for node_name in self._UnlockedGetNodeList():
1543
      if node_name == myhostname:
1544
        continue
1545
      node_info = self._UnlockedGetNodeInfo(node_name)
1546
      if not node_info.master_candidate:
1547
        continue
1548
      node_list.append(node_info.name)
1549
      addr_list.append(node_info.primary_ip)
1550

    
1551
    result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
1552
                                            address_list=addr_list)
1553
    for to_node, to_result in result.items():
1554
      msg = to_result.fail_msg
1555
      if msg:
1556
        msg = ("Copy of file %s to node %s failed: %s" %
1557
               (self._cfg_file, to_node, msg))
1558
        logging.error(msg)
1559

    
1560
        if feedback_fn:
1561
          feedback_fn(msg)
1562

    
1563
        bad = True
1564

    
1565
    return not bad
1566

    
1567
  def _WriteConfig(self, destination=None, feedback_fn=None):
1568
    """Write the configuration data to persistent storage.
1569

1570
    """
1571
    assert feedback_fn is None or callable(feedback_fn)
1572

    
1573
    # Warn on config errors, but don't abort the save - the
1574
    # configuration has already been modified, and we can't revert;
1575
    # the best we can do is to warn the user and save as is, leaving
1576
    # recovery to the user
1577
    config_errors = self._UnlockedVerifyConfig()
1578
    if config_errors:
1579
      errmsg = ("Configuration data is not consistent: %s" %
1580
                (utils.CommaJoin(config_errors)))
1581
      logging.critical(errmsg)
1582
      if feedback_fn:
1583
        feedback_fn(errmsg)
1584

    
1585
    if destination is None:
1586
      destination = self._cfg_file
1587
    self._BumpSerialNo()
1588
    txt = serializer.Dump(self._config_data.ToDict())
1589

    
1590
    getents = self._getents()
1591
    try:
1592
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
1593
                               close=False, gid=getents.confd_gid, mode=0640)
1594
    except errors.LockError:
1595
      raise errors.ConfigurationError("The configuration file has been"
1596
                                      " modified since the last write, cannot"
1597
                                      " update")
1598
    try:
1599
      self._cfg_id = utils.GetFileID(fd=fd)
1600
    finally:
1601
      os.close(fd)
1602

    
1603
    self.write_count += 1
1604

    
1605
    # and redistribute the config file to master candidates
1606
    self._DistributeConfig(feedback_fn)
1607

    
1608
    # Write ssconf files on all nodes (including locally)
1609
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
1610
      if not self._offline:
1611
        result = rpc.RpcRunner.call_write_ssconf_files(
1612
          self._UnlockedGetOnlineNodeList(),
1613
          self._UnlockedGetSsconfValues())
1614

    
1615
        for nname, nresu in result.items():
1616
          msg = nresu.fail_msg
1617
          if msg:
1618
            errmsg = ("Error while uploading ssconf files to"
1619
                      " node %s: %s" % (nname, msg))
1620
            logging.warning(errmsg)
1621

    
1622
            if feedback_fn:
1623
              feedback_fn(errmsg)
1624

    
1625
      self._last_cluster_serial = self._config_data.cluster.serial_no
1626

    
1627
  def _UnlockedGetSsconfValues(self):
1628
    """Return the values needed by ssconf.
1629

1630
    @rtype: dict
1631
    @return: a dictionary with keys the ssconf names and values their
1632
        associated value
1633

1634
    """
1635
    fn = "\n".join
1636
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1637
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
1638
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1639
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
1640
                    for ninfo in node_info]
1641
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
1642
                    for ninfo in node_info]
1643

    
1644
    instance_data = fn(instance_names)
1645
    off_data = fn(node.name for node in node_info if node.offline)
1646
    on_data = fn(node.name for node in node_info if not node.offline)
1647
    mc_data = fn(node.name for node in node_info if node.master_candidate)
1648
    mc_ips_data = fn(node.primary_ip for node in node_info
1649
                     if node.master_candidate)
1650
    node_data = fn(node_names)
1651
    node_pri_ips_data = fn(node_pri_ips)
1652
    node_snd_ips_data = fn(node_snd_ips)
1653

    
1654
    cluster = self._config_data.cluster
1655
    cluster_tags = fn(cluster.GetTags())
1656

    
1657
    hypervisor_list = fn(cluster.enabled_hypervisors)
1658

    
1659
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
1660

    
1661
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
1662
                  self._config_data.nodegroups.values()]
1663
    nodegroups_data = fn(utils.NiceSort(nodegroups))
1664

    
1665
    return {
1666
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
1667
      constants.SS_CLUSTER_TAGS: cluster_tags,
1668
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1669
      constants.SS_MASTER_CANDIDATES: mc_data,
1670
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
1671
      constants.SS_MASTER_IP: cluster.master_ip,
1672
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
1673
      constants.SS_MASTER_NODE: cluster.master_node,
1674
      constants.SS_NODE_LIST: node_data,
1675
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
1676
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
1677
      constants.SS_OFFLINE_NODES: off_data,
1678
      constants.SS_ONLINE_NODES: on_data,
1679
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
1680
      constants.SS_INSTANCE_LIST: instance_data,
1681
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1682
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
1683
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
1684
      constants.SS_UID_POOL: uid_pool,
1685
      constants.SS_NODEGROUPS: nodegroups_data,
1686
      }
1687

    
1688
  @locking.ssynchronized(_config_lock, shared=1)
1689
  def GetSsconfValues(self):
1690
    """Wrapper using lock around _UnlockedGetSsconf().
1691

1692
    """
1693
    return self._UnlockedGetSsconfValues()
1694

    
1695
  @locking.ssynchronized(_config_lock, shared=1)
1696
  def GetVGName(self):
1697
    """Return the volume group name.
1698

1699
    """
1700
    return self._config_data.cluster.volume_group_name
1701

    
1702
  @locking.ssynchronized(_config_lock)
1703
  def SetVGName(self, vg_name):
1704
    """Set the volume group name.
1705

1706
    """
1707
    self._config_data.cluster.volume_group_name = vg_name
1708
    self._config_data.cluster.serial_no += 1
1709
    self._WriteConfig()
1710

    
1711
  @locking.ssynchronized(_config_lock, shared=1)
1712
  def GetDRBDHelper(self):
1713
    """Return DRBD usermode helper.
1714

1715
    """
1716
    return self._config_data.cluster.drbd_usermode_helper
1717

    
1718
  @locking.ssynchronized(_config_lock)
1719
  def SetDRBDHelper(self, drbd_helper):
1720
    """Set DRBD usermode helper.
1721

1722
    """
1723
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
1724
    self._config_data.cluster.serial_no += 1
1725
    self._WriteConfig()
1726

    
1727
  @locking.ssynchronized(_config_lock, shared=1)
1728
  def GetMACPrefix(self):
1729
    """Return the mac prefix.
1730

1731
    """
1732
    return self._config_data.cluster.mac_prefix
1733

    
1734
  @locking.ssynchronized(_config_lock, shared=1)
1735
  def GetClusterInfo(self):
1736
    """Returns information about the cluster
1737

1738
    @rtype: L{objects.Cluster}
1739
    @return: the cluster object
1740

1741
    """
1742
    return self._config_data.cluster
1743

    
1744
  @locking.ssynchronized(_config_lock, shared=1)
1745
  def HasAnyDiskOfType(self, dev_type):
1746
    """Check if in there is at disk of the given type in the configuration.
1747

1748
    """
1749
    return self._config_data.HasAnyDiskOfType(dev_type)
1750

    
1751
  @locking.ssynchronized(_config_lock)
1752
  def Update(self, target, feedback_fn):
1753
    """Notify function to be called after updates.
1754

1755
    This function must be called when an object (as returned by
1756
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
1757
    caller wants the modifications saved to the backing store. Note
1758
    that all modified objects will be saved, but the target argument
1759
    is the one the caller wants to ensure that it's saved.
1760

1761
    @param target: an instance of either L{objects.Cluster},
1762
        L{objects.Node} or L{objects.Instance} which is existing in
1763
        the cluster
1764
    @param feedback_fn: Callable feedback function
1765

1766
    """
1767
    if self._config_data is None:
1768
      raise errors.ProgrammerError("Configuration file not read,"
1769
                                   " cannot save.")
1770
    update_serial = False
1771
    if isinstance(target, objects.Cluster):
1772
      test = target == self._config_data.cluster
1773
    elif isinstance(target, objects.Node):
1774
      test = target in self._config_data.nodes.values()
1775
      update_serial = True
1776
    elif isinstance(target, objects.Instance):
1777
      test = target in self._config_data.instances.values()
1778
    elif isinstance(target, objects.NodeGroup):
1779
      test = target in self._config_data.nodegroups.values()
1780
    else:
1781
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
1782
                                   " ConfigWriter.Update" % type(target))
1783
    if not test:
1784
      raise errors.ConfigurationError("Configuration updated since object"
1785
                                      " has been read or unknown object")
1786
    target.serial_no += 1
1787
    target.mtime = now = time.time()
1788

    
1789
    if update_serial:
1790
      # for node updates, we need to increase the cluster serial too
1791
      self._config_data.cluster.serial_no += 1
1792
      self._config_data.cluster.mtime = now
1793

    
1794
    if isinstance(target, objects.Instance):
1795
      self._UnlockedReleaseDRBDMinors(target.name)
1796

    
1797
    self._WriteConfig(feedback_fn=feedback_fn)
1798

    
1799
  @locking.ssynchronized(_config_lock)
1800
  def DropECReservations(self, ec_id):
1801
    """Drop per-execution-context reservations
1802

1803
    """
1804
    for rm in self._all_rms:
1805
      rm.DropECReservations(ec_id)