Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 1a2eb2dc

History | View | Annotate | Download (74.6 kB)

1
#
2
#
3

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

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

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

    
55

    
56
_config_lock = locking.SharedLock("ConfigWriter")
57

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

    
61

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

65
  This only verifies the version of the configuration.
66

67
  @raise errors.ConfigurationError: if the version differs from what
68
      we expect
69

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

    
74

    
75
class TemporaryReservationManager:
76
  """A temporary resource reservation manager.
77

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

81
  """
82
  def __init__(self):
83
    self._ec_reserved = {}
84

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

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

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

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

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

113
    """
114
    assert callable(generate_one_fn)
115

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

    
129

    
130
def _MatchNameComponentIgnoreCase(short_name, names):
131
  """Wrapper around L{utils.text.MatchNameComponent}.
132

133
  """
134
  return utils.MatchNameComponent(short_name, names, case_sensitive=False)
135

    
136

    
137
def _CheckInstanceDiskIvNames(disks):
138
  """Checks if instance's disks' C{iv_name} attributes are in order.
139

140
  @type disks: list of L{objects.Disk}
141
  @param disks: List of disks
142
  @rtype: list of tuples; (int, string, string)
143
  @return: List of wrongly named disks, each tuple contains disk index,
144
    expected and actual name
145

146
  """
147
  result = []
148

    
149
  for (idx, disk) in enumerate(disks):
150
    exp_iv_name = "disk/%s" % idx
151
    if disk.iv_name != exp_iv_name:
152
      result.append((idx, exp_iv_name, disk.iv_name))
153

    
154
  return result
155

    
156

    
157
class ConfigWriter:
158
  """The interface to the cluster configuration.
159

160
  @ivar _temporary_lvs: reservation manager for temporary LVs
161
  @ivar _all_rms: a list of all temporary reservation managers
162

163
  """
164
  def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts,
165
               accept_foreign=False):
166
    self.write_count = 0
167
    self._lock = _config_lock
168
    self._config_data = None
169
    self._offline = offline
170
    if cfg_file is None:
171
      self._cfg_file = pathutils.CLUSTER_CONF_FILE
172
    else:
173
      self._cfg_file = cfg_file
174
    self._getents = _getents
175
    self._temporary_ids = TemporaryReservationManager()
176
    self._temporary_drbds = {}
177
    self._temporary_macs = TemporaryReservationManager()
178
    self._temporary_secrets = TemporaryReservationManager()
179
    self._temporary_lvs = TemporaryReservationManager()
180
    self._all_rms = [self._temporary_ids, self._temporary_macs,
181
                     self._temporary_secrets, self._temporary_lvs]
182
    # Note: in order to prevent errors when resolving our name in
183
    # _DistributeConfig, we compute it here once and reuse it; it's
184
    # better to raise an error before starting to modify the config
185
    # file than after it was modified
186
    self._my_hostname = netutils.Hostname.GetSysName()
187
    self._last_cluster_serial = -1
188
    self._cfg_id = None
189
    self._context = None
190
    self._OpenConfig(accept_foreign)
191

    
192
  def _GetRpc(self, address_list):
193
    """Returns RPC runner for configuration.
194

195
    """
196
    return rpc.ConfigRunner(self._context, address_list)
197

    
198
  def SetContext(self, context):
199
    """Sets Ganeti context.
200

201
    """
202
    self._context = context
203

    
204
  # this method needs to be static, so that we can call it on the class
205
  @staticmethod
206
  def IsCluster():
207
    """Check if the cluster is configured.
208

209
    """
210
    return os.path.exists(pathutils.CLUSTER_CONF_FILE)
211

    
212
  def _GenerateOneMAC(self):
213
    """Generate one mac address
214

215
    """
216
    prefix = self._config_data.cluster.mac_prefix
217
    byte1 = random.randrange(0, 256)
218
    byte2 = random.randrange(0, 256)
219
    byte3 = random.randrange(0, 256)
220
    mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
221
    return mac
222

    
223
  @locking.ssynchronized(_config_lock, shared=1)
224
  def GetNdParams(self, node):
225
    """Get the node params populated with cluster defaults.
226

227
    @type node: L{objects.Node}
228
    @param node: The node we want to know the params for
229
    @return: A dict with the filled in node params
230

231
    """
232
    nodegroup = self._UnlockedGetNodeGroup(node.group)
233
    return self._config_data.cluster.FillND(node, nodegroup)
234

    
235
  @locking.ssynchronized(_config_lock, shared=1)
236
  def GetInstanceDiskParams(self, instance):
237
    """Get the disk params populated with inherit chain.
238

239
    @type instance: L{objects.Instance}
240
    @param instance: The instance we want to know the params for
241
    @return: A dict with the filled in disk params
242

243
    """
244
    node = self._UnlockedGetNodeInfo(instance.primary_node)
245
    nodegroup = self._UnlockedGetNodeGroup(node.group)
246
    return self._UnlockedGetGroupDiskParams(nodegroup)
247

    
248
  @locking.ssynchronized(_config_lock, shared=1)
249
  def GetGroupDiskParams(self, group):
250
    """Get the disk params populated with inherit chain.
251

252
    @type group: L{objects.NodeGroup}
253
    @param group: The group we want to know the params for
254
    @return: A dict with the filled in disk params
255

256
    """
257
    return self._UnlockedGetGroupDiskParams(group)
258

    
259
  def _UnlockedGetGroupDiskParams(self, group):
260
    """Get the disk params populated with inherit chain down to node-group.
261

262
    @type group: L{objects.NodeGroup}
263
    @param group: The group we want to know the params for
264
    @return: A dict with the filled in disk params
265

266
    """
267
    return self._config_data.cluster.SimpleFillDP(group.diskparams)
268

    
269
  @locking.ssynchronized(_config_lock, shared=1)
270
  def GenerateMAC(self, ec_id):
271
    """Generate a MAC for an instance.
272

273
    This should check the current instances for duplicates.
274

275
    """
276
    existing = self._AllMACs()
277
    return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
278

    
279
  @locking.ssynchronized(_config_lock, shared=1)
280
  def ReserveMAC(self, mac, ec_id):
281
    """Reserve a MAC for an instance.
282

283
    This only checks instances managed by this cluster, it does not
284
    check for potential collisions elsewhere.
285

286
    """
287
    all_macs = self._AllMACs()
288
    if mac in all_macs:
289
      raise errors.ReservationError("mac already in use")
290
    else:
291
      self._temporary_macs.Reserve(ec_id, mac)
292

    
293
  @locking.ssynchronized(_config_lock, shared=1)
294
  def ReserveLV(self, lv_name, ec_id):
295
    """Reserve an VG/LV pair for an instance.
296

297
    @type lv_name: string
298
    @param lv_name: the logical volume name to reserve
299

300
    """
301
    all_lvs = self._AllLVs()
302
    if lv_name in all_lvs:
303
      raise errors.ReservationError("LV already in use")
304
    else:
305
      self._temporary_lvs.Reserve(ec_id, lv_name)
306

    
307
  @locking.ssynchronized(_config_lock, shared=1)
308
  def GenerateDRBDSecret(self, ec_id):
309
    """Generate a DRBD secret.
310

311
    This checks the current disks for duplicates.
312

313
    """
314
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
315
                                            utils.GenerateSecret,
316
                                            ec_id)
317

    
318
  def _AllLVs(self):
319
    """Compute the list of all LVs.
320

321
    """
322
    lvnames = set()
323
    for instance in self._config_data.instances.values():
324
      node_data = instance.MapLVsByNode()
325
      for lv_list in node_data.values():
326
        lvnames.update(lv_list)
327
    return lvnames
328

    
329
  def _AllIDs(self, include_temporary):
330
    """Compute the list of all UUIDs and names we have.
331

332
    @type include_temporary: boolean
333
    @param include_temporary: whether to include the _temporary_ids set
334
    @rtype: set
335
    @return: a set of IDs
336

337
    """
338
    existing = set()
339
    if include_temporary:
340
      existing.update(self._temporary_ids.GetReserved())
341
    existing.update(self._AllLVs())
342
    existing.update(self._config_data.instances.keys())
343
    existing.update(self._config_data.nodes.keys())
344
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
345
    return existing
346

    
347
  def _GenerateUniqueID(self, ec_id):
348
    """Generate an unique UUID.
349

350
    This checks the current node, instances and disk names for
351
    duplicates.
352

353
    @rtype: string
354
    @return: the unique id
355

356
    """
357
    existing = self._AllIDs(include_temporary=False)
358
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
359

    
360
  @locking.ssynchronized(_config_lock, shared=1)
361
  def GenerateUniqueID(self, ec_id):
362
    """Generate an unique ID.
363

364
    This is just a wrapper over the unlocked version.
365

366
    @type ec_id: string
367
    @param ec_id: unique id for the job to reserve the id to
368

369
    """
370
    return self._GenerateUniqueID(ec_id)
371

    
372
  def _AllMACs(self):
373
    """Return all MACs present in the config.
374

375
    @rtype: list
376
    @return: the list of all MACs
377

378
    """
379
    result = []
380
    for instance in self._config_data.instances.values():
381
      for nic in instance.nics:
382
        result.append(nic.mac)
383

    
384
    return result
385

    
386
  def _AllDRBDSecrets(self):
387
    """Return all DRBD secrets present in the config.
388

389
    @rtype: list
390
    @return: the list of all DRBD secrets
391

392
    """
393
    def helper(disk, result):
394
      """Recursively gather secrets from this disk."""
395
      if disk.dev_type == constants.DT_DRBD8:
396
        result.append(disk.logical_id[5])
397
      if disk.children:
398
        for child in disk.children:
399
          helper(child, result)
400

    
401
    result = []
402
    for instance in self._config_data.instances.values():
403
      for disk in instance.disks:
404
        helper(disk, result)
405

    
406
    return result
407

    
408
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
409
    """Compute duplicate disk IDs
410

411
    @type disk: L{objects.Disk}
412
    @param disk: the disk at which to start searching
413
    @type l_ids: list
414
    @param l_ids: list of current logical ids
415
    @type p_ids: list
416
    @param p_ids: list of current physical ids
417
    @rtype: list
418
    @return: a list of error messages
419

420
    """
421
    result = []
422
    if disk.logical_id is not None:
423
      if disk.logical_id in l_ids:
424
        result.append("duplicate logical id %s" % str(disk.logical_id))
425
      else:
426
        l_ids.append(disk.logical_id)
427
    if disk.physical_id is not None:
428
      if disk.physical_id in p_ids:
429
        result.append("duplicate physical id %s" % str(disk.physical_id))
430
      else:
431
        p_ids.append(disk.physical_id)
432

    
433
    if disk.children:
434
      for child in disk.children:
435
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
436
    return result
437

    
438
  def _UnlockedVerifyConfig(self):
439
    """Verify function.
440

441
    @rtype: list
442
    @return: a list of error messages; a non-empty list signifies
443
        configuration errors
444

445
    """
446
    # pylint: disable=R0914
447
    result = []
448
    seen_macs = []
449
    ports = {}
450
    data = self._config_data
451
    cluster = data.cluster
452
    seen_lids = []
453
    seen_pids = []
454

    
455
    # global cluster checks
456
    if not cluster.enabled_hypervisors:
457
      result.append("enabled hypervisors list doesn't have any entries")
458
    invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
459
    if invalid_hvs:
460
      result.append("enabled hypervisors contains invalid entries: %s" %
461
                    invalid_hvs)
462
    missing_hvp = (set(cluster.enabled_hypervisors) -
463
                   set(cluster.hvparams.keys()))
464
    if missing_hvp:
465
      result.append("hypervisor parameters missing for the enabled"
466
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
467

    
468
    if cluster.master_node not in data.nodes:
469
      result.append("cluster has invalid primary node '%s'" %
470
                    cluster.master_node)
471

    
472
    def _helper(owner, attr, value, template):
473
      try:
474
        utils.ForceDictType(value, template)
475
      except errors.GenericError, err:
476
        result.append("%s has invalid %s: %s" % (owner, attr, err))
477

    
478
    def _helper_nic(owner, params):
479
      try:
480
        objects.NIC.CheckParameterSyntax(params)
481
      except errors.ConfigurationError, err:
482
        result.append("%s has invalid nicparams: %s" % (owner, err))
483

    
484
    def _helper_ipolicy(owner, params, check_std):
485
      try:
486
        objects.InstancePolicy.CheckParameterSyntax(params, check_std)
487
      except errors.ConfigurationError, err:
488
        result.append("%s has invalid instance policy: %s" % (owner, err))
489

    
490
    def _helper_ispecs(owner, params):
491
      for key, value in params.items():
492
        if key in constants.IPOLICY_ISPECS:
493
          fullkey = "ipolicy/" + key
494
          _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
495
        else:
496
          # FIXME: assuming list type
497
          if key in constants.IPOLICY_PARAMETERS:
498
            exp_type = float
499
          else:
500
            exp_type = list
501
          if not isinstance(value, exp_type):
502
            result.append("%s has invalid instance policy: for %s,"
503
                          " expecting %s, got %s" %
504
                          (owner, key, exp_type.__name__, type(value)))
505

    
506
    # check cluster parameters
507
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
508
            constants.BES_PARAMETER_TYPES)
509
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
510
            constants.NICS_PARAMETER_TYPES)
511
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
512
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
513
            constants.NDS_PARAMETER_TYPES)
514
    _helper_ipolicy("cluster", cluster.SimpleFillIPolicy({}), True)
515
    _helper_ispecs("cluster", cluster.SimpleFillIPolicy({}))
516

    
517
    # per-instance checks
518
    for instance_name in data.instances:
519
      instance = data.instances[instance_name]
520
      if instance.name != instance_name:
521
        result.append("instance '%s' is indexed by wrong name '%s'" %
522
                      (instance.name, instance_name))
523
      if instance.primary_node not in data.nodes:
524
        result.append("instance '%s' has invalid primary node '%s'" %
525
                      (instance_name, instance.primary_node))
526
      for snode in instance.secondary_nodes:
527
        if snode not in data.nodes:
528
          result.append("instance '%s' has invalid secondary node '%s'" %
529
                        (instance_name, snode))
530
      for idx, nic in enumerate(instance.nics):
531
        if nic.mac in seen_macs:
532
          result.append("instance '%s' has NIC %d mac %s duplicate" %
533
                        (instance_name, idx, nic.mac))
534
        else:
535
          seen_macs.append(nic.mac)
536
        if nic.nicparams:
537
          filled = cluster.SimpleFillNIC(nic.nicparams)
538
          owner = "instance %s nic %d" % (instance.name, idx)
539
          _helper(owner, "nicparams",
540
                  filled, constants.NICS_PARAMETER_TYPES)
541
          _helper_nic(owner, filled)
542

    
543
      # parameter checks
544
      if instance.beparams:
545
        _helper("instance %s" % instance.name, "beparams",
546
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
547

    
548
      # gather the drbd ports for duplicate checks
549
      for (idx, dsk) in enumerate(instance.disks):
550
        if dsk.dev_type in constants.LDS_DRBD:
551
          tcp_port = dsk.logical_id[2]
552
          if tcp_port not in ports:
553
            ports[tcp_port] = []
554
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
555
      # gather network port reservation
556
      net_port = getattr(instance, "network_port", None)
557
      if net_port is not None:
558
        if net_port not in ports:
559
          ports[net_port] = []
560
        ports[net_port].append((instance.name, "network port"))
561

    
562
      # instance disk verify
563
      for idx, disk in enumerate(instance.disks):
564
        result.extend(["instance '%s' disk %d error: %s" %
565
                       (instance.name, idx, msg) for msg in disk.Verify()])
566
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
567

    
568
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
569
      if wrong_names:
570
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
571
                         (idx, exp_name, actual_name))
572
                        for (idx, exp_name, actual_name) in wrong_names)
573

    
574
        result.append("Instance '%s' has wrongly named disks: %s" %
575
                      (instance.name, tmp))
576

    
577
    # cluster-wide pool of free ports
578
    for free_port in cluster.tcpudp_port_pool:
579
      if free_port not in ports:
580
        ports[free_port] = []
581
      ports[free_port].append(("cluster", "port marked as free"))
582

    
583
    # compute tcp/udp duplicate ports
584
    keys = ports.keys()
585
    keys.sort()
586
    for pnum in keys:
587
      pdata = ports[pnum]
588
      if len(pdata) > 1:
589
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
590
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
591

    
592
    # highest used tcp port check
593
    if keys:
594
      if keys[-1] > cluster.highest_used_port:
595
        result.append("Highest used port mismatch, saved %s, computed %s" %
596
                      (cluster.highest_used_port, keys[-1]))
597

    
598
    if not data.nodes[cluster.master_node].master_candidate:
599
      result.append("Master node is not a master candidate")
600

    
601
    # master candidate checks
602
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
603
    if mc_now < mc_max:
604
      result.append("Not enough master candidates: actual %d, target %d" %
605
                    (mc_now, mc_max))
606

    
607
    # node checks
608
    for node_name, node in data.nodes.items():
609
      if node.name != node_name:
610
        result.append("Node '%s' is indexed by wrong name '%s'" %
611
                      (node.name, node_name))
612
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
613
        result.append("Node %s state is invalid: master_candidate=%s,"
614
                      " drain=%s, offline=%s" %
615
                      (node.name, node.master_candidate, node.drained,
616
                       node.offline))
617
      if node.group not in data.nodegroups:
618
        result.append("Node '%s' has invalid group '%s'" %
619
                      (node.name, node.group))
620
      else:
621
        _helper("node %s" % node.name, "ndparams",
622
                cluster.FillND(node, data.nodegroups[node.group]),
623
                constants.NDS_PARAMETER_TYPES)
624

    
625
    # nodegroups checks
626
    nodegroups_names = set()
627
    for nodegroup_uuid in data.nodegroups:
628
      nodegroup = data.nodegroups[nodegroup_uuid]
629
      if nodegroup.uuid != nodegroup_uuid:
630
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
631
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
632
      if utils.UUID_RE.match(nodegroup.name.lower()):
633
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
634
                      (nodegroup.name, nodegroup.uuid))
635
      if nodegroup.name in nodegroups_names:
636
        result.append("duplicate node group name '%s'" % nodegroup.name)
637
      else:
638
        nodegroups_names.add(nodegroup.name)
639
      group_name = "group %s" % nodegroup.name
640
      _helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy),
641
                      False)
642
      _helper_ispecs(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy))
643
      if nodegroup.ndparams:
644
        _helper(group_name, "ndparams",
645
                cluster.SimpleFillND(nodegroup.ndparams),
646
                constants.NDS_PARAMETER_TYPES)
647

    
648
    # drbd minors check
649
    _, duplicates = self._UnlockedComputeDRBDMap()
650
    for node, minor, instance_a, instance_b in duplicates:
651
      result.append("DRBD minor %d on node %s is assigned twice to instances"
652
                    " %s and %s" % (minor, node, instance_a, instance_b))
653

    
654
    # IP checks
655
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
656
    ips = {}
657

    
658
    def _AddIpAddress(ip, name):
659
      ips.setdefault(ip, []).append(name)
660

    
661
    _AddIpAddress(cluster.master_ip, "cluster_ip")
662

    
663
    for node in data.nodes.values():
664
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
665
      if node.secondary_ip != node.primary_ip:
666
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
667

    
668
    for instance in data.instances.values():
669
      for idx, nic in enumerate(instance.nics):
670
        if nic.ip is None:
671
          continue
672

    
673
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
674
        nic_mode = nicparams[constants.NIC_MODE]
675
        nic_link = nicparams[constants.NIC_LINK]
676

    
677
        if nic_mode == constants.NIC_MODE_BRIDGED:
678
          link = "bridge:%s" % nic_link
679
        elif nic_mode == constants.NIC_MODE_ROUTED:
680
          link = "route:%s" % nic_link
681
        else:
682
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
683

    
684
        _AddIpAddress("%s/%s" % (link, nic.ip),
685
                      "instance:%s/nic:%d" % (instance.name, idx))
686

    
687
    for ip, owners in ips.items():
688
      if len(owners) > 1:
689
        result.append("IP address %s is used by multiple owners: %s" %
690
                      (ip, utils.CommaJoin(owners)))
691

    
692
    return result
693

    
694
  @locking.ssynchronized(_config_lock, shared=1)
695
  def VerifyConfig(self):
696
    """Verify function.
697

698
    This is just a wrapper over L{_UnlockedVerifyConfig}.
699

700
    @rtype: list
701
    @return: a list of error messages; a non-empty list signifies
702
        configuration errors
703

704
    """
705
    return self._UnlockedVerifyConfig()
706

    
707
  def _UnlockedSetDiskID(self, disk, node_name):
708
    """Convert the unique ID to the ID needed on the target nodes.
709

710
    This is used only for drbd, which needs ip/port configuration.
711

712
    The routine descends down and updates its children also, because
713
    this helps when the only the top device is passed to the remote
714
    node.
715

716
    This function is for internal use, when the config lock is already held.
717

718
    """
719
    if disk.children:
720
      for child in disk.children:
721
        self._UnlockedSetDiskID(child, node_name)
722

    
723
    if disk.logical_id is None and disk.physical_id is not None:
724
      return
725
    if disk.dev_type == constants.LD_DRBD8:
726
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
727
      if node_name not in (pnode, snode):
728
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
729
                                        node_name)
730
      pnode_info = self._UnlockedGetNodeInfo(pnode)
731
      snode_info = self._UnlockedGetNodeInfo(snode)
732
      if pnode_info is None or snode_info is None:
733
        raise errors.ConfigurationError("Can't find primary or secondary node"
734
                                        " for %s" % str(disk))
735
      p_data = (pnode_info.secondary_ip, port)
736
      s_data = (snode_info.secondary_ip, port)
737
      if pnode == node_name:
738
        disk.physical_id = p_data + s_data + (pminor, secret)
739
      else: # it must be secondary, we tested above
740
        disk.physical_id = s_data + p_data + (sminor, secret)
741
    else:
742
      disk.physical_id = disk.logical_id
743
    return
744

    
745
  @locking.ssynchronized(_config_lock)
746
  def SetDiskID(self, disk, node_name):
747
    """Convert the unique ID to the ID needed on the target nodes.
748

749
    This is used only for drbd, which needs ip/port configuration.
750

751
    The routine descends down and updates its children also, because
752
    this helps when the only the top device is passed to the remote
753
    node.
754

755
    """
756
    return self._UnlockedSetDiskID(disk, node_name)
757

    
758
  @locking.ssynchronized(_config_lock)
759
  def AddTcpUdpPort(self, port):
760
    """Adds a new port to the available port pool.
761

762
    @warning: this method does not "flush" the configuration (via
763
        L{_WriteConfig}); callers should do that themselves once the
764
        configuration is stable
765

766
    """
767
    if not isinstance(port, int):
768
      raise errors.ProgrammerError("Invalid type passed for port")
769

    
770
    self._config_data.cluster.tcpudp_port_pool.add(port)
771

    
772
  @locking.ssynchronized(_config_lock, shared=1)
773
  def GetPortList(self):
774
    """Returns a copy of the current port list.
775

776
    """
777
    return self._config_data.cluster.tcpudp_port_pool.copy()
778

    
779
  @locking.ssynchronized(_config_lock)
780
  def AllocatePort(self):
781
    """Allocate a port.
782

783
    The port will be taken from the available port pool or from the
784
    default port range (and in this case we increase
785
    highest_used_port).
786

787
    """
788
    # If there are TCP/IP ports configured, we use them first.
789
    if self._config_data.cluster.tcpudp_port_pool:
790
      port = self._config_data.cluster.tcpudp_port_pool.pop()
791
    else:
792
      port = self._config_data.cluster.highest_used_port + 1
793
      if port >= constants.LAST_DRBD_PORT:
794
        raise errors.ConfigurationError("The highest used port is greater"
795
                                        " than %s. Aborting." %
796
                                        constants.LAST_DRBD_PORT)
797
      self._config_data.cluster.highest_used_port = port
798

    
799
    self._WriteConfig()
800
    return port
801

    
802
  def _UnlockedComputeDRBDMap(self):
803
    """Compute the used DRBD minor/nodes.
804

805
    @rtype: (dict, list)
806
    @return: dictionary of node_name: dict of minor: instance_name;
807
        the returned dict will have all the nodes in it (even if with
808
        an empty list), and a list of duplicates; if the duplicates
809
        list is not empty, the configuration is corrupted and its caller
810
        should raise an exception
811

812
    """
813
    def _AppendUsedPorts(instance_name, disk, used):
814
      duplicates = []
815
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
816
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
817
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
818
          assert node in used, ("Node '%s' of instance '%s' not found"
819
                                " in node list" % (node, instance_name))
820
          if port in used[node]:
821
            duplicates.append((node, port, instance_name, used[node][port]))
822
          else:
823
            used[node][port] = instance_name
824
      if disk.children:
825
        for child in disk.children:
826
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
827
      return duplicates
828

    
829
    duplicates = []
830
    my_dict = dict((node, {}) for node in self._config_data.nodes)
831
    for instance in self._config_data.instances.itervalues():
832
      for disk in instance.disks:
833
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
834
    for (node, minor), instance in self._temporary_drbds.iteritems():
835
      if minor in my_dict[node] and my_dict[node][minor] != instance:
836
        duplicates.append((node, minor, instance, my_dict[node][minor]))
837
      else:
838
        my_dict[node][minor] = instance
839
    return my_dict, duplicates
840

    
841
  @locking.ssynchronized(_config_lock)
842
  def ComputeDRBDMap(self):
843
    """Compute the used DRBD minor/nodes.
844

845
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
846

847
    @return: dictionary of node_name: dict of minor: instance_name;
848
        the returned dict will have all the nodes in it (even if with
849
        an empty list).
850

851
    """
852
    d_map, duplicates = self._UnlockedComputeDRBDMap()
853
    if duplicates:
854
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
855
                                      str(duplicates))
856
    return d_map
857

    
858
  @locking.ssynchronized(_config_lock)
859
  def AllocateDRBDMinor(self, nodes, instance):
860
    """Allocate a drbd minor.
861

862
    The free minor will be automatically computed from the existing
863
    devices. A node can be given multiple times in order to allocate
864
    multiple minors. The result is the list of minors, in the same
865
    order as the passed nodes.
866

867
    @type instance: string
868
    @param instance: the instance for which we allocate minors
869

870
    """
871
    assert isinstance(instance, basestring), \
872
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
873

    
874
    d_map, duplicates = self._UnlockedComputeDRBDMap()
875
    if duplicates:
876
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
877
                                      str(duplicates))
878
    result = []
879
    for nname in nodes:
880
      ndata = d_map[nname]
881
      if not ndata:
882
        # no minors used, we can start at 0
883
        result.append(0)
884
        ndata[0] = instance
885
        self._temporary_drbds[(nname, 0)] = instance
886
        continue
887
      keys = ndata.keys()
888
      keys.sort()
889
      ffree = utils.FirstFree(keys)
890
      if ffree is None:
891
        # return the next minor
892
        # TODO: implement high-limit check
893
        minor = keys[-1] + 1
894
      else:
895
        minor = ffree
896
      # double-check minor against current instances
897
      assert minor not in d_map[nname], \
898
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
899
              " already allocated to instance %s" %
900
              (minor, nname, d_map[nname][minor]))
901
      ndata[minor] = instance
902
      # double-check minor against reservation
903
      r_key = (nname, minor)
904
      assert r_key not in self._temporary_drbds, \
905
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
906
              " reserved for instance %s" %
907
              (minor, nname, self._temporary_drbds[r_key]))
908
      self._temporary_drbds[r_key] = instance
909
      result.append(minor)
910
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
911
                  nodes, result)
912
    return result
913

    
914
  def _UnlockedReleaseDRBDMinors(self, instance):
915
    """Release temporary drbd minors allocated for a given instance.
916

917
    @type instance: string
918
    @param instance: the instance for which temporary minors should be
919
                     released
920

921
    """
922
    assert isinstance(instance, basestring), \
923
           "Invalid argument passed to ReleaseDRBDMinors"
924
    for key, name in self._temporary_drbds.items():
925
      if name == instance:
926
        del self._temporary_drbds[key]
927

    
928
  @locking.ssynchronized(_config_lock)
929
  def ReleaseDRBDMinors(self, instance):
930
    """Release temporary drbd minors allocated for a given instance.
931

932
    This should be called on the error paths, on the success paths
933
    it's automatically called by the ConfigWriter add and update
934
    functions.
935

936
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
937

938
    @type instance: string
939
    @param instance: the instance for which temporary minors should be
940
                     released
941

942
    """
943
    self._UnlockedReleaseDRBDMinors(instance)
944

    
945
  @locking.ssynchronized(_config_lock, shared=1)
946
  def GetConfigVersion(self):
947
    """Get the configuration version.
948

949
    @return: Config version
950

951
    """
952
    return self._config_data.version
953

    
954
  @locking.ssynchronized(_config_lock, shared=1)
955
  def GetClusterName(self):
956
    """Get cluster name.
957

958
    @return: Cluster name
959

960
    """
961
    return self._config_data.cluster.cluster_name
962

    
963
  @locking.ssynchronized(_config_lock, shared=1)
964
  def GetMasterNode(self):
965
    """Get the hostname of the master node for this cluster.
966

967
    @return: Master hostname
968

969
    """
970
    return self._config_data.cluster.master_node
971

    
972
  @locking.ssynchronized(_config_lock, shared=1)
973
  def GetMasterIP(self):
974
    """Get the IP of the master node for this cluster.
975

976
    @return: Master IP
977

978
    """
979
    return self._config_data.cluster.master_ip
980

    
981
  @locking.ssynchronized(_config_lock, shared=1)
982
  def GetMasterNetdev(self):
983
    """Get the master network device for this cluster.
984

985
    """
986
    return self._config_data.cluster.master_netdev
987

    
988
  @locking.ssynchronized(_config_lock, shared=1)
989
  def GetMasterNetmask(self):
990
    """Get the netmask of the master node for this cluster.
991

992
    """
993
    return self._config_data.cluster.master_netmask
994

    
995
  @locking.ssynchronized(_config_lock, shared=1)
996
  def GetUseExternalMipScript(self):
997
    """Get flag representing whether to use the external master IP setup script.
998

999
    """
1000
    return self._config_data.cluster.use_external_mip_script
1001

    
1002
  @locking.ssynchronized(_config_lock, shared=1)
1003
  def GetFileStorageDir(self):
1004
    """Get the file storage dir for this cluster.
1005

1006
    """
1007
    return self._config_data.cluster.file_storage_dir
1008

    
1009
  @locking.ssynchronized(_config_lock, shared=1)
1010
  def GetSharedFileStorageDir(self):
1011
    """Get the shared file storage dir for this cluster.
1012

1013
    """
1014
    return self._config_data.cluster.shared_file_storage_dir
1015

    
1016
  @locking.ssynchronized(_config_lock, shared=1)
1017
  def GetHypervisorType(self):
1018
    """Get the hypervisor type for this cluster.
1019

1020
    """
1021
    return self._config_data.cluster.enabled_hypervisors[0]
1022

    
1023
  @locking.ssynchronized(_config_lock, shared=1)
1024
  def GetHostKey(self):
1025
    """Return the rsa hostkey from the config.
1026

1027
    @rtype: string
1028
    @return: the rsa hostkey
1029

1030
    """
1031
    return self._config_data.cluster.rsahostkeypub
1032

    
1033
  @locking.ssynchronized(_config_lock, shared=1)
1034
  def GetDefaultIAllocator(self):
1035
    """Get the default instance allocator for this cluster.
1036

1037
    """
1038
    return self._config_data.cluster.default_iallocator
1039

    
1040
  @locking.ssynchronized(_config_lock, shared=1)
1041
  def GetPrimaryIPFamily(self):
1042
    """Get cluster primary ip family.
1043

1044
    @return: primary ip family
1045

1046
    """
1047
    return self._config_data.cluster.primary_ip_family
1048

    
1049
  @locking.ssynchronized(_config_lock, shared=1)
1050
  def GetMasterNetworkParameters(self):
1051
    """Get network parameters of the master node.
1052

1053
    @rtype: L{object.MasterNetworkParameters}
1054
    @return: network parameters of the master node
1055

1056
    """
1057
    cluster = self._config_data.cluster
1058
    result = objects.MasterNetworkParameters(
1059
      name=cluster.master_node, ip=cluster.master_ip,
1060
      netmask=cluster.master_netmask, netdev=cluster.master_netdev,
1061
      ip_family=cluster.primary_ip_family)
1062

    
1063
    return result
1064

    
1065
  @locking.ssynchronized(_config_lock)
1066
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1067
    """Add a node group to the configuration.
1068

1069
    This method calls group.UpgradeConfig() to fill any missing attributes
1070
    according to their default values.
1071

1072
    @type group: L{objects.NodeGroup}
1073
    @param group: the NodeGroup object to add
1074
    @type ec_id: string
1075
    @param ec_id: unique id for the job to use when creating a missing UUID
1076
    @type check_uuid: bool
1077
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1078
                       it does, ensure that it does not exist in the
1079
                       configuration already
1080

1081
    """
1082
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1083
    self._WriteConfig()
1084

    
1085
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1086
    """Add a node group to the configuration.
1087

1088
    """
1089
    logging.info("Adding node group %s to configuration", group.name)
1090

    
1091
    # Some code might need to add a node group with a pre-populated UUID
1092
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1093
    # the "does this UUID" exist already check.
1094
    if check_uuid:
1095
      self._EnsureUUID(group, ec_id)
1096

    
1097
    try:
1098
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1099
    except errors.OpPrereqError:
1100
      pass
1101
    else:
1102
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1103
                                 " node group (UUID: %s)" %
1104
                                 (group.name, existing_uuid),
1105
                                 errors.ECODE_EXISTS)
1106

    
1107
    group.serial_no = 1
1108
    group.ctime = group.mtime = time.time()
1109
    group.UpgradeConfig()
1110

    
1111
    self._config_data.nodegroups[group.uuid] = group
1112
    self._config_data.cluster.serial_no += 1
1113

    
1114
  @locking.ssynchronized(_config_lock)
1115
  def RemoveNodeGroup(self, group_uuid):
1116
    """Remove a node group from the configuration.
1117

1118
    @type group_uuid: string
1119
    @param group_uuid: the UUID of the node group to remove
1120

1121
    """
1122
    logging.info("Removing node group %s from configuration", group_uuid)
1123

    
1124
    if group_uuid not in self._config_data.nodegroups:
1125
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1126

    
1127
    assert len(self._config_data.nodegroups) != 1, \
1128
            "Group '%s' is the only group, cannot be removed" % group_uuid
1129

    
1130
    del self._config_data.nodegroups[group_uuid]
1131
    self._config_data.cluster.serial_no += 1
1132
    self._WriteConfig()
1133

    
1134
  def _UnlockedLookupNodeGroup(self, target):
1135
    """Lookup a node group's UUID.
1136

1137
    @type target: string or None
1138
    @param target: group name or UUID or None to look for the default
1139
    @rtype: string
1140
    @return: nodegroup UUID
1141
    @raises errors.OpPrereqError: when the target group cannot be found
1142

1143
    """
1144
    if target is None:
1145
      if len(self._config_data.nodegroups) != 1:
1146
        raise errors.OpPrereqError("More than one node group exists. Target"
1147
                                   " group must be specified explicitly.")
1148
      else:
1149
        return self._config_data.nodegroups.keys()[0]
1150
    if target in self._config_data.nodegroups:
1151
      return target
1152
    for nodegroup in self._config_data.nodegroups.values():
1153
      if nodegroup.name == target:
1154
        return nodegroup.uuid
1155
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1156
                               errors.ECODE_NOENT)
1157

    
1158
  @locking.ssynchronized(_config_lock, shared=1)
1159
  def LookupNodeGroup(self, target):
1160
    """Lookup a node group's UUID.
1161

1162
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1163

1164
    @type target: string or None
1165
    @param target: group name or UUID or None to look for the default
1166
    @rtype: string
1167
    @return: nodegroup UUID
1168

1169
    """
1170
    return self._UnlockedLookupNodeGroup(target)
1171

    
1172
  def _UnlockedGetNodeGroup(self, uuid):
1173
    """Lookup a node group.
1174

1175
    @type uuid: string
1176
    @param uuid: group UUID
1177
    @rtype: L{objects.NodeGroup} or None
1178
    @return: nodegroup object, or None if not found
1179

1180
    """
1181
    if uuid not in self._config_data.nodegroups:
1182
      return None
1183

    
1184
    return self._config_data.nodegroups[uuid]
1185

    
1186
  @locking.ssynchronized(_config_lock, shared=1)
1187
  def GetNodeGroup(self, uuid):
1188
    """Lookup a node group.
1189

1190
    @type uuid: string
1191
    @param uuid: group UUID
1192
    @rtype: L{objects.NodeGroup} or None
1193
    @return: nodegroup object, or None if not found
1194

1195
    """
1196
    return self._UnlockedGetNodeGroup(uuid)
1197

    
1198
  @locking.ssynchronized(_config_lock, shared=1)
1199
  def GetAllNodeGroupsInfo(self):
1200
    """Get the configuration of all node groups.
1201

1202
    """
1203
    return dict(self._config_data.nodegroups)
1204

    
1205
  @locking.ssynchronized(_config_lock, shared=1)
1206
  def GetNodeGroupList(self):
1207
    """Get a list of node groups.
1208

1209
    """
1210
    return self._config_data.nodegroups.keys()
1211

    
1212
  @locking.ssynchronized(_config_lock, shared=1)
1213
  def GetNodeGroupMembersByNodes(self, nodes):
1214
    """Get nodes which are member in the same nodegroups as the given nodes.
1215

1216
    """
1217
    ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1218
    return frozenset(member_name
1219
                     for node_name in nodes
1220
                     for member_name in
1221
                       self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1222

    
1223
  @locking.ssynchronized(_config_lock, shared=1)
1224
  def GetMultiNodeGroupInfo(self, group_uuids):
1225
    """Get the configuration of multiple node groups.
1226

1227
    @param group_uuids: List of node group UUIDs
1228
    @rtype: list
1229
    @return: List of tuples of (group_uuid, group_info)
1230

1231
    """
1232
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1233

    
1234
  @locking.ssynchronized(_config_lock)
1235
  def AddInstance(self, instance, ec_id):
1236
    """Add an instance to the config.
1237

1238
    This should be used after creating a new instance.
1239

1240
    @type instance: L{objects.Instance}
1241
    @param instance: the instance object
1242

1243
    """
1244
    if not isinstance(instance, objects.Instance):
1245
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1246

    
1247
    if instance.disk_template != constants.DT_DISKLESS:
1248
      all_lvs = instance.MapLVsByNode()
1249
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1250

    
1251
    all_macs = self._AllMACs()
1252
    for nic in instance.nics:
1253
      if nic.mac in all_macs:
1254
        raise errors.ConfigurationError("Cannot add instance %s:"
1255
                                        " MAC address '%s' already in use." %
1256
                                        (instance.name, nic.mac))
1257

    
1258
    self._EnsureUUID(instance, ec_id)
1259

    
1260
    instance.serial_no = 1
1261
    instance.ctime = instance.mtime = time.time()
1262
    self._config_data.instances[instance.name] = instance
1263
    self._config_data.cluster.serial_no += 1
1264
    self._UnlockedReleaseDRBDMinors(instance.name)
1265
    self._WriteConfig()
1266

    
1267
  def _EnsureUUID(self, item, ec_id):
1268
    """Ensures a given object has a valid UUID.
1269

1270
    @param item: the instance or node to be checked
1271
    @param ec_id: the execution context id for the uuid reservation
1272

1273
    """
1274
    if not item.uuid:
1275
      item.uuid = self._GenerateUniqueID(ec_id)
1276
    elif item.uuid in self._AllIDs(include_temporary=True):
1277
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1278
                                      " in use" % (item.name, item.uuid))
1279

    
1280
  def _SetInstanceStatus(self, instance_name, status):
1281
    """Set the instance's status to a given value.
1282

1283
    """
1284
    assert status in constants.ADMINST_ALL, \
1285
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1286

    
1287
    if instance_name not in self._config_data.instances:
1288
      raise errors.ConfigurationError("Unknown instance '%s'" %
1289
                                      instance_name)
1290
    instance = self._config_data.instances[instance_name]
1291
    if instance.admin_state != status:
1292
      instance.admin_state = status
1293
      instance.serial_no += 1
1294
      instance.mtime = time.time()
1295
      self._WriteConfig()
1296

    
1297
  @locking.ssynchronized(_config_lock)
1298
  def MarkInstanceUp(self, instance_name):
1299
    """Mark the instance status to up in the config.
1300

1301
    """
1302
    self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1303

    
1304
  @locking.ssynchronized(_config_lock)
1305
  def MarkInstanceOffline(self, instance_name):
1306
    """Mark the instance status to down in the config.
1307

1308
    """
1309
    self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1310

    
1311
  @locking.ssynchronized(_config_lock)
1312
  def RemoveInstance(self, instance_name):
1313
    """Remove the instance from the configuration.
1314

1315
    """
1316
    if instance_name not in self._config_data.instances:
1317
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1318

    
1319
    # If a network port has been allocated to the instance,
1320
    # return it to the pool of free ports.
1321
    inst = self._config_data.instances[instance_name]
1322
    network_port = getattr(inst, "network_port", None)
1323
    if network_port is not None:
1324
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1325

    
1326
    del self._config_data.instances[instance_name]
1327
    self._config_data.cluster.serial_no += 1
1328
    self._WriteConfig()
1329

    
1330
  @locking.ssynchronized(_config_lock)
1331
  def RenameInstance(self, old_name, new_name):
1332
    """Rename an instance.
1333

1334
    This needs to be done in ConfigWriter and not by RemoveInstance
1335
    combined with AddInstance as only we can guarantee an atomic
1336
    rename.
1337

1338
    """
1339
    if old_name not in self._config_data.instances:
1340
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1341

    
1342
    # Operate on a copy to not loose instance object in case of a failure
1343
    inst = self._config_data.instances[old_name].Copy()
1344
    inst.name = new_name
1345

    
1346
    for (idx, disk) in enumerate(inst.disks):
1347
      if disk.dev_type == constants.LD_FILE:
1348
        # rename the file paths in logical and physical id
1349
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1350
        disk.logical_id = (disk.logical_id[0],
1351
                           utils.PathJoin(file_storage_dir, inst.name,
1352
                                          "disk%s" % idx))
1353
        disk.physical_id = disk.logical_id
1354

    
1355
    # Actually replace instance object
1356
    del self._config_data.instances[old_name]
1357
    self._config_data.instances[inst.name] = inst
1358

    
1359
    # Force update of ssconf files
1360
    self._config_data.cluster.serial_no += 1
1361

    
1362
    self._WriteConfig()
1363

    
1364
  @locking.ssynchronized(_config_lock)
1365
  def MarkInstanceDown(self, instance_name):
1366
    """Mark the status of an instance to down in the configuration.
1367

1368
    """
1369
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1370

    
1371
  def _UnlockedGetInstanceList(self):
1372
    """Get the list of instances.
1373

1374
    This function is for internal use, when the config lock is already held.
1375

1376
    """
1377
    return self._config_data.instances.keys()
1378

    
1379
  @locking.ssynchronized(_config_lock, shared=1)
1380
  def GetInstanceList(self):
1381
    """Get the list of instances.
1382

1383
    @return: array of instances, ex. ['instance2.example.com',
1384
        'instance1.example.com']
1385

1386
    """
1387
    return self._UnlockedGetInstanceList()
1388

    
1389
  def ExpandInstanceName(self, short_name):
1390
    """Attempt to expand an incomplete instance name.
1391

1392
    """
1393
    # Locking is done in L{ConfigWriter.GetInstanceList}
1394
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1395

    
1396
  def _UnlockedGetInstanceInfo(self, instance_name):
1397
    """Returns information about an instance.
1398

1399
    This function is for internal use, when the config lock is already held.
1400

1401
    """
1402
    if instance_name not in self._config_data.instances:
1403
      return None
1404

    
1405
    return self._config_data.instances[instance_name]
1406

    
1407
  @locking.ssynchronized(_config_lock, shared=1)
1408
  def GetInstanceInfo(self, instance_name):
1409
    """Returns information about an instance.
1410

1411
    It takes the information from the configuration file. Other information of
1412
    an instance are taken from the live systems.
1413

1414
    @param instance_name: name of the instance, e.g.
1415
        I{instance1.example.com}
1416

1417
    @rtype: L{objects.Instance}
1418
    @return: the instance object
1419

1420
    """
1421
    return self._UnlockedGetInstanceInfo(instance_name)
1422

    
1423
  @locking.ssynchronized(_config_lock, shared=1)
1424
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1425
    """Returns set of node group UUIDs for instance's nodes.
1426

1427
    @rtype: frozenset
1428

1429
    """
1430
    instance = self._UnlockedGetInstanceInfo(instance_name)
1431
    if not instance:
1432
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1433

    
1434
    if primary_only:
1435
      nodes = [instance.primary_node]
1436
    else:
1437
      nodes = instance.all_nodes
1438

    
1439
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1440
                     for node_name in nodes)
1441

    
1442
  @locking.ssynchronized(_config_lock, shared=1)
1443
  def GetMultiInstanceInfo(self, instances):
1444
    """Get the configuration of multiple instances.
1445

1446
    @param instances: list of instance names
1447
    @rtype: list
1448
    @return: list of tuples (instance, instance_info), where
1449
        instance_info is what would GetInstanceInfo return for the
1450
        node, while keeping the original order
1451

1452
    """
1453
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1454

    
1455
  @locking.ssynchronized(_config_lock, shared=1)
1456
  def GetAllInstancesInfo(self):
1457
    """Get the configuration of all instances.
1458

1459
    @rtype: dict
1460
    @return: dict of (instance, instance_info), where instance_info is what
1461
              would GetInstanceInfo return for the node
1462

1463
    """
1464
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1465
                    for instance in self._UnlockedGetInstanceList()])
1466
    return my_dict
1467

    
1468
  @locking.ssynchronized(_config_lock, shared=1)
1469
  def GetInstancesInfoByFilter(self, filter_fn):
1470
    """Get instance configuration with a filter.
1471

1472
    @type filter_fn: callable
1473
    @param filter_fn: Filter function receiving instance object as parameter,
1474
      returning boolean. Important: this function is called while the
1475
      configuration locks is held. It must not do any complex work or call
1476
      functions potentially leading to a deadlock. Ideally it doesn't call any
1477
      other functions and just compares instance attributes.
1478

1479
    """
1480
    return dict((name, inst)
1481
                for (name, inst) in self._config_data.instances.items()
1482
                if filter_fn(inst))
1483

    
1484
  @locking.ssynchronized(_config_lock)
1485
  def AddNode(self, node, ec_id):
1486
    """Add a node to the configuration.
1487

1488
    @type node: L{objects.Node}
1489
    @param node: a Node instance
1490

1491
    """
1492
    logging.info("Adding node %s to configuration", node.name)
1493

    
1494
    self._EnsureUUID(node, ec_id)
1495

    
1496
    node.serial_no = 1
1497
    node.ctime = node.mtime = time.time()
1498
    self._UnlockedAddNodeToGroup(node.name, node.group)
1499
    self._config_data.nodes[node.name] = node
1500
    self._config_data.cluster.serial_no += 1
1501
    self._WriteConfig()
1502

    
1503
  @locking.ssynchronized(_config_lock)
1504
  def RemoveNode(self, node_name):
1505
    """Remove a node from the configuration.
1506

1507
    """
1508
    logging.info("Removing node %s from configuration", node_name)
1509

    
1510
    if node_name not in self._config_data.nodes:
1511
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1512

    
1513
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1514
    del self._config_data.nodes[node_name]
1515
    self._config_data.cluster.serial_no += 1
1516
    self._WriteConfig()
1517

    
1518
  def ExpandNodeName(self, short_name):
1519
    """Attempt to expand an incomplete node name.
1520

1521
    """
1522
    # Locking is done in L{ConfigWriter.GetNodeList}
1523
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1524

    
1525
  def _UnlockedGetNodeInfo(self, node_name):
1526
    """Get the configuration of a node, as stored in the config.
1527

1528
    This function is for internal use, when the config lock is already
1529
    held.
1530

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

1533
    @rtype: L{objects.Node}
1534
    @return: the node object
1535

1536
    """
1537
    if node_name not in self._config_data.nodes:
1538
      return None
1539

    
1540
    return self._config_data.nodes[node_name]
1541

    
1542
  @locking.ssynchronized(_config_lock, shared=1)
1543
  def GetNodeInfo(self, node_name):
1544
    """Get the configuration of a node, as stored in the config.
1545

1546
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1547

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

1550
    @rtype: L{objects.Node}
1551
    @return: the node object
1552

1553
    """
1554
    return self._UnlockedGetNodeInfo(node_name)
1555

    
1556
  @locking.ssynchronized(_config_lock, shared=1)
1557
  def GetNodeInstances(self, node_name):
1558
    """Get the instances of a node, as stored in the config.
1559

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

1562
    @rtype: (list, list)
1563
    @return: a tuple with two lists: the primary and the secondary instances
1564

1565
    """
1566
    pri = []
1567
    sec = []
1568
    for inst in self._config_data.instances.values():
1569
      if inst.primary_node == node_name:
1570
        pri.append(inst.name)
1571
      if node_name in inst.secondary_nodes:
1572
        sec.append(inst.name)
1573
    return (pri, sec)
1574

    
1575
  @locking.ssynchronized(_config_lock, shared=1)
1576
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1577
    """Get the instances of a node group.
1578

1579
    @param uuid: Node group UUID
1580
    @param primary_only: Whether to only consider primary nodes
1581
    @rtype: frozenset
1582
    @return: List of instance names in node group
1583

1584
    """
1585
    if primary_only:
1586
      nodes_fn = lambda inst: [inst.primary_node]
1587
    else:
1588
      nodes_fn = lambda inst: inst.all_nodes
1589

    
1590
    return frozenset(inst.name
1591
                     for inst in self._config_data.instances.values()
1592
                     for node_name in nodes_fn(inst)
1593
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1594

    
1595
  def _UnlockedGetNodeList(self):
1596
    """Return the list of nodes which are in the configuration.
1597

1598
    This function is for internal use, when the config lock is already
1599
    held.
1600

1601
    @rtype: list
1602

1603
    """
1604
    return self._config_data.nodes.keys()
1605

    
1606
  @locking.ssynchronized(_config_lock, shared=1)
1607
  def GetNodeList(self):
1608
    """Return the list of nodes which are in the configuration.
1609

1610
    """
1611
    return self._UnlockedGetNodeList()
1612

    
1613
  def _UnlockedGetOnlineNodeList(self):
1614
    """Return the list of nodes which are online.
1615

1616
    """
1617
    all_nodes = [self._UnlockedGetNodeInfo(node)
1618
                 for node in self._UnlockedGetNodeList()]
1619
    return [node.name for node in all_nodes if not node.offline]
1620

    
1621
  @locking.ssynchronized(_config_lock, shared=1)
1622
  def GetOnlineNodeList(self):
1623
    """Return the list of nodes which are online.
1624

1625
    """
1626
    return self._UnlockedGetOnlineNodeList()
1627

    
1628
  @locking.ssynchronized(_config_lock, shared=1)
1629
  def GetVmCapableNodeList(self):
1630
    """Return the list of nodes which are not vm capable.
1631

1632
    """
1633
    all_nodes = [self._UnlockedGetNodeInfo(node)
1634
                 for node in self._UnlockedGetNodeList()]
1635
    return [node.name for node in all_nodes if node.vm_capable]
1636

    
1637
  @locking.ssynchronized(_config_lock, shared=1)
1638
  def GetNonVmCapableNodeList(self):
1639
    """Return the list of nodes which are not vm capable.
1640

1641
    """
1642
    all_nodes = [self._UnlockedGetNodeInfo(node)
1643
                 for node in self._UnlockedGetNodeList()]
1644
    return [node.name for node in all_nodes if not node.vm_capable]
1645

    
1646
  @locking.ssynchronized(_config_lock, shared=1)
1647
  def GetMultiNodeInfo(self, nodes):
1648
    """Get the configuration of multiple nodes.
1649

1650
    @param nodes: list of node names
1651
    @rtype: list
1652
    @return: list of tuples of (node, node_info), where node_info is
1653
        what would GetNodeInfo return for the node, in the original
1654
        order
1655

1656
    """
1657
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1658

    
1659
  @locking.ssynchronized(_config_lock, shared=1)
1660
  def GetAllNodesInfo(self):
1661
    """Get the configuration of all nodes.
1662

1663
    @rtype: dict
1664
    @return: dict of (node, node_info), where node_info is what
1665
              would GetNodeInfo return for the node
1666

1667
    """
1668
    return self._UnlockedGetAllNodesInfo()
1669

    
1670
  def _UnlockedGetAllNodesInfo(self):
1671
    """Gets configuration of all nodes.
1672

1673
    @note: See L{GetAllNodesInfo}
1674

1675
    """
1676
    return dict([(node, self._UnlockedGetNodeInfo(node))
1677
                 for node in self._UnlockedGetNodeList()])
1678

    
1679
  @locking.ssynchronized(_config_lock, shared=1)
1680
  def GetNodeGroupsFromNodes(self, nodes):
1681
    """Returns groups for a list of nodes.
1682

1683
    @type nodes: list of string
1684
    @param nodes: List of node names
1685
    @rtype: frozenset
1686

1687
    """
1688
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1689

    
1690
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1691
    """Get the number of current and maximum desired and possible candidates.
1692

1693
    @type exceptions: list
1694
    @param exceptions: if passed, list of nodes that should be ignored
1695
    @rtype: tuple
1696
    @return: tuple of (current, desired and possible, possible)
1697

1698
    """
1699
    mc_now = mc_should = mc_max = 0
1700
    for node in self._config_data.nodes.values():
1701
      if exceptions and node.name in exceptions:
1702
        continue
1703
      if not (node.offline or node.drained) and node.master_capable:
1704
        mc_max += 1
1705
      if node.master_candidate:
1706
        mc_now += 1
1707
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1708
    return (mc_now, mc_should, mc_max)
1709

    
1710
  @locking.ssynchronized(_config_lock, shared=1)
1711
  def GetMasterCandidateStats(self, exceptions=None):
1712
    """Get the number of current and maximum possible candidates.
1713

1714
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1715

1716
    @type exceptions: list
1717
    @param exceptions: if passed, list of nodes that should be ignored
1718
    @rtype: tuple
1719
    @return: tuple of (current, max)
1720

1721
    """
1722
    return self._UnlockedGetMasterCandidateStats(exceptions)
1723

    
1724
  @locking.ssynchronized(_config_lock)
1725
  def MaintainCandidatePool(self, exceptions):
1726
    """Try to grow the candidate pool to the desired size.
1727

1728
    @type exceptions: list
1729
    @param exceptions: if passed, list of nodes that should be ignored
1730
    @rtype: list
1731
    @return: list with the adjusted nodes (L{objects.Node} instances)
1732

1733
    """
1734
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1735
    mod_list = []
1736
    if mc_now < mc_max:
1737
      node_list = self._config_data.nodes.keys()
1738
      random.shuffle(node_list)
1739
      for name in node_list:
1740
        if mc_now >= mc_max:
1741
          break
1742
        node = self._config_data.nodes[name]
1743
        if (node.master_candidate or node.offline or node.drained or
1744
            node.name in exceptions or not node.master_capable):
1745
          continue
1746
        mod_list.append(node)
1747
        node.master_candidate = True
1748
        node.serial_no += 1
1749
        mc_now += 1
1750
      if mc_now != mc_max:
1751
        # this should not happen
1752
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1753
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1754
      if mod_list:
1755
        self._config_data.cluster.serial_no += 1
1756
        self._WriteConfig()
1757

    
1758
    return mod_list
1759

    
1760
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1761
    """Add a given node to the specified group.
1762

1763
    """
1764
    if nodegroup_uuid not in self._config_data.nodegroups:
1765
      # This can happen if a node group gets deleted between its lookup and
1766
      # when we're adding the first node to it, since we don't keep a lock in
1767
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1768
      # is not found anymore.
1769
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1770
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1771
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1772

    
1773
  def _UnlockedRemoveNodeFromGroup(self, node):
1774
    """Remove a given node from its group.
1775

1776
    """
1777
    nodegroup = node.group
1778
    if nodegroup not in self._config_data.nodegroups:
1779
      logging.warning("Warning: node '%s' has unknown node group '%s'"
1780
                      " (while being removed from it)", node.name, nodegroup)
1781
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1782
    if node.name not in nodegroup_obj.members:
1783
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
1784
                      " (while being removed from it)", node.name, nodegroup)
1785
    else:
1786
      nodegroup_obj.members.remove(node.name)
1787

    
1788
  @locking.ssynchronized(_config_lock)
1789
  def AssignGroupNodes(self, mods):
1790
    """Changes the group of a number of nodes.
1791

1792
    @type mods: list of tuples; (node name, new group UUID)
1793
    @param mods: Node membership modifications
1794

1795
    """
1796
    groups = self._config_data.nodegroups
1797
    nodes = self._config_data.nodes
1798

    
1799
    resmod = []
1800

    
1801
    # Try to resolve names/UUIDs first
1802
    for (node_name, new_group_uuid) in mods:
1803
      try:
1804
        node = nodes[node_name]
1805
      except KeyError:
1806
        raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1807

    
1808
      if node.group == new_group_uuid:
1809
        # Node is being assigned to its current group
1810
        logging.debug("Node '%s' was assigned to its current group (%s)",
1811
                      node_name, node.group)
1812
        continue
1813

    
1814
      # Try to find current group of node
1815
      try:
1816
        old_group = groups[node.group]
1817
      except KeyError:
1818
        raise errors.ConfigurationError("Unable to find old group '%s'" %
1819
                                        node.group)
1820

    
1821
      # Try to find new group for node
1822
      try:
1823
        new_group = groups[new_group_uuid]
1824
      except KeyError:
1825
        raise errors.ConfigurationError("Unable to find new group '%s'" %
1826
                                        new_group_uuid)
1827

    
1828
      assert node.name in old_group.members, \
1829
        ("Inconsistent configuration: node '%s' not listed in members for its"
1830
         " old group '%s'" % (node.name, old_group.uuid))
1831
      assert node.name not in new_group.members, \
1832
        ("Inconsistent configuration: node '%s' already listed in members for"
1833
         " its new group '%s'" % (node.name, new_group.uuid))
1834

    
1835
      resmod.append((node, old_group, new_group))
1836

    
1837
    # Apply changes
1838
    for (node, old_group, new_group) in resmod:
1839
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
1840
        "Assigning to current group is not possible"
1841

    
1842
      node.group = new_group.uuid
1843

    
1844
      # Update members of involved groups
1845
      if node.name in old_group.members:
1846
        old_group.members.remove(node.name)
1847
      if node.name not in new_group.members:
1848
        new_group.members.append(node.name)
1849

    
1850
    # Update timestamps and serials (only once per node/group object)
1851
    now = time.time()
1852
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
1853
      obj.serial_no += 1
1854
      obj.mtime = now
1855

    
1856
    # Force ssconf update
1857
    self._config_data.cluster.serial_no += 1
1858

    
1859
    self._WriteConfig()
1860

    
1861
  def _BumpSerialNo(self):
1862
    """Bump up the serial number of the config.
1863

1864
    """
1865
    self._config_data.serial_no += 1
1866
    self._config_data.mtime = time.time()
1867

    
1868
  def _AllUUIDObjects(self):
1869
    """Returns all objects with uuid attributes.
1870

1871
    """
1872
    return (self._config_data.instances.values() +
1873
            self._config_data.nodes.values() +
1874
            self._config_data.nodegroups.values() +
1875
            [self._config_data.cluster])
1876

    
1877
  def _OpenConfig(self, accept_foreign):
1878
    """Read the config data from disk.
1879

1880
    """
1881
    raw_data = utils.ReadFile(self._cfg_file)
1882

    
1883
    try:
1884
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1885
    except Exception, err:
1886
      raise errors.ConfigurationError(err)
1887

    
1888
    # Make sure the configuration has the right version
1889
    _ValidateConfig(data)
1890

    
1891
    if (not hasattr(data, "cluster") or
1892
        not hasattr(data.cluster, "rsahostkeypub")):
1893
      raise errors.ConfigurationError("Incomplete configuration"
1894
                                      " (missing cluster.rsahostkeypub)")
1895

    
1896
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
1897
      msg = ("The configuration denotes node %s as master, while my"
1898
             " hostname is %s; opening a foreign configuration is only"
1899
             " possible in accept_foreign mode" %
1900
             (data.cluster.master_node, self._my_hostname))
1901
      raise errors.ConfigurationError(msg)
1902

    
1903
    # Upgrade configuration if needed
1904
    data.UpgradeConfig()
1905

    
1906
    self._config_data = data
1907
    # reset the last serial as -1 so that the next write will cause
1908
    # ssconf update
1909
    self._last_cluster_serial = -1
1910

    
1911
    # And finally run our (custom) config upgrade sequence
1912
    self._UpgradeConfig()
1913

    
1914
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
1915

    
1916
  def _UpgradeConfig(self):
1917
    """Run upgrade steps that cannot be done purely in the objects.
1918

1919
    This is because some data elements need uniqueness across the
1920
    whole configuration, etc.
1921

1922
    @warning: this function will call L{_WriteConfig()}, but also
1923
        L{DropECReservations} so it needs to be called only from a
1924
        "safe" place (the constructor). If one wanted to call it with
1925
        the lock held, a DropECReservationUnlocked would need to be
1926
        created first, to avoid causing deadlock.
1927

1928
    """
1929
    modified = False
1930
    for item in self._AllUUIDObjects():
1931
      if item.uuid is None:
1932
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1933
        modified = True
1934
    if not self._config_data.nodegroups:
1935
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
1936
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
1937
                                            members=[])
1938
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
1939
      modified = True
1940
    for node in self._config_data.nodes.values():
1941
      if not node.group:
1942
        node.group = self.LookupNodeGroup(None)
1943
        modified = True
1944
      # This is technically *not* an upgrade, but needs to be done both when
1945
      # nodegroups are being added, and upon normally loading the config,
1946
      # because the members list of a node group is discarded upon
1947
      # serializing/deserializing the object.
1948
      self._UnlockedAddNodeToGroup(node.name, node.group)
1949
    if modified:
1950
      self._WriteConfig()
1951
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
1952
      # only called at config init time, without the lock held
1953
      self.DropECReservations(_UPGRADE_CONFIG_JID)
1954

    
1955
  def _DistributeConfig(self, feedback_fn):
1956
    """Distribute the configuration to the other nodes.
1957

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

1961
    """
1962
    if self._offline:
1963
      return True
1964

    
1965
    bad = False
1966

    
1967
    node_list = []
1968
    addr_list = []
1969
    myhostname = self._my_hostname
1970
    # we can skip checking whether _UnlockedGetNodeInfo returns None
1971
    # since the node list comes from _UnlocketGetNodeList, and we are
1972
    # called with the lock held, so no modifications should take place
1973
    # in between
1974
    for node_name in self._UnlockedGetNodeList():
1975
      if node_name == myhostname:
1976
        continue
1977
      node_info = self._UnlockedGetNodeInfo(node_name)
1978
      if not node_info.master_candidate:
1979
        continue
1980
      node_list.append(node_info.name)
1981
      addr_list.append(node_info.primary_ip)
1982

    
1983
    # TODO: Use dedicated resolver talking to config writer for name resolution
1984
    result = \
1985
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
1986
    for to_node, to_result in result.items():
1987
      msg = to_result.fail_msg
1988
      if msg:
1989
        msg = ("Copy of file %s to node %s failed: %s" %
1990
               (self._cfg_file, to_node, msg))
1991
        logging.error(msg)
1992

    
1993
        if feedback_fn:
1994
          feedback_fn(msg)
1995

    
1996
        bad = True
1997

    
1998
    return not bad
1999

    
2000
  def _WriteConfig(self, destination=None, feedback_fn=None):
2001
    """Write the configuration data to persistent storage.
2002

2003
    """
2004
    assert feedback_fn is None or callable(feedback_fn)
2005

    
2006
    # Warn on config errors, but don't abort the save - the
2007
    # configuration has already been modified, and we can't revert;
2008
    # the best we can do is to warn the user and save as is, leaving
2009
    # recovery to the user
2010
    config_errors = self._UnlockedVerifyConfig()
2011
    if config_errors:
2012
      errmsg = ("Configuration data is not consistent: %s" %
2013
                (utils.CommaJoin(config_errors)))
2014
      logging.critical(errmsg)
2015
      if feedback_fn:
2016
        feedback_fn(errmsg)
2017

    
2018
    if destination is None:
2019
      destination = self._cfg_file
2020
    self._BumpSerialNo()
2021
    txt = serializer.Dump(self._config_data.ToDict())
2022

    
2023
    getents = self._getents()
2024
    try:
2025
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2026
                               close=False, gid=getents.confd_gid, mode=0640)
2027
    except errors.LockError:
2028
      raise errors.ConfigurationError("The configuration file has been"
2029
                                      " modified since the last write, cannot"
2030
                                      " update")
2031
    try:
2032
      self._cfg_id = utils.GetFileID(fd=fd)
2033
    finally:
2034
      os.close(fd)
2035

    
2036
    self.write_count += 1
2037

    
2038
    # and redistribute the config file to master candidates
2039
    self._DistributeConfig(feedback_fn)
2040

    
2041
    # Write ssconf files on all nodes (including locally)
2042
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2043
      if not self._offline:
2044
        result = self._GetRpc(None).call_write_ssconf_files(
2045
          self._UnlockedGetOnlineNodeList(),
2046
          self._UnlockedGetSsconfValues())
2047

    
2048
        for nname, nresu in result.items():
2049
          msg = nresu.fail_msg
2050
          if msg:
2051
            errmsg = ("Error while uploading ssconf files to"
2052
                      " node %s: %s" % (nname, msg))
2053
            logging.warning(errmsg)
2054

    
2055
            if feedback_fn:
2056
              feedback_fn(errmsg)
2057

    
2058
      self._last_cluster_serial = self._config_data.cluster.serial_no
2059

    
2060
  def _UnlockedGetSsconfValues(self):
2061
    """Return the values needed by ssconf.
2062

2063
    @rtype: dict
2064
    @return: a dictionary with keys the ssconf names and values their
2065
        associated value
2066

2067
    """
2068
    fn = "\n".join
2069
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
2070
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
2071
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
2072
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2073
                    for ninfo in node_info]
2074
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2075
                    for ninfo in node_info]
2076

    
2077
    instance_data = fn(instance_names)
2078
    off_data = fn(node.name for node in node_info if node.offline)
2079
    on_data = fn(node.name for node in node_info if not node.offline)
2080
    mc_data = fn(node.name for node in node_info if node.master_candidate)
2081
    mc_ips_data = fn(node.primary_ip for node in node_info
2082
                     if node.master_candidate)
2083
    node_data = fn(node_names)
2084
    node_pri_ips_data = fn(node_pri_ips)
2085
    node_snd_ips_data = fn(node_snd_ips)
2086

    
2087
    cluster = self._config_data.cluster
2088
    cluster_tags = fn(cluster.GetTags())
2089

    
2090
    hypervisor_list = fn(cluster.enabled_hypervisors)
2091

    
2092
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2093

    
2094
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2095
                  self._config_data.nodegroups.values()]
2096
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2097

    
2098
    ssconf_values = {
2099
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
2100
      constants.SS_CLUSTER_TAGS: cluster_tags,
2101
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2102
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2103
      constants.SS_MASTER_CANDIDATES: mc_data,
2104
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2105
      constants.SS_MASTER_IP: cluster.master_ip,
2106
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
2107
      constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2108
      constants.SS_MASTER_NODE: cluster.master_node,
2109
      constants.SS_NODE_LIST: node_data,
2110
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2111
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2112
      constants.SS_OFFLINE_NODES: off_data,
2113
      constants.SS_ONLINE_NODES: on_data,
2114
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2115
      constants.SS_INSTANCE_LIST: instance_data,
2116
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2117
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
2118
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2119
      constants.SS_UID_POOL: uid_pool,
2120
      constants.SS_NODEGROUPS: nodegroups_data,
2121
      }
2122
    bad_values = [(k, v) for k, v in ssconf_values.items()
2123
                  if not isinstance(v, (str, basestring))]
2124
    if bad_values:
2125
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2126
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2127
                                      " values: %s" % err)
2128
    return ssconf_values
2129

    
2130
  @locking.ssynchronized(_config_lock, shared=1)
2131
  def GetSsconfValues(self):
2132
    """Wrapper using lock around _UnlockedGetSsconf().
2133

2134
    """
2135
    return self._UnlockedGetSsconfValues()
2136

    
2137
  @locking.ssynchronized(_config_lock, shared=1)
2138
  def GetVGName(self):
2139
    """Return the volume group name.
2140

2141
    """
2142
    return self._config_data.cluster.volume_group_name
2143

    
2144
  @locking.ssynchronized(_config_lock)
2145
  def SetVGName(self, vg_name):
2146
    """Set the volume group name.
2147

2148
    """
2149
    self._config_data.cluster.volume_group_name = vg_name
2150
    self._config_data.cluster.serial_no += 1
2151
    self._WriteConfig()
2152

    
2153
  @locking.ssynchronized(_config_lock, shared=1)
2154
  def GetDRBDHelper(self):
2155
    """Return DRBD usermode helper.
2156

2157
    """
2158
    return self._config_data.cluster.drbd_usermode_helper
2159

    
2160
  @locking.ssynchronized(_config_lock)
2161
  def SetDRBDHelper(self, drbd_helper):
2162
    """Set DRBD usermode helper.
2163

2164
    """
2165
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2166
    self._config_data.cluster.serial_no += 1
2167
    self._WriteConfig()
2168

    
2169
  @locking.ssynchronized(_config_lock, shared=1)
2170
  def GetMACPrefix(self):
2171
    """Return the mac prefix.
2172

2173
    """
2174
    return self._config_data.cluster.mac_prefix
2175

    
2176
  @locking.ssynchronized(_config_lock, shared=1)
2177
  def GetClusterInfo(self):
2178
    """Returns information about the cluster
2179

2180
    @rtype: L{objects.Cluster}
2181
    @return: the cluster object
2182

2183
    """
2184
    return self._config_data.cluster
2185

    
2186
  @locking.ssynchronized(_config_lock, shared=1)
2187
  def HasAnyDiskOfType(self, dev_type):
2188
    """Check if in there is at disk of the given type in the configuration.
2189

2190
    """
2191
    return self._config_data.HasAnyDiskOfType(dev_type)
2192

    
2193
  @locking.ssynchronized(_config_lock)
2194
  def Update(self, target, feedback_fn):
2195
    """Notify function to be called after updates.
2196

2197
    This function must be called when an object (as returned by
2198
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2199
    caller wants the modifications saved to the backing store. Note
2200
    that all modified objects will be saved, but the target argument
2201
    is the one the caller wants to ensure that it's saved.
2202

2203
    @param target: an instance of either L{objects.Cluster},
2204
        L{objects.Node} or L{objects.Instance} which is existing in
2205
        the cluster
2206
    @param feedback_fn: Callable feedback function
2207

2208
    """
2209
    if self._config_data is None:
2210
      raise errors.ProgrammerError("Configuration file not read,"
2211
                                   " cannot save.")
2212
    update_serial = False
2213
    if isinstance(target, objects.Cluster):
2214
      test = target == self._config_data.cluster
2215
    elif isinstance(target, objects.Node):
2216
      test = target in self._config_data.nodes.values()
2217
      update_serial = True
2218
    elif isinstance(target, objects.Instance):
2219
      test = target in self._config_data.instances.values()
2220
    elif isinstance(target, objects.NodeGroup):
2221
      test = target in self._config_data.nodegroups.values()
2222
    else:
2223
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2224
                                   " ConfigWriter.Update" % type(target))
2225
    if not test:
2226
      raise errors.ConfigurationError("Configuration updated since object"
2227
                                      " has been read or unknown object")
2228
    target.serial_no += 1
2229
    target.mtime = now = time.time()
2230

    
2231
    if update_serial:
2232
      # for node updates, we need to increase the cluster serial too
2233
      self._config_data.cluster.serial_no += 1
2234
      self._config_data.cluster.mtime = now
2235

    
2236
    if isinstance(target, objects.Instance):
2237
      self._UnlockedReleaseDRBDMinors(target.name)
2238

    
2239
    self._WriteConfig(feedback_fn=feedback_fn)
2240

    
2241
  @locking.ssynchronized(_config_lock)
2242
  def DropECReservations(self, ec_id):
2243
    """Drop per-execution-context reservations
2244

2245
    """
2246
    for rm in self._all_rms:
2247
      rm.DropECReservations(ec_id)