Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ eb180fe2

History | View | Annotate | Download (54.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010 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.items():
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
                                    (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 GenerateMAC(self, ec_id):
183
    """Generate a MAC for an instance.
184

185
    This should check the current instances for duplicates.
186

187
    """
188
    existing = self._AllMACs()
189
    return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
190

    
191
  @locking.ssynchronized(_config_lock, shared=1)
192
  def ReserveMAC(self, mac, ec_id):
193
    """Reserve a MAC for an instance.
194

195
    This only checks instances managed by this cluster, it does not
196
    check for potential collisions elsewhere.
197

198
    """
199
    all_macs = self._AllMACs()
200
    if mac in all_macs:
201
      raise errors.ReservationError("mac already in use")
202
    else:
203
      self._temporary_macs.Reserve(mac, ec_id)
204

    
205
  @locking.ssynchronized(_config_lock, shared=1)
206
  def ReserveLV(self, lv_name, ec_id):
207
    """Reserve an VG/LV pair for an instance.
208

209
    @type lv_name: string
210
    @param lv_name: the logical volume name to reserve
211

212
    """
213
    all_lvs = self._AllLVs()
214
    if lv_name in all_lvs:
215
      raise errors.ReservationError("LV already in use")
216
    else:
217
      self._temporary_lvs.Reserve(lv_name, ec_id)
218

    
219
  @locking.ssynchronized(_config_lock, shared=1)
220
  def GenerateDRBDSecret(self, ec_id):
221
    """Generate a DRBD secret.
222

223
    This checks the current disks for duplicates.
224

225
    """
226
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
227
                                            utils.GenerateSecret,
228
                                            ec_id)
229

    
230
  def _AllLVs(self):
231
    """Compute the list of all LVs.
232

233
    """
234
    lvnames = set()
235
    for instance in self._config_data.instances.values():
236
      node_data = instance.MapLVsByNode()
237
      for lv_list in node_data.values():
238
        lvnames.update(lv_list)
239
    return lvnames
240

    
241
  def _AllIDs(self, include_temporary):
242
    """Compute the list of all UUIDs and names we have.
243

244
    @type include_temporary: boolean
245
    @param include_temporary: whether to include the _temporary_ids set
246
    @rtype: set
247
    @return: a set of IDs
248

249
    """
250
    existing = set()
251
    if include_temporary:
252
      existing.update(self._temporary_ids.GetReserved())
253
    existing.update(self._AllLVs())
254
    existing.update(self._config_data.instances.keys())
255
    existing.update(self._config_data.nodes.keys())
256
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
257
    return existing
258

    
259
  def _GenerateUniqueID(self, ec_id):
260
    """Generate an unique UUID.
261

262
    This checks the current node, instances and disk names for
263
    duplicates.
264

265
    @rtype: string
266
    @return: the unique id
267

268
    """
269
    existing = self._AllIDs(include_temporary=False)
270
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
271

    
272
  @locking.ssynchronized(_config_lock, shared=1)
273
  def GenerateUniqueID(self, ec_id):
274
    """Generate an unique ID.
275

276
    This is just a wrapper over the unlocked version.
277

278
    @type ec_id: string
279
    @param ec_id: unique id for the job to reserve the id to
280

281
    """
282
    return self._GenerateUniqueID(ec_id)
283

    
284
  def _AllMACs(self):
285
    """Return all MACs present in the config.
286

287
    @rtype: list
288
    @return: the list of all MACs
289

290
    """
291
    result = []
292
    for instance in self._config_data.instances.values():
293
      for nic in instance.nics:
294
        result.append(nic.mac)
295

    
296
    return result
297

    
298
  def _AllDRBDSecrets(self):
299
    """Return all DRBD secrets present in the config.
300

301
    @rtype: list
302
    @return: the list of all DRBD secrets
303

304
    """
305
    def helper(disk, result):
306
      """Recursively gather secrets from this disk."""
307
      if disk.dev_type == constants.DT_DRBD8:
308
        result.append(disk.logical_id[5])
309
      if disk.children:
310
        for child in disk.children:
311
          helper(child, result)
312

    
313
    result = []
314
    for instance in self._config_data.instances.values():
315
      for disk in instance.disks:
316
        helper(disk, result)
317

    
318
    return result
319

    
320
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
321
    """Compute duplicate disk IDs
322

323
    @type disk: L{objects.Disk}
324
    @param disk: the disk at which to start searching
325
    @type l_ids: list
326
    @param l_ids: list of current logical ids
327
    @type p_ids: list
328
    @param p_ids: list of current physical ids
329
    @rtype: list
330
    @return: a list of error messages
331

332
    """
333
    result = []
334
    if disk.logical_id is not None:
335
      if disk.logical_id in l_ids:
336
        result.append("duplicate logical id %s" % str(disk.logical_id))
337
      else:
338
        l_ids.append(disk.logical_id)
339
    if disk.physical_id is not None:
340
      if disk.physical_id in p_ids:
341
        result.append("duplicate physical id %s" % str(disk.physical_id))
342
      else:
343
        p_ids.append(disk.physical_id)
344

    
345
    if disk.children:
346
      for child in disk.children:
347
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
348
    return result
349

    
350
  def _UnlockedVerifyConfig(self):
351
    """Verify function.
352

353
    @rtype: list
354
    @return: a list of error messages; a non-empty list signifies
355
        configuration errors
356

357
    """
358
    result = []
359
    seen_macs = []
360
    ports = {}
361
    data = self._config_data
362
    seen_lids = []
363
    seen_pids = []
364

    
365
    # global cluster checks
366
    if not data.cluster.enabled_hypervisors:
367
      result.append("enabled hypervisors list doesn't have any entries")
368
    invalid_hvs = set(data.cluster.enabled_hypervisors) - constants.HYPER_TYPES
369
    if invalid_hvs:
370
      result.append("enabled hypervisors contains invalid entries: %s" %
371
                    invalid_hvs)
372
    missing_hvp = (set(data.cluster.enabled_hypervisors) -
373
                   set(data.cluster.hvparams.keys()))
374
    if missing_hvp:
375
      result.append("hypervisor parameters missing for the enabled"
376
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
377

    
378
    if data.cluster.master_node not in data.nodes:
379
      result.append("cluster has invalid primary node '%s'" %
380
                    data.cluster.master_node)
381

    
382
    # per-instance checks
383
    for instance_name in data.instances:
384
      instance = data.instances[instance_name]
385
      if instance.name != instance_name:
386
        result.append("instance '%s' is indexed by wrong name '%s'" %
387
                      (instance.name, instance_name))
388
      if instance.primary_node not in data.nodes:
389
        result.append("instance '%s' has invalid primary node '%s'" %
390
                      (instance_name, instance.primary_node))
391
      for snode in instance.secondary_nodes:
392
        if snode not in data.nodes:
393
          result.append("instance '%s' has invalid secondary node '%s'" %
394
                        (instance_name, snode))
395
      for idx, nic in enumerate(instance.nics):
396
        if nic.mac in seen_macs:
397
          result.append("instance '%s' has NIC %d mac %s duplicate" %
398
                        (instance_name, idx, nic.mac))
399
        else:
400
          seen_macs.append(nic.mac)
401

    
402
      # gather the drbd ports for duplicate checks
403
      for dsk in instance.disks:
404
        if dsk.dev_type in constants.LDS_DRBD:
405
          tcp_port = dsk.logical_id[2]
406
          if tcp_port not in ports:
407
            ports[tcp_port] = []
408
          ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
409
      # gather network port reservation
410
      net_port = getattr(instance, "network_port", None)
411
      if net_port is not None:
412
        if net_port not in ports:
413
          ports[net_port] = []
414
        ports[net_port].append((instance.name, "network port"))
415

    
416
      # instance disk verify
417
      for idx, disk in enumerate(instance.disks):
418
        result.extend(["instance '%s' disk %d error: %s" %
419
                       (instance.name, idx, msg) for msg in disk.Verify()])
420
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
421

    
422
    # cluster-wide pool of free ports
423
    for free_port in data.cluster.tcpudp_port_pool:
424
      if free_port not in ports:
425
        ports[free_port] = []
426
      ports[free_port].append(("cluster", "port marked as free"))
427

    
428
    # compute tcp/udp duplicate ports
429
    keys = ports.keys()
430
    keys.sort()
431
    for pnum in keys:
432
      pdata = ports[pnum]
433
      if len(pdata) > 1:
434
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
435
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
436

    
437
    # highest used tcp port check
438
    if keys:
439
      if keys[-1] > data.cluster.highest_used_port:
440
        result.append("Highest used port mismatch, saved %s, computed %s" %
441
                      (data.cluster.highest_used_port, keys[-1]))
442

    
443
    if not data.nodes[data.cluster.master_node].master_candidate:
444
      result.append("Master node is not a master candidate")
445

    
446
    # master candidate checks
447
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
448
    if mc_now < mc_max:
449
      result.append("Not enough master candidates: actual %d, target %d" %
450
                    (mc_now, mc_max))
451

    
452
    # node checks
453
    for node_name, node in data.nodes.items():
454
      if node.name != node_name:
455
        result.append("Node '%s' is indexed by wrong name '%s'" %
456
                      (node.name, node_name))
457
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
458
        result.append("Node %s state is invalid: master_candidate=%s,"
459
                      " drain=%s, offline=%s" %
460
                      (node.name, node.master_candidate, node.drain,
461
                       node.offline))
462

    
463
    # nodegroups checks
464
    nodegroups_names = set()
465
    for nodegroup_uuid in data.nodegroups:
466
      nodegroup = data.nodegroups[nodegroup_uuid]
467
      if nodegroup.uuid != nodegroup_uuid:
468
        result.append("nodegroup '%s' (uuid: '%s') indexed by wrong uuid '%s'"
469
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
470
      if utils.UUID_RE.match(nodegroup.name.lower()):
471
        result.append("nodegroup '%s' (uuid: '%s') has uuid-like name" %
472
                      (nodegroup.name, nodegroup.uuid))
473
      if nodegroup.name in nodegroups_names:
474
        result.append("duplicate nodegroup name '%s'" % nodegroup.name)
475
      else:
476
        nodegroups_names.add(nodegroup.name)
477

    
478
    # drbd minors check
479
    _, duplicates = self._UnlockedComputeDRBDMap()
480
    for node, minor, instance_a, instance_b in duplicates:
481
      result.append("DRBD minor %d on node %s is assigned twice to instances"
482
                    " %s and %s" % (minor, node, instance_a, instance_b))
483

    
484
    # IP checks
485
    default_nicparams = data.cluster.nicparams[constants.PP_DEFAULT]
486
    ips = {}
487

    
488
    def _AddIpAddress(ip, name):
489
      ips.setdefault(ip, []).append(name)
490

    
491
    _AddIpAddress(data.cluster.master_ip, "cluster_ip")
492

    
493
    for node in data.nodes.values():
494
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
495
      if node.secondary_ip != node.primary_ip:
496
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
497

    
498
    for instance in data.instances.values():
499
      for idx, nic in enumerate(instance.nics):
500
        if nic.ip is None:
501
          continue
502

    
503
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
504
        nic_mode = nicparams[constants.NIC_MODE]
505
        nic_link = nicparams[constants.NIC_LINK]
506

    
507
        if nic_mode == constants.NIC_MODE_BRIDGED:
508
          link = "bridge:%s" % nic_link
509
        elif nic_mode == constants.NIC_MODE_ROUTED:
510
          link = "route:%s" % nic_link
511
        else:
512
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
513

    
514
        _AddIpAddress("%s/%s" % (link, nic.ip),
515
                      "instance:%s/nic:%d" % (instance.name, idx))
516

    
517
    for ip, owners in ips.items():
518
      if len(owners) > 1:
519
        result.append("IP address %s is used by multiple owners: %s" %
520
                      (ip, utils.CommaJoin(owners)))
521

    
522
    return result
523

    
524
  @locking.ssynchronized(_config_lock, shared=1)
525
  def VerifyConfig(self):
526
    """Verify function.
527

528
    This is just a wrapper over L{_UnlockedVerifyConfig}.
529

530
    @rtype: list
531
    @return: a list of error messages; a non-empty list signifies
532
        configuration errors
533

534
    """
535
    return self._UnlockedVerifyConfig()
536

    
537
  def _UnlockedSetDiskID(self, disk, node_name):
538
    """Convert the unique ID to the ID needed on the target nodes.
539

540
    This is used only for drbd, which needs ip/port configuration.
541

542
    The routine descends down and updates its children also, because
543
    this helps when the only the top device is passed to the remote
544
    node.
545

546
    This function is for internal use, when the config lock is already held.
547

548
    """
549
    if disk.children:
550
      for child in disk.children:
551
        self._UnlockedSetDiskID(child, node_name)
552

    
553
    if disk.logical_id is None and disk.physical_id is not None:
554
      return
555
    if disk.dev_type == constants.LD_DRBD8:
556
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
557
      if node_name not in (pnode, snode):
558
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
559
                                        node_name)
560
      pnode_info = self._UnlockedGetNodeInfo(pnode)
561
      snode_info = self._UnlockedGetNodeInfo(snode)
562
      if pnode_info is None or snode_info is None:
563
        raise errors.ConfigurationError("Can't find primary or secondary node"
564
                                        " for %s" % str(disk))
565
      p_data = (pnode_info.secondary_ip, port)
566
      s_data = (snode_info.secondary_ip, port)
567
      if pnode == node_name:
568
        disk.physical_id = p_data + s_data + (pminor, secret)
569
      else: # it must be secondary, we tested above
570
        disk.physical_id = s_data + p_data + (sminor, secret)
571
    else:
572
      disk.physical_id = disk.logical_id
573
    return
574

    
575
  @locking.ssynchronized(_config_lock)
576
  def SetDiskID(self, disk, node_name):
577
    """Convert the unique ID to the ID needed on the target nodes.
578

579
    This is used only for drbd, which needs ip/port configuration.
580

581
    The routine descends down and updates its children also, because
582
    this helps when the only the top device is passed to the remote
583
    node.
584

585
    """
586
    return self._UnlockedSetDiskID(disk, node_name)
587

    
588
  @locking.ssynchronized(_config_lock)
589
  def AddTcpUdpPort(self, port):
590
    """Adds a new port to the available port pool.
591

592
    """
593
    if not isinstance(port, int):
594
      raise errors.ProgrammerError("Invalid type passed for port")
595

    
596
    self._config_data.cluster.tcpudp_port_pool.add(port)
597
    self._WriteConfig()
598

    
599
  @locking.ssynchronized(_config_lock, shared=1)
600
  def GetPortList(self):
601
    """Returns a copy of the current port list.
602

603
    """
604
    return self._config_data.cluster.tcpudp_port_pool.copy()
605

    
606
  @locking.ssynchronized(_config_lock)
607
  def AllocatePort(self):
608
    """Allocate a port.
609

610
    The port will be taken from the available port pool or from the
611
    default port range (and in this case we increase
612
    highest_used_port).
613

614
    """
615
    # If there are TCP/IP ports configured, we use them first.
616
    if self._config_data.cluster.tcpudp_port_pool:
617
      port = self._config_data.cluster.tcpudp_port_pool.pop()
618
    else:
619
      port = self._config_data.cluster.highest_used_port + 1
620
      if port >= constants.LAST_DRBD_PORT:
621
        raise errors.ConfigurationError("The highest used port is greater"
622
                                        " than %s. Aborting." %
623
                                        constants.LAST_DRBD_PORT)
624
      self._config_data.cluster.highest_used_port = port
625

    
626
    self._WriteConfig()
627
    return port
628

    
629
  def _UnlockedComputeDRBDMap(self):
630
    """Compute the used DRBD minor/nodes.
631

632
    @rtype: (dict, list)
633
    @return: dictionary of node_name: dict of minor: instance_name;
634
        the returned dict will have all the nodes in it (even if with
635
        an empty list), and a list of duplicates; if the duplicates
636
        list is not empty, the configuration is corrupted and its caller
637
        should raise an exception
638

639
    """
640
    def _AppendUsedPorts(instance_name, disk, used):
641
      duplicates = []
642
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
643
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
644
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
645
          assert node in used, ("Node '%s' of instance '%s' not found"
646
                                " in node list" % (node, instance_name))
647
          if port in used[node]:
648
            duplicates.append((node, port, instance_name, used[node][port]))
649
          else:
650
            used[node][port] = instance_name
651
      if disk.children:
652
        for child in disk.children:
653
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
654
      return duplicates
655

    
656
    duplicates = []
657
    my_dict = dict((node, {}) for node in self._config_data.nodes)
658
    for instance in self._config_data.instances.itervalues():
659
      for disk in instance.disks:
660
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
661
    for (node, minor), instance in self._temporary_drbds.iteritems():
662
      if minor in my_dict[node] and my_dict[node][minor] != instance:
663
        duplicates.append((node, minor, instance, my_dict[node][minor]))
664
      else:
665
        my_dict[node][minor] = instance
666
    return my_dict, duplicates
667

    
668
  @locking.ssynchronized(_config_lock)
669
  def ComputeDRBDMap(self):
670
    """Compute the used DRBD minor/nodes.
671

672
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
673

674
    @return: dictionary of node_name: dict of minor: instance_name;
675
        the returned dict will have all the nodes in it (even if with
676
        an empty list).
677

678
    """
679
    d_map, duplicates = self._UnlockedComputeDRBDMap()
680
    if duplicates:
681
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
682
                                      str(duplicates))
683
    return d_map
684

    
685
  @locking.ssynchronized(_config_lock)
686
  def AllocateDRBDMinor(self, nodes, instance):
687
    """Allocate a drbd minor.
688

689
    The free minor will be automatically computed from the existing
690
    devices. A node can be given multiple times in order to allocate
691
    multiple minors. The result is the list of minors, in the same
692
    order as the passed nodes.
693

694
    @type instance: string
695
    @param instance: the instance for which we allocate minors
696

697
    """
698
    assert isinstance(instance, basestring), \
699
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
700

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

    
741
  def _UnlockedReleaseDRBDMinors(self, instance):
742
    """Release temporary drbd minors allocated for a given instance.
743

744
    @type instance: string
745
    @param instance: the instance for which temporary minors should be
746
                     released
747

748
    """
749
    assert isinstance(instance, basestring), \
750
           "Invalid argument passed to ReleaseDRBDMinors"
751
    for key, name in self._temporary_drbds.items():
752
      if name == instance:
753
        del self._temporary_drbds[key]
754

    
755
  @locking.ssynchronized(_config_lock)
756
  def ReleaseDRBDMinors(self, instance):
757
    """Release temporary drbd minors allocated for a given instance.
758

759
    This should be called on the error paths, on the success paths
760
    it's automatically called by the ConfigWriter add and update
761
    functions.
762

763
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
764

765
    @type instance: string
766
    @param instance: the instance for which temporary minors should be
767
                     released
768

769
    """
770
    self._UnlockedReleaseDRBDMinors(instance)
771

    
772
  @locking.ssynchronized(_config_lock, shared=1)
773
  def GetConfigVersion(self):
774
    """Get the configuration version.
775

776
    @return: Config version
777

778
    """
779
    return self._config_data.version
780

    
781
  @locking.ssynchronized(_config_lock, shared=1)
782
  def GetClusterName(self):
783
    """Get cluster name.
784

785
    @return: Cluster name
786

787
    """
788
    return self._config_data.cluster.cluster_name
789

    
790
  @locking.ssynchronized(_config_lock, shared=1)
791
  def GetMasterNode(self):
792
    """Get the hostname of the master node for this cluster.
793

794
    @return: Master hostname
795

796
    """
797
    return self._config_data.cluster.master_node
798

    
799
  @locking.ssynchronized(_config_lock, shared=1)
800
  def GetMasterIP(self):
801
    """Get the IP of the master node for this cluster.
802

803
    @return: Master IP
804

805
    """
806
    return self._config_data.cluster.master_ip
807

    
808
  @locking.ssynchronized(_config_lock, shared=1)
809
  def GetMasterNetdev(self):
810
    """Get the master network device for this cluster.
811

812
    """
813
    return self._config_data.cluster.master_netdev
814

    
815
  @locking.ssynchronized(_config_lock, shared=1)
816
  def GetFileStorageDir(self):
817
    """Get the file storage dir for this cluster.
818

819
    """
820
    return self._config_data.cluster.file_storage_dir
821

    
822
  @locking.ssynchronized(_config_lock, shared=1)
823
  def GetHypervisorType(self):
824
    """Get the hypervisor type for this cluster.
825

826
    """
827
    return self._config_data.cluster.enabled_hypervisors[0]
828

    
829
  @locking.ssynchronized(_config_lock, shared=1)
830
  def GetHostKey(self):
831
    """Return the rsa hostkey from the config.
832

833
    @rtype: string
834
    @return: the rsa hostkey
835

836
    """
837
    return self._config_data.cluster.rsahostkeypub
838

    
839
  @locking.ssynchronized(_config_lock, shared=1)
840
  def GetDefaultIAllocator(self):
841
    """Get the default instance allocator for this cluster.
842

843
    """
844
    return self._config_data.cluster.default_iallocator
845

    
846
  @locking.ssynchronized(_config_lock, shared=1)
847
  def GetPrimaryIPFamily(self):
848
    """Get cluster primary ip family.
849

850
    @return: primary ip family
851

852
    """
853
    return self._config_data.cluster.primary_ip_family
854

    
855
  @locking.ssynchronized(_config_lock, shared=1)
856
  def LookupNodeGroup(self, target):
857
    """Lookup a node group.
858

859
    @type target: string or None
860
    @param  target: group name or uuid or None to look for the default
861
    @rtype: string
862
    @return: nodegroup uuid
863
    @raises errors.OpPrereqError: when the target group cannot be found
864

865
    """
866
    if target is None:
867
      if len(self._config_data.nodegroups) != 1:
868
        raise errors.OpPrereqError("More than one nodegroup exists. Target"
869
                                   " group must be specified explicitely.")
870
      else:
871
        return self._config_data.nodegroups.keys()[0]
872
    if target in self._config_data.nodegroups:
873
      return target
874
    for nodegroup in self._config_data.nodegroups.values():
875
      if nodegroup.name == target:
876
        return nodegroup.uuid
877
    raise errors.OpPrereqError("Nodegroup '%s' not found", target)
878

    
879
  @locking.ssynchronized(_config_lock)
880
  def AddInstance(self, instance, ec_id):
881
    """Add an instance to the config.
882

883
    This should be used after creating a new instance.
884

885
    @type instance: L{objects.Instance}
886
    @param instance: the instance object
887

888
    """
889
    if not isinstance(instance, objects.Instance):
890
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
891

    
892
    if instance.disk_template != constants.DT_DISKLESS:
893
      all_lvs = instance.MapLVsByNode()
894
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
895

    
896
    all_macs = self._AllMACs()
897
    for nic in instance.nics:
898
      if nic.mac in all_macs:
899
        raise errors.ConfigurationError("Cannot add instance %s:"
900
                                        " MAC address '%s' already in use." %
901
                                        (instance.name, nic.mac))
902

    
903
    self._EnsureUUID(instance, ec_id)
904

    
905
    instance.serial_no = 1
906
    instance.ctime = instance.mtime = time.time()
907
    self._config_data.instances[instance.name] = instance
908
    self._config_data.cluster.serial_no += 1
909
    self._UnlockedReleaseDRBDMinors(instance.name)
910
    self._WriteConfig()
911

    
912
  def _EnsureUUID(self, item, ec_id):
913
    """Ensures a given object has a valid UUID.
914

915
    @param item: the instance or node to be checked
916
    @param ec_id: the execution context id for the uuid reservation
917

918
    """
919
    if not item.uuid:
920
      item.uuid = self._GenerateUniqueID(ec_id)
921
    elif item.uuid in self._AllIDs(include_temporary=True):
922
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
923
                                      " in use" % (item.name, item.uuid))
924

    
925
  def _SetInstanceStatus(self, instance_name, status):
926
    """Set the instance's status to a given value.
927

928
    """
929
    assert isinstance(status, bool), \
930
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
931

    
932
    if instance_name not in self._config_data.instances:
933
      raise errors.ConfigurationError("Unknown instance '%s'" %
934
                                      instance_name)
935
    instance = self._config_data.instances[instance_name]
936
    if instance.admin_up != status:
937
      instance.admin_up = status
938
      instance.serial_no += 1
939
      instance.mtime = time.time()
940
      self._WriteConfig()
941

    
942
  @locking.ssynchronized(_config_lock)
943
  def MarkInstanceUp(self, instance_name):
944
    """Mark the instance status to up in the config.
945

946
    """
947
    self._SetInstanceStatus(instance_name, True)
948

    
949
  @locking.ssynchronized(_config_lock)
950
  def RemoveInstance(self, instance_name):
951
    """Remove the instance from the configuration.
952

953
    """
954
    if instance_name not in self._config_data.instances:
955
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
956
    del self._config_data.instances[instance_name]
957
    self._config_data.cluster.serial_no += 1
958
    self._WriteConfig()
959

    
960
  @locking.ssynchronized(_config_lock)
961
  def RenameInstance(self, old_name, new_name):
962
    """Rename an instance.
963

964
    This needs to be done in ConfigWriter and not by RemoveInstance
965
    combined with AddInstance as only we can guarantee an atomic
966
    rename.
967

968
    """
969
    if old_name not in self._config_data.instances:
970
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
971
    inst = self._config_data.instances[old_name]
972
    del self._config_data.instances[old_name]
973
    inst.name = new_name
974

    
975
    for disk in inst.disks:
976
      if disk.dev_type == constants.LD_FILE:
977
        # rename the file paths in logical and physical id
978
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
979
        disk.physical_id = disk.logical_id = (disk.logical_id[0],
980
                                              utils.PathJoin(file_storage_dir,
981
                                                             inst.name,
982
                                                             disk.iv_name))
983

    
984
    self._config_data.instances[inst.name] = inst
985
    self._WriteConfig()
986

    
987
  @locking.ssynchronized(_config_lock)
988
  def MarkInstanceDown(self, instance_name):
989
    """Mark the status of an instance to down in the configuration.
990

991
    """
992
    self._SetInstanceStatus(instance_name, False)
993

    
994
  def _UnlockedGetInstanceList(self):
995
    """Get the list of instances.
996

997
    This function is for internal use, when the config lock is already held.
998

999
    """
1000
    return self._config_data.instances.keys()
1001

    
1002
  @locking.ssynchronized(_config_lock, shared=1)
1003
  def GetInstanceList(self):
1004
    """Get the list of instances.
1005

1006
    @return: array of instances, ex. ['instance2.example.com',
1007
        'instance1.example.com']
1008

1009
    """
1010
    return self._UnlockedGetInstanceList()
1011

    
1012
  @locking.ssynchronized(_config_lock, shared=1)
1013
  def ExpandInstanceName(self, short_name):
1014
    """Attempt to expand an incomplete instance name.
1015

1016
    """
1017
    return utils.MatchNameComponent(short_name,
1018
                                    self._config_data.instances.keys(),
1019
                                    case_sensitive=False)
1020

    
1021
  def _UnlockedGetInstanceInfo(self, instance_name):
1022
    """Returns information about an instance.
1023

1024
    This function is for internal use, when the config lock is already held.
1025

1026
    """
1027
    if instance_name not in self._config_data.instances:
1028
      return None
1029

    
1030
    return self._config_data.instances[instance_name]
1031

    
1032
  @locking.ssynchronized(_config_lock, shared=1)
1033
  def GetInstanceInfo(self, instance_name):
1034
    """Returns information about an instance.
1035

1036
    It takes the information from the configuration file. Other information of
1037
    an instance are taken from the live systems.
1038

1039
    @param instance_name: name of the instance, e.g.
1040
        I{instance1.example.com}
1041

1042
    @rtype: L{objects.Instance}
1043
    @return: the instance object
1044

1045
    """
1046
    return self._UnlockedGetInstanceInfo(instance_name)
1047

    
1048
  @locking.ssynchronized(_config_lock, shared=1)
1049
  def GetAllInstancesInfo(self):
1050
    """Get the configuration of all instances.
1051

1052
    @rtype: dict
1053
    @return: dict of (instance, instance_info), where instance_info is what
1054
              would GetInstanceInfo return for the node
1055

1056
    """
1057
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1058
                    for instance in self._UnlockedGetInstanceList()])
1059
    return my_dict
1060

    
1061
  @locking.ssynchronized(_config_lock)
1062
  def AddNode(self, node, ec_id):
1063
    """Add a node to the configuration.
1064

1065
    @type node: L{objects.Node}
1066
    @param node: a Node instance
1067

1068
    """
1069
    logging.info("Adding node %s to configuration", node.name)
1070

    
1071
    self._EnsureUUID(node, ec_id)
1072

    
1073
    node.serial_no = 1
1074
    node.ctime = node.mtime = time.time()
1075
    self._UnlockedAddNodeToGroup(node.name, node.nodegroup)
1076
    self._config_data.nodes[node.name] = node
1077
    self._config_data.cluster.serial_no += 1
1078
    self._WriteConfig()
1079

    
1080
  @locking.ssynchronized(_config_lock)
1081
  def RemoveNode(self, node_name):
1082
    """Remove a node from the configuration.
1083

1084
    """
1085
    logging.info("Removing node %s from configuration", node_name)
1086

    
1087
    if node_name not in self._config_data.nodes:
1088
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1089

    
1090
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1091
    del self._config_data.nodes[node_name]
1092
    self._config_data.cluster.serial_no += 1
1093
    self._WriteConfig()
1094

    
1095
  @locking.ssynchronized(_config_lock, shared=1)
1096
  def ExpandNodeName(self, short_name):
1097
    """Attempt to expand an incomplete instance name.
1098

1099
    """
1100
    return utils.MatchNameComponent(short_name,
1101
                                    self._config_data.nodes.keys(),
1102
                                    case_sensitive=False)
1103

    
1104
  def _UnlockedGetNodeInfo(self, node_name):
1105
    """Get the configuration of a node, as stored in the config.
1106

1107
    This function is for internal use, when the config lock is already
1108
    held.
1109

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

1112
    @rtype: L{objects.Node}
1113
    @return: the node object
1114

1115
    """
1116
    if node_name not in self._config_data.nodes:
1117
      return None
1118

    
1119
    return self._config_data.nodes[node_name]
1120

    
1121
  @locking.ssynchronized(_config_lock, shared=1)
1122
  def GetNodeInfo(self, node_name):
1123
    """Get the configuration of a node, as stored in the config.
1124

1125
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1126

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

1129
    @rtype: L{objects.Node}
1130
    @return: the node object
1131

1132
    """
1133
    return self._UnlockedGetNodeInfo(node_name)
1134

    
1135
  def _UnlockedGetNodeList(self):
1136
    """Return the list of nodes which are in the configuration.
1137

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

1141
    @rtype: list
1142

1143
    """
1144
    return self._config_data.nodes.keys()
1145

    
1146
  @locking.ssynchronized(_config_lock, shared=1)
1147
  def GetNodeList(self):
1148
    """Return the list of nodes which are in the configuration.
1149

1150
    """
1151
    return self._UnlockedGetNodeList()
1152

    
1153
  def _UnlockedGetOnlineNodeList(self):
1154
    """Return the list of nodes which are online.
1155

1156
    """
1157
    all_nodes = [self._UnlockedGetNodeInfo(node)
1158
                 for node in self._UnlockedGetNodeList()]
1159
    return [node.name for node in all_nodes if not node.offline]
1160

    
1161
  @locking.ssynchronized(_config_lock, shared=1)
1162
  def GetOnlineNodeList(self):
1163
    """Return the list of nodes which are online.
1164

1165
    """
1166
    return self._UnlockedGetOnlineNodeList()
1167

    
1168
  @locking.ssynchronized(_config_lock, shared=1)
1169
  def GetAllNodesInfo(self):
1170
    """Get the configuration of all nodes.
1171

1172
    @rtype: dict
1173
    @return: dict of (node, node_info), where node_info is what
1174
              would GetNodeInfo return for the node
1175

1176
    """
1177
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
1178
                    for node in self._UnlockedGetNodeList()])
1179
    return my_dict
1180

    
1181
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1182
    """Get the number of current and maximum desired and possible candidates.
1183

1184
    @type exceptions: list
1185
    @param exceptions: if passed, list of nodes that should be ignored
1186
    @rtype: tuple
1187
    @return: tuple of (current, desired and possible, possible)
1188

1189
    """
1190
    mc_now = mc_should = mc_max = 0
1191
    for node in self._config_data.nodes.values():
1192
      if exceptions and node.name in exceptions:
1193
        continue
1194
      if not (node.offline or node.drained):
1195
        mc_max += 1
1196
      if node.master_candidate:
1197
        mc_now += 1
1198
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1199
    return (mc_now, mc_should, mc_max)
1200

    
1201
  @locking.ssynchronized(_config_lock, shared=1)
1202
  def GetMasterCandidateStats(self, exceptions=None):
1203
    """Get the number of current and maximum possible candidates.
1204

1205
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1206

1207
    @type exceptions: list
1208
    @param exceptions: if passed, list of nodes that should be ignored
1209
    @rtype: tuple
1210
    @return: tuple of (current, max)
1211

1212
    """
1213
    return self._UnlockedGetMasterCandidateStats(exceptions)
1214

    
1215
  @locking.ssynchronized(_config_lock)
1216
  def MaintainCandidatePool(self, exceptions):
1217
    """Try to grow the candidate pool to the desired size.
1218

1219
    @type exceptions: list
1220
    @param exceptions: if passed, list of nodes that should be ignored
1221
    @rtype: list
1222
    @return: list with the adjusted nodes (L{objects.Node} instances)
1223

1224
    """
1225
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1226
    mod_list = []
1227
    if mc_now < mc_max:
1228
      node_list = self._config_data.nodes.keys()
1229
      random.shuffle(node_list)
1230
      for name in node_list:
1231
        if mc_now >= mc_max:
1232
          break
1233
        node = self._config_data.nodes[name]
1234
        if (node.master_candidate or node.offline or node.drained or
1235
            node.name in exceptions):
1236
          continue
1237
        mod_list.append(node)
1238
        node.master_candidate = True
1239
        node.serial_no += 1
1240
        mc_now += 1
1241
      if mc_now != mc_max:
1242
        # this should not happen
1243
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1244
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1245
      if mod_list:
1246
        self._config_data.cluster.serial_no += 1
1247
        self._WriteConfig()
1248

    
1249
    return mod_list
1250

    
1251
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1252
    """Add a given node to the specified group.
1253

1254
    """
1255
    if nodegroup_uuid not in self._config_data.nodegroups:
1256
      # This can happen if a node group gets deleted between its lookup and
1257
      # when we're adding the first node to it, since we don't keep a lock in
1258
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1259
      # is not found anymore.
1260
      raise errors.OpExecError("Unknown nodegroup: %s" % nodegroup_uuid)
1261
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1262
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1263

    
1264
  def _UnlockedRemoveNodeFromGroup(self, node):
1265
    """Remove a given node from its group.
1266

1267
    """
1268
    nodegroup = node.nodegroup
1269
    if nodegroup not in self._config_data.nodegroups:
1270
      logging.warning("Warning: node '%s' has a non-existing nodegroup '%s'"
1271
                      " (while being removed from it)", node.name, nodegroup)
1272
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1273
    if node.name not in nodegroup_obj.members:
1274
      logging.warning("Warning: node '%s' not a member of its nodegroup '%s'"
1275
                      " (while being removed from it)", node.name, nodegroup)
1276
    else:
1277
      nodegroup_obj.members.remove(node.name)
1278

    
1279
  def _BumpSerialNo(self):
1280
    """Bump up the serial number of the config.
1281

1282
    """
1283
    self._config_data.serial_no += 1
1284
    self._config_data.mtime = time.time()
1285

    
1286
  def _AllUUIDObjects(self):
1287
    """Returns all objects with uuid attributes.
1288

1289
    """
1290
    return (self._config_data.instances.values() +
1291
            self._config_data.nodes.values() +
1292
            self._config_data.nodegroups.values() +
1293
            [self._config_data.cluster])
1294

    
1295
  def _OpenConfig(self, accept_foreign):
1296
    """Read the config data from disk.
1297

1298
    """
1299
    raw_data = utils.ReadFile(self._cfg_file)
1300

    
1301
    try:
1302
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1303
    except Exception, err:
1304
      raise errors.ConfigurationError(err)
1305

    
1306
    # Make sure the configuration has the right version
1307
    _ValidateConfig(data)
1308

    
1309
    if (not hasattr(data, 'cluster') or
1310
        not hasattr(data.cluster, 'rsahostkeypub')):
1311
      raise errors.ConfigurationError("Incomplete configuration"
1312
                                      " (missing cluster.rsahostkeypub)")
1313

    
1314
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
1315
      msg = ("The configuration denotes node %s as master, while my"
1316
             " hostname is %s; opening a foreign configuration is only"
1317
             " possible in accept_foreign mode" %
1318
             (data.cluster.master_node, self._my_hostname))
1319
      raise errors.ConfigurationError(msg)
1320

    
1321
    # Upgrade configuration if needed
1322
    data.UpgradeConfig()
1323

    
1324
    self._config_data = data
1325
    # reset the last serial as -1 so that the next write will cause
1326
    # ssconf update
1327
    self._last_cluster_serial = -1
1328

    
1329
    # And finally run our (custom) config upgrade sequence
1330
    self._UpgradeConfig()
1331

    
1332
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
1333

    
1334
  def _UpgradeConfig(self):
1335
    """Run upgrade steps that cannot be done purely in the objects.
1336

1337
    This is because some data elements need uniqueness across the
1338
    whole configuration, etc.
1339

1340
    @warning: this function will call L{_WriteConfig()}, but also
1341
        L{DropECReservations} so it needs to be called only from a
1342
        "safe" place (the constructor). If one wanted to call it with
1343
        the lock held, a DropECReservationUnlocked would need to be
1344
        created first, to avoid causing deadlock.
1345

1346
    """
1347
    modified = False
1348
    for item in self._AllUUIDObjects():
1349
      if item.uuid is None:
1350
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1351
        modified = True
1352
    if not self._config_data.nodegroups:
1353
      default_nodegroup_uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1354
      default_nodegroup = objects.NodeGroup(
1355
          uuid=default_nodegroup_uuid,
1356
          name="default",
1357
          members=[],
1358
          )
1359
      self._config_data.nodegroups[default_nodegroup_uuid] = default_nodegroup
1360
      modified = True
1361
    for node in self._config_data.nodes.values():
1362
      if not node.nodegroup:
1363
        node.nodegroup = self.LookupNodeGroup(None)
1364
        modified = True
1365
      # This is technically *not* an upgrade, but needs to be done both when
1366
      # nodegroups are being added, and upon normally loading the config,
1367
      # because the members list of a node group is discarded upon
1368
      # serializing/deserializing the object.
1369
      self._UnlockedAddNodeToGroup(node.name, node.nodegroup)
1370
    if modified:
1371
      self._WriteConfig()
1372
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
1373
      # only called at config init time, without the lock held
1374
      self.DropECReservations(_UPGRADE_CONFIG_JID)
1375

    
1376
  def _DistributeConfig(self, feedback_fn):
1377
    """Distribute the configuration to the other nodes.
1378

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

1382
    """
1383
    if self._offline:
1384
      return True
1385

    
1386
    bad = False
1387

    
1388
    node_list = []
1389
    addr_list = []
1390
    myhostname = self._my_hostname
1391
    # we can skip checking whether _UnlockedGetNodeInfo returns None
1392
    # since the node list comes from _UnlocketGetNodeList, and we are
1393
    # called with the lock held, so no modifications should take place
1394
    # in between
1395
    for node_name in self._UnlockedGetNodeList():
1396
      if node_name == myhostname:
1397
        continue
1398
      node_info = self._UnlockedGetNodeInfo(node_name)
1399
      if not node_info.master_candidate:
1400
        continue
1401
      node_list.append(node_info.name)
1402
      addr_list.append(node_info.primary_ip)
1403

    
1404
    result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
1405
                                            address_list=addr_list)
1406
    for to_node, to_result in result.items():
1407
      msg = to_result.fail_msg
1408
      if msg:
1409
        msg = ("Copy of file %s to node %s failed: %s" %
1410
               (self._cfg_file, to_node, msg))
1411
        logging.error(msg)
1412

    
1413
        if feedback_fn:
1414
          feedback_fn(msg)
1415

    
1416
        bad = True
1417

    
1418
    return not bad
1419

    
1420
  def _WriteConfig(self, destination=None, feedback_fn=None):
1421
    """Write the configuration data to persistent storage.
1422

1423
    """
1424
    assert feedback_fn is None or callable(feedback_fn)
1425

    
1426
    # Warn on config errors, but don't abort the save - the
1427
    # configuration has already been modified, and we can't revert;
1428
    # the best we can do is to warn the user and save as is, leaving
1429
    # recovery to the user
1430
    config_errors = self._UnlockedVerifyConfig()
1431
    if config_errors:
1432
      errmsg = ("Configuration data is not consistent: %s" %
1433
                (utils.CommaJoin(config_errors)))
1434
      logging.critical(errmsg)
1435
      if feedback_fn:
1436
        feedback_fn(errmsg)
1437

    
1438
    if destination is None:
1439
      destination = self._cfg_file
1440
    self._BumpSerialNo()
1441
    txt = serializer.Dump(self._config_data.ToDict())
1442

    
1443
    getents = self._getents()
1444
    try:
1445
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
1446
                               close=False, gid=getents.confd_gid, mode=0640)
1447
    except errors.LockError:
1448
      raise errors.ConfigurationError("The configuration file has been"
1449
                                      " modified since the last write, cannot"
1450
                                      " update")
1451
    try:
1452
      self._cfg_id = utils.GetFileID(fd=fd)
1453
    finally:
1454
      os.close(fd)
1455

    
1456
    self.write_count += 1
1457

    
1458
    # and redistribute the config file to master candidates
1459
    self._DistributeConfig(feedback_fn)
1460

    
1461
    # Write ssconf files on all nodes (including locally)
1462
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
1463
      if not self._offline:
1464
        result = rpc.RpcRunner.call_write_ssconf_files(
1465
          self._UnlockedGetOnlineNodeList(),
1466
          self._UnlockedGetSsconfValues())
1467

    
1468
        for nname, nresu in result.items():
1469
          msg = nresu.fail_msg
1470
          if msg:
1471
            errmsg = ("Error while uploading ssconf files to"
1472
                      " node %s: %s" % (nname, msg))
1473
            logging.warning(errmsg)
1474

    
1475
            if feedback_fn:
1476
              feedback_fn(errmsg)
1477

    
1478
      self._last_cluster_serial = self._config_data.cluster.serial_no
1479

    
1480
  def _UnlockedGetSsconfValues(self):
1481
    """Return the values needed by ssconf.
1482

1483
    @rtype: dict
1484
    @return: a dictionary with keys the ssconf names and values their
1485
        associated value
1486

1487
    """
1488
    fn = "\n".join
1489
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1490
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
1491
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1492
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
1493
                    for ninfo in node_info]
1494
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
1495
                    for ninfo in node_info]
1496

    
1497
    instance_data = fn(instance_names)
1498
    off_data = fn(node.name for node in node_info if node.offline)
1499
    on_data = fn(node.name for node in node_info if not node.offline)
1500
    mc_data = fn(node.name for node in node_info if node.master_candidate)
1501
    mc_ips_data = fn(node.primary_ip for node in node_info
1502
                     if node.master_candidate)
1503
    node_data = fn(node_names)
1504
    node_pri_ips_data = fn(node_pri_ips)
1505
    node_snd_ips_data = fn(node_snd_ips)
1506

    
1507
    cluster = self._config_data.cluster
1508
    cluster_tags = fn(cluster.GetTags())
1509

    
1510
    hypervisor_list = fn(cluster.enabled_hypervisors)
1511

    
1512
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
1513

    
1514
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
1515
                  self._config_data.nodegroups.values()]
1516
    nodegroups_data = fn(utils.NiceSort(nodegroups))
1517

    
1518
    return {
1519
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
1520
      constants.SS_CLUSTER_TAGS: cluster_tags,
1521
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1522
      constants.SS_MASTER_CANDIDATES: mc_data,
1523
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
1524
      constants.SS_MASTER_IP: cluster.master_ip,
1525
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
1526
      constants.SS_MASTER_NODE: cluster.master_node,
1527
      constants.SS_NODE_LIST: node_data,
1528
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
1529
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
1530
      constants.SS_OFFLINE_NODES: off_data,
1531
      constants.SS_ONLINE_NODES: on_data,
1532
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
1533
      constants.SS_INSTANCE_LIST: instance_data,
1534
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1535
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
1536
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
1537
      constants.SS_UID_POOL: uid_pool,
1538
      constants.SS_NODEGROUPS: nodegroups_data,
1539
      }
1540

    
1541
  @locking.ssynchronized(_config_lock, shared=1)
1542
  def GetSsconfValues(self):
1543
    """Wrapper using lock around _UnlockedGetSsconf().
1544

1545
    """
1546
    return self._UnlockedGetSsconfValues()
1547

    
1548
  @locking.ssynchronized(_config_lock, shared=1)
1549
  def GetVGName(self):
1550
    """Return the volume group name.
1551

1552
    """
1553
    return self._config_data.cluster.volume_group_name
1554

    
1555
  @locking.ssynchronized(_config_lock)
1556
  def SetVGName(self, vg_name):
1557
    """Set the volume group name.
1558

1559
    """
1560
    self._config_data.cluster.volume_group_name = vg_name
1561
    self._config_data.cluster.serial_no += 1
1562
    self._WriteConfig()
1563

    
1564
  @locking.ssynchronized(_config_lock, shared=1)
1565
  def GetDRBDHelper(self):
1566
    """Return DRBD usermode helper.
1567

1568
    """
1569
    return self._config_data.cluster.drbd_usermode_helper
1570

    
1571
  @locking.ssynchronized(_config_lock)
1572
  def SetDRBDHelper(self, drbd_helper):
1573
    """Set DRBD usermode helper.
1574

1575
    """
1576
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
1577
    self._config_data.cluster.serial_no += 1
1578
    self._WriteConfig()
1579

    
1580
  @locking.ssynchronized(_config_lock, shared=1)
1581
  def GetMACPrefix(self):
1582
    """Return the mac prefix.
1583

1584
    """
1585
    return self._config_data.cluster.mac_prefix
1586

    
1587
  @locking.ssynchronized(_config_lock, shared=1)
1588
  def GetClusterInfo(self):
1589
    """Returns information about the cluster
1590

1591
    @rtype: L{objects.Cluster}
1592
    @return: the cluster object
1593

1594
    """
1595
    return self._config_data.cluster
1596

    
1597
  @locking.ssynchronized(_config_lock, shared=1)
1598
  def HasAnyDiskOfType(self, dev_type):
1599
    """Check if in there is at disk of the given type in the configuration.
1600

1601
    """
1602
    return self._config_data.HasAnyDiskOfType(dev_type)
1603

    
1604
  @locking.ssynchronized(_config_lock)
1605
  def Update(self, target, feedback_fn):
1606
    """Notify function to be called after updates.
1607

1608
    This function must be called when an object (as returned by
1609
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
1610
    caller wants the modifications saved to the backing store. Note
1611
    that all modified objects will be saved, but the target argument
1612
    is the one the caller wants to ensure that it's saved.
1613

1614
    @param target: an instance of either L{objects.Cluster},
1615
        L{objects.Node} or L{objects.Instance} which is existing in
1616
        the cluster
1617
    @param feedback_fn: Callable feedback function
1618

1619
    """
1620
    if self._config_data is None:
1621
      raise errors.ProgrammerError("Configuration file not read,"
1622
                                   " cannot save.")
1623
    update_serial = False
1624
    if isinstance(target, objects.Cluster):
1625
      test = target == self._config_data.cluster
1626
    elif isinstance(target, objects.Node):
1627
      test = target in self._config_data.nodes.values()
1628
      update_serial = True
1629
    elif isinstance(target, objects.Instance):
1630
      test = target in self._config_data.instances.values()
1631
    else:
1632
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
1633
                                   " ConfigWriter.Update" % type(target))
1634
    if not test:
1635
      raise errors.ConfigurationError("Configuration updated since object"
1636
                                      " has been read or unknown object")
1637
    target.serial_no += 1
1638
    target.mtime = now = time.time()
1639

    
1640
    if update_serial:
1641
      # for node updates, we need to increase the cluster serial too
1642
      self._config_data.cluster.serial_no += 1
1643
      self._config_data.cluster.mtime = now
1644

    
1645
    if isinstance(target, objects.Instance):
1646
      self._UnlockedReleaseDRBDMinors(target.name)
1647

    
1648
    self._WriteConfig(feedback_fn=feedback_fn)
1649

    
1650
  @locking.ssynchronized(_config_lock)
1651
  def DropECReservations(self, ec_id):
1652
    """Drop per-execution-context reservations
1653

1654
    """
1655
    for rm in self._all_rms:
1656
      rm.DropECReservations(ec_id)