Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 6488e5bc

History | View | Annotate | Download (97 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 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 copy
38
import os
39
import random
40
import logging
41
import time
42
import itertools
43

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

    
57

    
58
_config_lock = locking.SharedLock("ConfigWriter")
59

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

    
63

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

67
  This only verifies the version of the configuration.
68

69
  @raise errors.ConfigurationError: if the version differs from what
70
      we expect
71

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

    
76

    
77
class TemporaryReservationManager:
78
  """A temporary resource reservation manager.
79

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

83
  """
84
  def __init__(self):
85
    self._ec_reserved = {}
86

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

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

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

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

    
112
  def GetECReserved(self, ec_id):
113
    """ Used when you want to retrieve all reservations for a specific
114
        execution context. E.g when commiting reserved IPs for a specific
115
        network.
116

117
    """
118
    ec_reserved = set()
119
    if ec_id in self._ec_reserved:
120
      ec_reserved.update(self._ec_reserved[ec_id])
121
    return ec_reserved
122

    
123
  def Generate(self, existing, generate_one_fn, ec_id):
124
    """Generate a new resource of this type
125

126
    """
127
    assert callable(generate_one_fn)
128

    
129
    all_elems = self.GetReserved()
130
    all_elems.update(existing)
131
    retries = 64
132
    while retries > 0:
133
      new_resource = generate_one_fn()
134
      if new_resource is not None and new_resource not in all_elems:
135
        break
136
    else:
137
      raise errors.ConfigurationError("Not able generate new resource"
138
                                      " (last tried: %s)" % new_resource)
139
    self.Reserve(ec_id, new_resource)
140
    return new_resource
141

    
142

    
143
def _MatchNameComponentIgnoreCase(short_name, names):
144
  """Wrapper around L{utils.text.MatchNameComponent}.
145

146
  """
147
  return utils.MatchNameComponent(short_name, names, case_sensitive=False)
148

    
149

    
150
def _CheckInstanceDiskIvNames(disks):
151
  """Checks if instance's disks' C{iv_name} attributes are in order.
152

153
  @type disks: list of L{objects.Disk}
154
  @param disks: List of disks
155
  @rtype: list of tuples; (int, string, string)
156
  @return: List of wrongly named disks, each tuple contains disk index,
157
    expected and actual name
158

159
  """
160
  result = []
161

    
162
  for (idx, disk) in enumerate(disks):
163
    exp_iv_name = "disk/%s" % idx
164
    if disk.iv_name != exp_iv_name:
165
      result.append((idx, exp_iv_name, disk.iv_name))
166

    
167
  return result
168

    
169

    
170
class ConfigWriter(object):
171
  """The interface to the cluster configuration.
172

173
  @ivar _temporary_lvs: reservation manager for temporary LVs
174
  @ivar _all_rms: a list of all temporary reservation managers
175

176
  """
177
  def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts,
178
               accept_foreign=False):
179
    self.write_count = 0
180
    self._lock = _config_lock
181
    self._config_data = None
182
    self._offline = offline
183
    if cfg_file is None:
184
      self._cfg_file = pathutils.CLUSTER_CONF_FILE
185
    else:
186
      self._cfg_file = cfg_file
187
    self._getents = _getents
188
    self._temporary_ids = TemporaryReservationManager()
189
    self._temporary_drbds = {}
190
    self._temporary_macs = TemporaryReservationManager()
191
    self._temporary_secrets = TemporaryReservationManager()
192
    self._temporary_lvs = TemporaryReservationManager()
193
    self._temporary_ips = TemporaryReservationManager()
194
    self._all_rms = [self._temporary_ids, self._temporary_macs,
195
                     self._temporary_secrets, self._temporary_lvs,
196
                     self._temporary_ips]
197
    # Note: in order to prevent errors when resolving our name in
198
    # _DistributeConfig, we compute it here once and reuse it; it's
199
    # better to raise an error before starting to modify the config
200
    # file than after it was modified
201
    self._my_hostname = netutils.Hostname.GetSysName()
202
    self._last_cluster_serial = -1
203
    self._cfg_id = None
204
    self._context = None
205
    self._OpenConfig(accept_foreign)
206

    
207
  def _GetRpc(self, address_list):
208
    """Returns RPC runner for configuration.
209

210
    """
211
    return rpc.ConfigRunner(self._context, address_list)
212

    
213
  def SetContext(self, context):
214
    """Sets Ganeti context.
215

216
    """
217
    self._context = context
218

    
219
  # this method needs to be static, so that we can call it on the class
220
  @staticmethod
221
  def IsCluster():
222
    """Check if the cluster is configured.
223

224
    """
225
    return os.path.exists(pathutils.CLUSTER_CONF_FILE)
226

    
227
  @locking.ssynchronized(_config_lock, shared=1)
228
  def GetNdParams(self, node):
229
    """Get the node params populated with cluster defaults.
230

231
    @type node: L{objects.Node}
232
    @param node: The node we want to know the params for
233
    @return: A dict with the filled in node params
234

235
    """
236
    nodegroup = self._UnlockedGetNodeGroup(node.group)
237
    return self._config_data.cluster.FillND(node, nodegroup)
238

    
239
  @locking.ssynchronized(_config_lock, shared=1)
240
  def GetNdGroupParams(self, nodegroup):
241
    """Get the node groups params populated with cluster defaults.
242

243
    @type nodegroup: L{objects.NodeGroup}
244
    @param nodegroup: The node group we want to know the params for
245
    @return: A dict with the filled in node group params
246

247
    """
248
    return self._config_data.cluster.FillNDGroup(nodegroup)
249

    
250
  @locking.ssynchronized(_config_lock, shared=1)
251
  def GetInstanceDiskParams(self, instance):
252
    """Get the disk params populated with inherit chain.
253

254
    @type instance: L{objects.Instance}
255
    @param instance: The instance we want to know the params for
256
    @return: A dict with the filled in disk params
257

258
    """
259
    node = self._UnlockedGetNodeInfo(instance.primary_node)
260
    nodegroup = self._UnlockedGetNodeGroup(node.group)
261
    return self._UnlockedGetGroupDiskParams(nodegroup)
262

    
263
  @locking.ssynchronized(_config_lock, shared=1)
264
  def GetGroupDiskParams(self, group):
265
    """Get the disk params populated with inherit chain.
266

267
    @type group: L{objects.NodeGroup}
268
    @param group: The group we want to know the params for
269
    @return: A dict with the filled in disk params
270

271
    """
272
    return self._UnlockedGetGroupDiskParams(group)
273

    
274
  def _UnlockedGetGroupDiskParams(self, group):
275
    """Get the disk params populated with inherit chain down to node-group.
276

277
    @type group: L{objects.NodeGroup}
278
    @param group: The group we want to know the params for
279
    @return: A dict with the filled in disk params
280

281
    """
282
    return self._config_data.cluster.SimpleFillDP(group.diskparams)
283

    
284
  def _UnlockedGetNetworkMACPrefix(self, net_uuid):
285
    """Return the network mac prefix if it exists or the cluster level default.
286

287
    """
288
    prefix = None
289
    if net_uuid:
290
      nobj = self._UnlockedGetNetwork(net_uuid)
291
      if nobj.mac_prefix:
292
        prefix = nobj.mac_prefix
293

    
294
    return prefix
295

    
296
  def _GenerateOneMAC(self, prefix=None):
297
    """Return a function that randomly generates a MAC suffic
298
       and appends it to the given prefix. If prefix is not given get
299
       the cluster level default.
300

301
    """
302
    if not prefix:
303
      prefix = self._config_data.cluster.mac_prefix
304

    
305
    def GenMac():
306
      byte1 = random.randrange(0, 256)
307
      byte2 = random.randrange(0, 256)
308
      byte3 = random.randrange(0, 256)
309
      mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
310
      return mac
311

    
312
    return GenMac
313

    
314
  @locking.ssynchronized(_config_lock, shared=1)
315
  def GenerateMAC(self, net_uuid, ec_id):
316
    """Generate a MAC for an instance.
317

318
    This should check the current instances for duplicates.
319

320
    """
321
    existing = self._AllMACs()
322
    prefix = self._UnlockedGetNetworkMACPrefix(net_uuid)
323
    gen_mac = self._GenerateOneMAC(prefix)
324
    return self._temporary_ids.Generate(existing, gen_mac, ec_id)
325

    
326
  @locking.ssynchronized(_config_lock, shared=1)
327
  def ReserveMAC(self, mac, ec_id):
328
    """Reserve a MAC for an instance.
329

330
    This only checks instances managed by this cluster, it does not
331
    check for potential collisions elsewhere.
332

333
    """
334
    all_macs = self._AllMACs()
335
    if mac in all_macs:
336
      raise errors.ReservationError("mac already in use")
337
    else:
338
      self._temporary_macs.Reserve(ec_id, mac)
339

    
340
  def _UnlockedCommitTemporaryIps(self, ec_id):
341
    """Commit all reserved IP address to their respective pools
342

343
    """
344
    for action, address, net_uuid in self._temporary_ips.GetECReserved(ec_id):
345
      self._UnlockedCommitIp(action, net_uuid, address)
346

    
347
  def _UnlockedCommitIp(self, action, net_uuid, address):
348
    """Commit a reserved IP address to an IP pool.
349

350
    The IP address is taken from the network's IP pool and marked as reserved.
351

352
    """
353
    nobj = self._UnlockedGetNetwork(net_uuid)
354
    pool = network.AddressPool(nobj)
355
    if action == constants.RESERVE_ACTION:
356
      pool.Reserve(address)
357
    elif action == constants.RELEASE_ACTION:
358
      pool.Release(address)
359

    
360
  def _UnlockedReleaseIp(self, net_uuid, address, ec_id):
361
    """Give a specific IP address back to an IP pool.
362

363
    The IP address is returned to the IP pool designated by pool_id and marked
364
    as reserved.
365

366
    """
367
    self._temporary_ips.Reserve(ec_id,
368
                                (constants.RELEASE_ACTION, address, net_uuid))
369

    
370
  @locking.ssynchronized(_config_lock, shared=1)
371
  def ReleaseIp(self, net_uuid, address, ec_id):
372
    """Give a specified IP address back to an IP pool.
373

374
    This is just a wrapper around _UnlockedReleaseIp.
375

376
    """
377
    if net_uuid:
378
      self._UnlockedReleaseIp(net_uuid, address, ec_id)
379

    
380
  @locking.ssynchronized(_config_lock, shared=1)
381
  def GenerateIp(self, net_uuid, ec_id):
382
    """Find a free IPv4 address for an instance.
383

384
    """
385
    nobj = self._UnlockedGetNetwork(net_uuid)
386
    pool = network.AddressPool(nobj)
387

    
388
    def gen_one():
389
      try:
390
        ip = pool.GenerateFree()
391
      except errors.AddressPoolError:
392
        raise errors.ReservationError("Cannot generate IP. Network is full")
393
      return (constants.RESERVE_ACTION, ip, net_uuid)
394

    
395
    _, address, _ = self._temporary_ips.Generate([], gen_one, ec_id)
396
    return address
397

    
398
  def _UnlockedReserveIp(self, net_uuid, address, ec_id):
399
    """Reserve a given IPv4 address for use by an instance.
400

401
    """
402
    nobj = self._UnlockedGetNetwork(net_uuid)
403
    pool = network.AddressPool(nobj)
404
    try:
405
      isreserved = pool.IsReserved(address)
406
    except errors.AddressPoolError:
407
      raise errors.ReservationError("IP address not in network")
408
    if isreserved:
409
      raise errors.ReservationError("IP address already in use")
410

    
411
    return self._temporary_ips.Reserve(ec_id,
412
                                       (constants.RESERVE_ACTION,
413
                                        address, net_uuid))
414

    
415
  @locking.ssynchronized(_config_lock, shared=1)
416
  def ReserveIp(self, net_uuid, address, ec_id):
417
    """Reserve a given IPv4 address for use by an instance.
418

419
    """
420
    if net_uuid:
421
      return self._UnlockedReserveIp(net_uuid, address, ec_id)
422

    
423
  @locking.ssynchronized(_config_lock, shared=1)
424
  def ReserveLV(self, lv_name, ec_id):
425
    """Reserve an VG/LV pair for an instance.
426

427
    @type lv_name: string
428
    @param lv_name: the logical volume name to reserve
429

430
    """
431
    all_lvs = self._AllLVs()
432
    if lv_name in all_lvs:
433
      raise errors.ReservationError("LV already in use")
434
    else:
435
      self._temporary_lvs.Reserve(ec_id, lv_name)
436

    
437
  @locking.ssynchronized(_config_lock, shared=1)
438
  def GenerateDRBDSecret(self, ec_id):
439
    """Generate a DRBD secret.
440

441
    This checks the current disks for duplicates.
442

443
    """
444
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
445
                                            utils.GenerateSecret,
446
                                            ec_id)
447

    
448
  def _AllLVs(self):
449
    """Compute the list of all LVs.
450

451
    """
452
    lvnames = set()
453
    for instance in self._config_data.instances.values():
454
      node_data = instance.MapLVsByNode()
455
      for lv_list in node_data.values():
456
        lvnames.update(lv_list)
457
    return lvnames
458

    
459
  def _AllDisks(self):
460
    """Compute the list of all Disks (recursively, including children).
461

462
    """
463
    def DiskAndAllChildren(disk):
464
      """Returns a list containing the given disk and all of his children.
465

466
      """
467
      disks = [disk]
468
      if disk.children:
469
        for child_disk in disk.children:
470
          disks.extend(DiskAndAllChildren(child_disk))
471
      return disks
472

    
473
    disks = []
474
    for instance in self._config_data.instances.values():
475
      for disk in instance.disks:
476
        disks.extend(DiskAndAllChildren(disk))
477
    return disks
478

    
479
  def _AllNICs(self):
480
    """Compute the list of all NICs.
481

482
    """
483
    nics = []
484
    for instance in self._config_data.instances.values():
485
      nics.extend(instance.nics)
486
    return nics
487

    
488
  def _AllIDs(self, include_temporary):
489
    """Compute the list of all UUIDs and names we have.
490

491
    @type include_temporary: boolean
492
    @param include_temporary: whether to include the _temporary_ids set
493
    @rtype: set
494
    @return: a set of IDs
495

496
    """
497
    existing = set()
498
    if include_temporary:
499
      existing.update(self._temporary_ids.GetReserved())
500
    existing.update(self._AllLVs())
501
    existing.update(self._config_data.instances.keys())
502
    existing.update(self._config_data.nodes.keys())
503
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
504
    return existing
505

    
506
  def _GenerateUniqueID(self, ec_id):
507
    """Generate an unique UUID.
508

509
    This checks the current node, instances and disk names for
510
    duplicates.
511

512
    @rtype: string
513
    @return: the unique id
514

515
    """
516
    existing = self._AllIDs(include_temporary=False)
517
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
518

    
519
  @locking.ssynchronized(_config_lock, shared=1)
520
  def GenerateUniqueID(self, ec_id):
521
    """Generate an unique ID.
522

523
    This is just a wrapper over the unlocked version.
524

525
    @type ec_id: string
526
    @param ec_id: unique id for the job to reserve the id to
527

528
    """
529
    return self._GenerateUniqueID(ec_id)
530

    
531
  def _AllMACs(self):
532
    """Return all MACs present in the config.
533

534
    @rtype: list
535
    @return: the list of all MACs
536

537
    """
538
    result = []
539
    for instance in self._config_data.instances.values():
540
      for nic in instance.nics:
541
        result.append(nic.mac)
542

    
543
    return result
544

    
545
  def _AllDRBDSecrets(self):
546
    """Return all DRBD secrets present in the config.
547

548
    @rtype: list
549
    @return: the list of all DRBD secrets
550

551
    """
552
    def helper(disk, result):
553
      """Recursively gather secrets from this disk."""
554
      if disk.dev_type == constants.DT_DRBD8:
555
        result.append(disk.logical_id[5])
556
      if disk.children:
557
        for child in disk.children:
558
          helper(child, result)
559

    
560
    result = []
561
    for instance in self._config_data.instances.values():
562
      for disk in instance.disks:
563
        helper(disk, result)
564

    
565
    return result
566

    
567
  def _CheckDiskIDs(self, disk, l_ids):
568
    """Compute duplicate disk IDs
569

570
    @type disk: L{objects.Disk}
571
    @param disk: the disk at which to start searching
572
    @type l_ids: list
573
    @param l_ids: list of current logical ids
574
    @rtype: list
575
    @return: a list of error messages
576

577
    """
578
    result = []
579
    if disk.logical_id is not None:
580
      if disk.logical_id in l_ids:
581
        result.append("duplicate logical id %s" % str(disk.logical_id))
582
      else:
583
        l_ids.append(disk.logical_id)
584

    
585
    if disk.children:
586
      for child in disk.children:
587
        result.extend(self._CheckDiskIDs(child, l_ids))
588
    return result
589

    
590
  def _UnlockedVerifyConfig(self):
591
    """Verify function.
592

593
    @rtype: list
594
    @return: a list of error messages; a non-empty list signifies
595
        configuration errors
596

597
    """
598
    # pylint: disable=R0914
599
    result = []
600
    seen_macs = []
601
    ports = {}
602
    data = self._config_data
603
    cluster = data.cluster
604
    seen_lids = []
605

    
606
    # global cluster checks
607
    if not cluster.enabled_hypervisors:
608
      result.append("enabled hypervisors list doesn't have any entries")
609
    invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
610
    if invalid_hvs:
611
      result.append("enabled hypervisors contains invalid entries: %s" %
612
                    utils.CommaJoin(invalid_hvs))
613
    missing_hvp = (set(cluster.enabled_hypervisors) -
614
                   set(cluster.hvparams.keys()))
615
    if missing_hvp:
616
      result.append("hypervisor parameters missing for the enabled"
617
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
618

    
619
    if not cluster.enabled_disk_templates:
620
      result.append("enabled disk templates list doesn't have any entries")
621
    invalid_disk_templates = set(cluster.enabled_disk_templates) \
622
                               - constants.DISK_TEMPLATES
623
    if invalid_disk_templates:
624
      result.append("enabled disk templates list contains invalid entries:"
625
                    " %s" % utils.CommaJoin(invalid_disk_templates))
626

    
627
    if cluster.master_node not in data.nodes:
628
      result.append("cluster has invalid primary node '%s'" %
629
                    cluster.master_node)
630

    
631
    def _helper(owner, attr, value, template):
632
      try:
633
        utils.ForceDictType(value, template)
634
      except errors.GenericError, err:
635
        result.append("%s has invalid %s: %s" % (owner, attr, err))
636

    
637
    def _helper_nic(owner, params):
638
      try:
639
        objects.NIC.CheckParameterSyntax(params)
640
      except errors.ConfigurationError, err:
641
        result.append("%s has invalid nicparams: %s" % (owner, err))
642

    
643
    def _helper_ipolicy(owner, ipolicy, iscluster):
644
      try:
645
        objects.InstancePolicy.CheckParameterSyntax(ipolicy, iscluster)
646
      except errors.ConfigurationError, err:
647
        result.append("%s has invalid instance policy: %s" % (owner, err))
648
      for key, value in ipolicy.items():
649
        if key == constants.ISPECS_MINMAX:
650
          for k in range(len(value)):
651
            _helper_ispecs(owner, "ipolicy/%s[%s]" % (key, k), value[k])
652
        elif key == constants.ISPECS_STD:
653
          _helper(owner, "ipolicy/" + key, value,
654
                  constants.ISPECS_PARAMETER_TYPES)
655
        else:
656
          # FIXME: assuming list type
657
          if key in constants.IPOLICY_PARAMETERS:
658
            exp_type = float
659
          else:
660
            exp_type = list
661
          if not isinstance(value, exp_type):
662
            result.append("%s has invalid instance policy: for %s,"
663
                          " expecting %s, got %s" %
664
                          (owner, key, exp_type.__name__, type(value)))
665

    
666
    def _helper_ispecs(owner, parentkey, params):
667
      for (key, value) in params.items():
668
        fullkey = "/".join([parentkey, key])
669
        _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
670

    
671
    # check cluster parameters
672
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
673
            constants.BES_PARAMETER_TYPES)
674
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
675
            constants.NICS_PARAMETER_TYPES)
676
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
677
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
678
            constants.NDS_PARAMETER_TYPES)
679
    _helper_ipolicy("cluster", cluster.ipolicy, True)
680

    
681
    for disk_template in cluster.diskparams:
682
      if disk_template not in constants.DTS_HAVE_ACCESS:
683
        continue
684

    
685
      access = cluster.diskparams[disk_template].get(constants.LDP_ACCESS,
686
                                                     constants.DISK_KERNELSPACE)
687
      if access not in constants.DISK_VALID_ACCESS_MODES:
688
        result.append(
689
          "Invalid value of '%s:%s': '%s' (expected one of %s)" % (
690
            disk_template, constants.LDP_ACCESS, access,
691
            utils.CommaJoin(constants.DISK_VALID_ACCESS_MODES)
692
          )
693
        )
694

    
695
    # per-instance checks
696
    for instance_uuid in data.instances:
697
      instance = data.instances[instance_uuid]
698
      if instance.uuid != instance_uuid:
699
        result.append("instance '%s' is indexed by wrong UUID '%s'" %
700
                      (instance.name, instance_uuid))
701
      if instance.primary_node not in data.nodes:
702
        result.append("instance '%s' has invalid primary node '%s'" %
703
                      (instance.name, instance.primary_node))
704
      for snode in instance.secondary_nodes:
705
        if snode not in data.nodes:
706
          result.append("instance '%s' has invalid secondary node '%s'" %
707
                        (instance.name, snode))
708
      for idx, nic in enumerate(instance.nics):
709
        if nic.mac in seen_macs:
710
          result.append("instance '%s' has NIC %d mac %s duplicate" %
711
                        (instance.name, idx, nic.mac))
712
        else:
713
          seen_macs.append(nic.mac)
714
        if nic.nicparams:
715
          filled = cluster.SimpleFillNIC(nic.nicparams)
716
          owner = "instance %s nic %d" % (instance.name, idx)
717
          _helper(owner, "nicparams",
718
                  filled, constants.NICS_PARAMETER_TYPES)
719
          _helper_nic(owner, filled)
720

    
721
      # disk template checks
722
      if not instance.disk_template in data.cluster.enabled_disk_templates:
723
        result.append("instance '%s' uses the disabled disk template '%s'." %
724
                      (instance.name, instance.disk_template))
725

    
726
      # parameter checks
727
      if instance.beparams:
728
        _helper("instance %s" % instance.name, "beparams",
729
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
730

    
731
      # gather the drbd ports for duplicate checks
732
      for (idx, dsk) in enumerate(instance.disks):
733
        if dsk.dev_type in constants.DTS_DRBD:
734
          tcp_port = dsk.logical_id[2]
735
          if tcp_port not in ports:
736
            ports[tcp_port] = []
737
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
738
      # gather network port reservation
739
      net_port = getattr(instance, "network_port", None)
740
      if net_port is not None:
741
        if net_port not in ports:
742
          ports[net_port] = []
743
        ports[net_port].append((instance.name, "network port"))
744

    
745
      # instance disk verify
746
      for idx, disk in enumerate(instance.disks):
747
        result.extend(["instance '%s' disk %d error: %s" %
748
                       (instance.name, idx, msg) for msg in disk.Verify()])
749
        result.extend(self._CheckDiskIDs(disk, seen_lids))
750

    
751
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
752
      if wrong_names:
753
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
754
                         (idx, exp_name, actual_name))
755
                        for (idx, exp_name, actual_name) in wrong_names)
756

    
757
        result.append("Instance '%s' has wrongly named disks: %s" %
758
                      (instance.name, tmp))
759

    
760
    # cluster-wide pool of free ports
761
    for free_port in cluster.tcpudp_port_pool:
762
      if free_port not in ports:
763
        ports[free_port] = []
764
      ports[free_port].append(("cluster", "port marked as free"))
765

    
766
    # compute tcp/udp duplicate ports
767
    keys = ports.keys()
768
    keys.sort()
769
    for pnum in keys:
770
      pdata = ports[pnum]
771
      if len(pdata) > 1:
772
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
773
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
774

    
775
    # highest used tcp port check
776
    if keys:
777
      if keys[-1] > cluster.highest_used_port:
778
        result.append("Highest used port mismatch, saved %s, computed %s" %
779
                      (cluster.highest_used_port, keys[-1]))
780

    
781
    if not data.nodes[cluster.master_node].master_candidate:
782
      result.append("Master node is not a master candidate")
783

    
784
    # master candidate checks
785
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
786
    if mc_now < mc_max:
787
      result.append("Not enough master candidates: actual %d, target %d" %
788
                    (mc_now, mc_max))
789

    
790
    # node checks
791
    for node_uuid, node in data.nodes.items():
792
      if node.uuid != node_uuid:
793
        result.append("Node '%s' is indexed by wrong UUID '%s'" %
794
                      (node.name, node_uuid))
795
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
796
        result.append("Node %s state is invalid: master_candidate=%s,"
797
                      " drain=%s, offline=%s" %
798
                      (node.name, node.master_candidate, node.drained,
799
                       node.offline))
800
      if node.group not in data.nodegroups:
801
        result.append("Node '%s' has invalid group '%s'" %
802
                      (node.name, node.group))
803
      else:
804
        _helper("node %s" % node.name, "ndparams",
805
                cluster.FillND(node, data.nodegroups[node.group]),
806
                constants.NDS_PARAMETER_TYPES)
807
      used_globals = constants.NDC_GLOBALS.intersection(node.ndparams)
808
      if used_globals:
809
        result.append("Node '%s' has some global parameters set: %s" %
810
                      (node.name, utils.CommaJoin(used_globals)))
811

    
812
    # nodegroups checks
813
    nodegroups_names = set()
814
    for nodegroup_uuid in data.nodegroups:
815
      nodegroup = data.nodegroups[nodegroup_uuid]
816
      if nodegroup.uuid != nodegroup_uuid:
817
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
818
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
819
      if utils.UUID_RE.match(nodegroup.name.lower()):
820
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
821
                      (nodegroup.name, nodegroup.uuid))
822
      if nodegroup.name in nodegroups_names:
823
        result.append("duplicate node group name '%s'" % nodegroup.name)
824
      else:
825
        nodegroups_names.add(nodegroup.name)
826
      group_name = "group %s" % nodegroup.name
827
      _helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy),
828
                      False)
829
      if nodegroup.ndparams:
830
        _helper(group_name, "ndparams",
831
                cluster.SimpleFillND(nodegroup.ndparams),
832
                constants.NDS_PARAMETER_TYPES)
833

    
834
    # drbd minors check
835
    _, duplicates = self._UnlockedComputeDRBDMap()
836
    for node, minor, instance_a, instance_b in duplicates:
837
      result.append("DRBD minor %d on node %s is assigned twice to instances"
838
                    " %s and %s" % (minor, node, instance_a, instance_b))
839

    
840
    # IP checks
841
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
842
    ips = {}
843

    
844
    def _AddIpAddress(ip, name):
845
      ips.setdefault(ip, []).append(name)
846

    
847
    _AddIpAddress(cluster.master_ip, "cluster_ip")
848

    
849
    for node in data.nodes.values():
850
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
851
      if node.secondary_ip != node.primary_ip:
852
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
853

    
854
    for instance in data.instances.values():
855
      for idx, nic in enumerate(instance.nics):
856
        if nic.ip is None:
857
          continue
858

    
859
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
860
        nic_mode = nicparams[constants.NIC_MODE]
861
        nic_link = nicparams[constants.NIC_LINK]
862

    
863
        if nic_mode == constants.NIC_MODE_BRIDGED:
864
          link = "bridge:%s" % nic_link
865
        elif nic_mode == constants.NIC_MODE_ROUTED:
866
          link = "route:%s" % nic_link
867
        else:
868
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
869

    
870
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
871
                      "instance:%s/nic:%d" % (instance.name, idx))
872

    
873
    for ip, owners in ips.items():
874
      if len(owners) > 1:
875
        result.append("IP address %s is used by multiple owners: %s" %
876
                      (ip, utils.CommaJoin(owners)))
877

    
878
    return result
879

    
880
  @locking.ssynchronized(_config_lock, shared=1)
881
  def VerifyConfig(self):
882
    """Verify function.
883

884
    This is just a wrapper over L{_UnlockedVerifyConfig}.
885

886
    @rtype: list
887
    @return: a list of error messages; a non-empty list signifies
888
        configuration errors
889

890
    """
891
    return self._UnlockedVerifyConfig()
892

    
893
  @locking.ssynchronized(_config_lock)
894
  def AddTcpUdpPort(self, port):
895
    """Adds a new port to the available port pool.
896

897
    @warning: this method does not "flush" the configuration (via
898
        L{_WriteConfig}); callers should do that themselves once the
899
        configuration is stable
900

901
    """
902
    if not isinstance(port, int):
903
      raise errors.ProgrammerError("Invalid type passed for port")
904

    
905
    self._config_data.cluster.tcpudp_port_pool.add(port)
906

    
907
  @locking.ssynchronized(_config_lock, shared=1)
908
  def GetPortList(self):
909
    """Returns a copy of the current port list.
910

911
    """
912
    return self._config_data.cluster.tcpudp_port_pool.copy()
913

    
914
  @locking.ssynchronized(_config_lock)
915
  def AllocatePort(self):
916
    """Allocate a port.
917

918
    The port will be taken from the available port pool or from the
919
    default port range (and in this case we increase
920
    highest_used_port).
921

922
    """
923
    # If there are TCP/IP ports configured, we use them first.
924
    if self._config_data.cluster.tcpudp_port_pool:
925
      port = self._config_data.cluster.tcpudp_port_pool.pop()
926
    else:
927
      port = self._config_data.cluster.highest_used_port + 1
928
      if port >= constants.LAST_DRBD_PORT:
929
        raise errors.ConfigurationError("The highest used port is greater"
930
                                        " than %s. Aborting." %
931
                                        constants.LAST_DRBD_PORT)
932
      self._config_data.cluster.highest_used_port = port
933

    
934
    self._WriteConfig()
935
    return port
936

    
937
  def _UnlockedComputeDRBDMap(self):
938
    """Compute the used DRBD minor/nodes.
939

940
    @rtype: (dict, list)
941
    @return: dictionary of node_uuid: dict of minor: instance_uuid;
942
        the returned dict will have all the nodes in it (even if with
943
        an empty list), and a list of duplicates; if the duplicates
944
        list is not empty, the configuration is corrupted and its caller
945
        should raise an exception
946

947
    """
948
    def _AppendUsedMinors(get_node_name_fn, instance, disk, used):
949
      duplicates = []
950
      if disk.dev_type == constants.DT_DRBD8 and len(disk.logical_id) >= 5:
951
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
952
        for node_uuid, minor in ((node_a, minor_a), (node_b, minor_b)):
953
          assert node_uuid in used, \
954
            ("Node '%s' of instance '%s' not found in node list" %
955
             (get_node_name_fn(node_uuid), instance.name))
956
          if minor in used[node_uuid]:
957
            duplicates.append((node_uuid, minor, instance.uuid,
958
                               used[node_uuid][minor]))
959
          else:
960
            used[node_uuid][minor] = instance.uuid
961
      if disk.children:
962
        for child in disk.children:
963
          duplicates.extend(_AppendUsedMinors(get_node_name_fn, instance, child,
964
                                              used))
965
      return duplicates
966

    
967
    duplicates = []
968
    my_dict = dict((node_uuid, {}) for node_uuid in self._config_data.nodes)
969
    for instance in self._config_data.instances.itervalues():
970
      for disk in instance.disks:
971
        duplicates.extend(_AppendUsedMinors(self._UnlockedGetNodeName,
972
                                            instance, disk, my_dict))
973
    for (node_uuid, minor), inst_uuid in self._temporary_drbds.iteritems():
974
      if minor in my_dict[node_uuid] and my_dict[node_uuid][minor] != inst_uuid:
975
        duplicates.append((node_uuid, minor, inst_uuid,
976
                           my_dict[node_uuid][minor]))
977
      else:
978
        my_dict[node_uuid][minor] = inst_uuid
979
    return my_dict, duplicates
980

    
981
  @locking.ssynchronized(_config_lock)
982
  def ComputeDRBDMap(self):
983
    """Compute the used DRBD minor/nodes.
984

985
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
986

987
    @return: dictionary of node_uuid: dict of minor: instance_uuid;
988
        the returned dict will have all the nodes in it (even if with
989
        an empty list).
990

991
    """
992
    d_map, duplicates = self._UnlockedComputeDRBDMap()
993
    if duplicates:
994
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
995
                                      str(duplicates))
996
    return d_map
997

    
998
  @locking.ssynchronized(_config_lock)
999
  def AllocateDRBDMinor(self, node_uuids, inst_uuid):
1000
    """Allocate a drbd minor.
1001

1002
    The free minor will be automatically computed from the existing
1003
    devices. A node can be given multiple times in order to allocate
1004
    multiple minors. The result is the list of minors, in the same
1005
    order as the passed nodes.
1006

1007
    @type inst_uuid: string
1008
    @param inst_uuid: the instance for which we allocate minors
1009

1010
    """
1011
    assert isinstance(inst_uuid, basestring), \
1012
           "Invalid argument '%s' passed to AllocateDRBDMinor" % inst_uuid
1013

    
1014
    d_map, duplicates = self._UnlockedComputeDRBDMap()
1015
    if duplicates:
1016
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
1017
                                      str(duplicates))
1018
    result = []
1019
    for nuuid in node_uuids:
1020
      ndata = d_map[nuuid]
1021
      if not ndata:
1022
        # no minors used, we can start at 0
1023
        result.append(0)
1024
        ndata[0] = inst_uuid
1025
        self._temporary_drbds[(nuuid, 0)] = inst_uuid
1026
        continue
1027
      keys = ndata.keys()
1028
      keys.sort()
1029
      ffree = utils.FirstFree(keys)
1030
      if ffree is None:
1031
        # return the next minor
1032
        # TODO: implement high-limit check
1033
        minor = keys[-1] + 1
1034
      else:
1035
        minor = ffree
1036
      # double-check minor against current instances
1037
      assert minor not in d_map[nuuid], \
1038
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
1039
              " already allocated to instance %s" %
1040
              (minor, nuuid, d_map[nuuid][minor]))
1041
      ndata[minor] = inst_uuid
1042
      # double-check minor against reservation
1043
      r_key = (nuuid, minor)
1044
      assert r_key not in self._temporary_drbds, \
1045
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
1046
              " reserved for instance %s" %
1047
              (minor, nuuid, self._temporary_drbds[r_key]))
1048
      self._temporary_drbds[r_key] = inst_uuid
1049
      result.append(minor)
1050
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
1051
                  node_uuids, result)
1052
    return result
1053

    
1054
  def _UnlockedReleaseDRBDMinors(self, inst_uuid):
1055
    """Release temporary drbd minors allocated for a given instance.
1056

1057
    @type inst_uuid: string
1058
    @param inst_uuid: the instance for which temporary minors should be
1059
                      released
1060

1061
    """
1062
    assert isinstance(inst_uuid, basestring), \
1063
           "Invalid argument passed to ReleaseDRBDMinors"
1064
    for key, uuid in self._temporary_drbds.items():
1065
      if uuid == inst_uuid:
1066
        del self._temporary_drbds[key]
1067

    
1068
  @locking.ssynchronized(_config_lock)
1069
  def ReleaseDRBDMinors(self, inst_uuid):
1070
    """Release temporary drbd minors allocated for a given instance.
1071

1072
    This should be called on the error paths, on the success paths
1073
    it's automatically called by the ConfigWriter add and update
1074
    functions.
1075

1076
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1077

1078
    @type inst_uuid: string
1079
    @param inst_uuid: the instance for which temporary minors should be
1080
                      released
1081

1082
    """
1083
    self._UnlockedReleaseDRBDMinors(inst_uuid)
1084

    
1085
  @locking.ssynchronized(_config_lock, shared=1)
1086
  def GetConfigVersion(self):
1087
    """Get the configuration version.
1088

1089
    @return: Config version
1090

1091
    """
1092
    return self._config_data.version
1093

    
1094
  @locking.ssynchronized(_config_lock, shared=1)
1095
  def GetClusterName(self):
1096
    """Get cluster name.
1097

1098
    @return: Cluster name
1099

1100
    """
1101
    return self._config_data.cluster.cluster_name
1102

    
1103
  @locking.ssynchronized(_config_lock, shared=1)
1104
  def GetMasterNode(self):
1105
    """Get the UUID of the master node for this cluster.
1106

1107
    @return: Master node UUID
1108

1109
    """
1110
    return self._config_data.cluster.master_node
1111

    
1112
  @locking.ssynchronized(_config_lock, shared=1)
1113
  def GetMasterNodeName(self):
1114
    """Get the hostname of the master node for this cluster.
1115

1116
    @return: Master node hostname
1117

1118
    """
1119
    return self._UnlockedGetNodeName(self._config_data.cluster.master_node)
1120

    
1121
  @locking.ssynchronized(_config_lock, shared=1)
1122
  def GetMasterNodeInfo(self):
1123
    """Get the master node information for this cluster.
1124

1125
    @rtype: objects.Node
1126
    @return: Master node L{objects.Node} object
1127

1128
    """
1129
    return self._UnlockedGetNodeInfo(self._config_data.cluster.master_node)
1130

    
1131
  @locking.ssynchronized(_config_lock, shared=1)
1132
  def GetMasterIP(self):
1133
    """Get the IP of the master node for this cluster.
1134

1135
    @return: Master IP
1136

1137
    """
1138
    return self._config_data.cluster.master_ip
1139

    
1140
  @locking.ssynchronized(_config_lock, shared=1)
1141
  def GetMasterNetdev(self):
1142
    """Get the master network device for this cluster.
1143

1144
    """
1145
    return self._config_data.cluster.master_netdev
1146

    
1147
  @locking.ssynchronized(_config_lock, shared=1)
1148
  def GetMasterNetmask(self):
1149
    """Get the netmask of the master node for this cluster.
1150

1151
    """
1152
    return self._config_data.cluster.master_netmask
1153

    
1154
  @locking.ssynchronized(_config_lock, shared=1)
1155
  def GetUseExternalMipScript(self):
1156
    """Get flag representing whether to use the external master IP setup script.
1157

1158
    """
1159
    return self._config_data.cluster.use_external_mip_script
1160

    
1161
  @locking.ssynchronized(_config_lock, shared=1)
1162
  def GetFileStorageDir(self):
1163
    """Get the file storage dir for this cluster.
1164

1165
    """
1166
    return self._config_data.cluster.file_storage_dir
1167

    
1168
  @locking.ssynchronized(_config_lock, shared=1)
1169
  def GetSharedFileStorageDir(self):
1170
    """Get the shared file storage dir for this cluster.
1171

1172
    """
1173
    return self._config_data.cluster.shared_file_storage_dir
1174

    
1175
  @locking.ssynchronized(_config_lock, shared=1)
1176
  def GetGlusterStorageDir(self):
1177
    """Get the Gluster storage dir for this cluster.
1178

1179
    """
1180
    return self._config_data.cluster.gluster_storage_dir
1181

    
1182
  @locking.ssynchronized(_config_lock, shared=1)
1183
  def GetHypervisorType(self):
1184
    """Get the hypervisor type for this cluster.
1185

1186
    """
1187
    return self._config_data.cluster.enabled_hypervisors[0]
1188

    
1189
  @locking.ssynchronized(_config_lock, shared=1)
1190
  def GetRsaHostKey(self):
1191
    """Return the rsa hostkey from the config.
1192

1193
    @rtype: string
1194
    @return: the rsa hostkey
1195

1196
    """
1197
    return self._config_data.cluster.rsahostkeypub
1198

    
1199
  @locking.ssynchronized(_config_lock, shared=1)
1200
  def GetDsaHostKey(self):
1201
    """Return the dsa hostkey from the config.
1202

1203
    @rtype: string
1204
    @return: the dsa hostkey
1205

1206
    """
1207
    return self._config_data.cluster.dsahostkeypub
1208

    
1209
  @locking.ssynchronized(_config_lock, shared=1)
1210
  def GetDefaultIAllocator(self):
1211
    """Get the default instance allocator for this cluster.
1212

1213
    """
1214
    return self._config_data.cluster.default_iallocator
1215

    
1216
  @locking.ssynchronized(_config_lock, shared=1)
1217
  def GetDefaultIAllocatorParameters(self):
1218
    """Get the default instance allocator parameters for this cluster.
1219

1220
    @rtype: dict
1221
    @return: dict of iallocator parameters
1222

1223
    """
1224
    return self._config_data.cluster.default_iallocator_params
1225

    
1226
  @locking.ssynchronized(_config_lock, shared=1)
1227
  def GetPrimaryIPFamily(self):
1228
    """Get cluster primary ip family.
1229

1230
    @return: primary ip family
1231

1232
    """
1233
    return self._config_data.cluster.primary_ip_family
1234

    
1235
  @locking.ssynchronized(_config_lock, shared=1)
1236
  def GetMasterNetworkParameters(self):
1237
    """Get network parameters of the master node.
1238

1239
    @rtype: L{object.MasterNetworkParameters}
1240
    @return: network parameters of the master node
1241

1242
    """
1243
    cluster = self._config_data.cluster
1244
    result = objects.MasterNetworkParameters(
1245
      uuid=cluster.master_node, ip=cluster.master_ip,
1246
      netmask=cluster.master_netmask, netdev=cluster.master_netdev,
1247
      ip_family=cluster.primary_ip_family)
1248

    
1249
    return result
1250

    
1251
  @locking.ssynchronized(_config_lock)
1252
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1253
    """Add a node group to the configuration.
1254

1255
    This method calls group.UpgradeConfig() to fill any missing attributes
1256
    according to their default values.
1257

1258
    @type group: L{objects.NodeGroup}
1259
    @param group: the NodeGroup object to add
1260
    @type ec_id: string
1261
    @param ec_id: unique id for the job to use when creating a missing UUID
1262
    @type check_uuid: bool
1263
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1264
                       it does, ensure that it does not exist in the
1265
                       configuration already
1266

1267
    """
1268
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1269
    self._WriteConfig()
1270

    
1271
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1272
    """Add a node group to the configuration.
1273

1274
    """
1275
    logging.info("Adding node group %s to configuration", group.name)
1276

    
1277
    # Some code might need to add a node group with a pre-populated UUID
1278
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1279
    # the "does this UUID" exist already check.
1280
    if check_uuid:
1281
      self._EnsureUUID(group, ec_id)
1282

    
1283
    try:
1284
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1285
    except errors.OpPrereqError:
1286
      pass
1287
    else:
1288
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1289
                                 " node group (UUID: %s)" %
1290
                                 (group.name, existing_uuid),
1291
                                 errors.ECODE_EXISTS)
1292

    
1293
    group.serial_no = 1
1294
    group.ctime = group.mtime = time.time()
1295
    group.UpgradeConfig()
1296

    
1297
    self._config_data.nodegroups[group.uuid] = group
1298
    self._config_data.cluster.serial_no += 1
1299

    
1300
  @locking.ssynchronized(_config_lock)
1301
  def RemoveNodeGroup(self, group_uuid):
1302
    """Remove a node group from the configuration.
1303

1304
    @type group_uuid: string
1305
    @param group_uuid: the UUID of the node group to remove
1306

1307
    """
1308
    logging.info("Removing node group %s from configuration", group_uuid)
1309

    
1310
    if group_uuid not in self._config_data.nodegroups:
1311
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1312

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

    
1316
    del self._config_data.nodegroups[group_uuid]
1317
    self._config_data.cluster.serial_no += 1
1318
    self._WriteConfig()
1319

    
1320
  def _UnlockedLookupNodeGroup(self, target):
1321
    """Lookup a node group's UUID.
1322

1323
    @type target: string or None
1324
    @param target: group name or UUID or None to look for the default
1325
    @rtype: string
1326
    @return: nodegroup UUID
1327
    @raises errors.OpPrereqError: when the target group cannot be found
1328

1329
    """
1330
    if target is None:
1331
      if len(self._config_data.nodegroups) != 1:
1332
        raise errors.OpPrereqError("More than one node group exists. Target"
1333
                                   " group must be specified explicitly.")
1334
      else:
1335
        return self._config_data.nodegroups.keys()[0]
1336
    if target in self._config_data.nodegroups:
1337
      return target
1338
    for nodegroup in self._config_data.nodegroups.values():
1339
      if nodegroup.name == target:
1340
        return nodegroup.uuid
1341
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1342
                               errors.ECODE_NOENT)
1343

    
1344
  @locking.ssynchronized(_config_lock, shared=1)
1345
  def LookupNodeGroup(self, target):
1346
    """Lookup a node group's UUID.
1347

1348
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1349

1350
    @type target: string or None
1351
    @param target: group name or UUID or None to look for the default
1352
    @rtype: string
1353
    @return: nodegroup UUID
1354

1355
    """
1356
    return self._UnlockedLookupNodeGroup(target)
1357

    
1358
  def _UnlockedGetNodeGroup(self, uuid):
1359
    """Lookup a node group.
1360

1361
    @type uuid: string
1362
    @param uuid: group UUID
1363
    @rtype: L{objects.NodeGroup} or None
1364
    @return: nodegroup object, or None if not found
1365

1366
    """
1367
    if uuid not in self._config_data.nodegroups:
1368
      return None
1369

    
1370
    return self._config_data.nodegroups[uuid]
1371

    
1372
  @locking.ssynchronized(_config_lock, shared=1)
1373
  def GetNodeGroup(self, uuid):
1374
    """Lookup a node group.
1375

1376
    @type uuid: string
1377
    @param uuid: group UUID
1378
    @rtype: L{objects.NodeGroup} or None
1379
    @return: nodegroup object, or None if not found
1380

1381
    """
1382
    return self._UnlockedGetNodeGroup(uuid)
1383

    
1384
  def _UnlockedGetAllNodeGroupsInfo(self):
1385
    """Get the configuration of all node groups.
1386

1387
    """
1388
    return dict(self._config_data.nodegroups)
1389

    
1390
  @locking.ssynchronized(_config_lock, shared=1)
1391
  def GetAllNodeGroupsInfo(self):
1392
    """Get the configuration of all node groups.
1393

1394
    """
1395
    return self._UnlockedGetAllNodeGroupsInfo()
1396

    
1397
  @locking.ssynchronized(_config_lock, shared=1)
1398
  def GetAllNodeGroupsInfoDict(self):
1399
    """Get the configuration of all node groups expressed as a dictionary of
1400
    dictionaries.
1401

1402
    """
1403
    return dict(map(lambda (uuid, ng): (uuid, ng.ToDict()),
1404
                    self._UnlockedGetAllNodeGroupsInfo().items()))
1405

    
1406
  @locking.ssynchronized(_config_lock, shared=1)
1407
  def GetNodeGroupList(self):
1408
    """Get a list of node groups.
1409

1410
    """
1411
    return self._config_data.nodegroups.keys()
1412

    
1413
  @locking.ssynchronized(_config_lock, shared=1)
1414
  def GetNodeGroupMembersByNodes(self, nodes):
1415
    """Get nodes which are member in the same nodegroups as the given nodes.
1416

1417
    """
1418
    ngfn = lambda node_uuid: self._UnlockedGetNodeInfo(node_uuid).group
1419
    return frozenset(member_uuid
1420
                     for node_uuid in nodes
1421
                     for member_uuid in
1422
                       self._UnlockedGetNodeGroup(ngfn(node_uuid)).members)
1423

    
1424
  @locking.ssynchronized(_config_lock, shared=1)
1425
  def GetMultiNodeGroupInfo(self, group_uuids):
1426
    """Get the configuration of multiple node groups.
1427

1428
    @param group_uuids: List of node group UUIDs
1429
    @rtype: list
1430
    @return: List of tuples of (group_uuid, group_info)
1431

1432
    """
1433
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1434

    
1435
  @locking.ssynchronized(_config_lock)
1436
  def AddInstance(self, instance, ec_id):
1437
    """Add an instance to the config.
1438

1439
    This should be used after creating a new instance.
1440

1441
    @type instance: L{objects.Instance}
1442
    @param instance: the instance object
1443

1444
    """
1445
    if not isinstance(instance, objects.Instance):
1446
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1447

    
1448
    if instance.disk_template != constants.DT_DISKLESS:
1449
      all_lvs = instance.MapLVsByNode()
1450
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1451

    
1452
    all_macs = self._AllMACs()
1453
    for nic in instance.nics:
1454
      if nic.mac in all_macs:
1455
        raise errors.ConfigurationError("Cannot add instance %s:"
1456
                                        " MAC address '%s' already in use." %
1457
                                        (instance.name, nic.mac))
1458

    
1459
    self._CheckUniqueUUID(instance, include_temporary=False)
1460

    
1461
    instance.serial_no = 1
1462
    instance.ctime = instance.mtime = time.time()
1463
    self._config_data.instances[instance.uuid] = instance
1464
    self._config_data.cluster.serial_no += 1
1465
    self._UnlockedReleaseDRBDMinors(instance.uuid)
1466
    self._UnlockedCommitTemporaryIps(ec_id)
1467
    self._WriteConfig()
1468

    
1469
  def _EnsureUUID(self, item, ec_id):
1470
    """Ensures a given object has a valid UUID.
1471

1472
    @param item: the instance or node to be checked
1473
    @param ec_id: the execution context id for the uuid reservation
1474

1475
    """
1476
    if not item.uuid:
1477
      item.uuid = self._GenerateUniqueID(ec_id)
1478
    else:
1479
      self._CheckUniqueUUID(item, include_temporary=True)
1480

    
1481
  def _CheckUniqueUUID(self, item, include_temporary):
1482
    """Checks that the UUID of the given object is unique.
1483

1484
    @param item: the instance or node to be checked
1485
    @param include_temporary: whether temporarily generated UUID's should be
1486
              included in the check. If the UUID of the item to be checked is
1487
              a temporarily generated one, this has to be C{False}.
1488

1489
    """
1490
    if not item.uuid:
1491
      raise errors.ConfigurationError("'%s' must have an UUID" % (item.name,))
1492
    if item.uuid in self._AllIDs(include_temporary=include_temporary):
1493
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1494
                                      " in use" % (item.name, item.uuid))
1495

    
1496
  def _SetInstanceStatus(self, inst_uuid, status, disks_active):
1497
    """Set the instance's status to a given value.
1498

1499
    """
1500
    if inst_uuid not in self._config_data.instances:
1501
      raise errors.ConfigurationError("Unknown instance '%s'" %
1502
                                      inst_uuid)
1503
    instance = self._config_data.instances[inst_uuid]
1504

    
1505
    if status is None:
1506
      status = instance.admin_state
1507
    if disks_active is None:
1508
      disks_active = instance.disks_active
1509

    
1510
    assert status in constants.ADMINST_ALL, \
1511
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1512

    
1513
    if instance.admin_state != status or \
1514
       instance.disks_active != disks_active:
1515
      instance.admin_state = status
1516
      instance.disks_active = disks_active
1517
      instance.serial_no += 1
1518
      instance.mtime = time.time()
1519
      self._WriteConfig()
1520

    
1521
  @locking.ssynchronized(_config_lock)
1522
  def MarkInstanceUp(self, inst_uuid):
1523
    """Mark the instance status to up in the config.
1524

1525
    This also sets the instance disks active flag.
1526

1527
    """
1528
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_UP, True)
1529

    
1530
  @locking.ssynchronized(_config_lock)
1531
  def MarkInstanceOffline(self, inst_uuid):
1532
    """Mark the instance status to down in the config.
1533

1534
    This also clears the instance disks active flag.
1535

1536
    """
1537
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_OFFLINE, False)
1538

    
1539
  @locking.ssynchronized(_config_lock)
1540
  def RemoveInstance(self, inst_uuid):
1541
    """Remove the instance from the configuration.
1542

1543
    """
1544
    if inst_uuid not in self._config_data.instances:
1545
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1546

    
1547
    # If a network port has been allocated to the instance,
1548
    # return it to the pool of free ports.
1549
    inst = self._config_data.instances[inst_uuid]
1550
    network_port = getattr(inst, "network_port", None)
1551
    if network_port is not None:
1552
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1553

    
1554
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1555

    
1556
    for nic in instance.nics:
1557
      if nic.network and nic.ip:
1558
        # Return all IP addresses to the respective address pools
1559
        self._UnlockedCommitIp(constants.RELEASE_ACTION, nic.network, nic.ip)
1560

    
1561
    del self._config_data.instances[inst_uuid]
1562
    self._config_data.cluster.serial_no += 1
1563
    self._WriteConfig()
1564

    
1565
  @locking.ssynchronized(_config_lock)
1566
  def RenameInstance(self, inst_uuid, new_name):
1567
    """Rename an instance.
1568

1569
    This needs to be done in ConfigWriter and not by RemoveInstance
1570
    combined with AddInstance as only we can guarantee an atomic
1571
    rename.
1572

1573
    """
1574
    if inst_uuid not in self._config_data.instances:
1575
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1576

    
1577
    inst = self._config_data.instances[inst_uuid]
1578
    inst.name = new_name
1579

    
1580
    for (idx, disk) in enumerate(inst.disks):
1581
      if disk.dev_type in [constants.DT_FILE, constants.DT_SHARED_FILE]:
1582
        # rename the file paths in logical and physical id
1583
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1584
        disk.logical_id = (disk.logical_id[0],
1585
                           utils.PathJoin(file_storage_dir, inst.name,
1586
                                          "disk%s" % idx))
1587

    
1588
    # Force update of ssconf files
1589
    self._config_data.cluster.serial_no += 1
1590

    
1591
    self._WriteConfig()
1592

    
1593
  @locking.ssynchronized(_config_lock)
1594
  def MarkInstanceDown(self, inst_uuid):
1595
    """Mark the status of an instance to down in the configuration.
1596

1597
    This does not touch the instance disks active flag, as shut down instances
1598
    can still have active disks.
1599

1600
    """
1601
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_DOWN, None)
1602

    
1603
  @locking.ssynchronized(_config_lock)
1604
  def MarkInstanceDisksActive(self, inst_uuid):
1605
    """Mark the status of instance disks active.
1606

1607
    """
1608
    self._SetInstanceStatus(inst_uuid, None, True)
1609

    
1610
  @locking.ssynchronized(_config_lock)
1611
  def MarkInstanceDisksInactive(self, inst_uuid):
1612
    """Mark the status of instance disks inactive.
1613

1614
    """
1615
    self._SetInstanceStatus(inst_uuid, None, False)
1616

    
1617
  def _UnlockedGetInstanceList(self):
1618
    """Get the list of instances.
1619

1620
    This function is for internal use, when the config lock is already held.
1621

1622
    """
1623
    return self._config_data.instances.keys()
1624

    
1625
  @locking.ssynchronized(_config_lock, shared=1)
1626
  def GetInstanceList(self):
1627
    """Get the list of instances.
1628

1629
    @return: array of instances, ex. ['instance2-uuid', 'instance1-uuid']
1630

1631
    """
1632
    return self._UnlockedGetInstanceList()
1633

    
1634
  def ExpandInstanceName(self, short_name):
1635
    """Attempt to expand an incomplete instance name.
1636

1637
    """
1638
    # Locking is done in L{ConfigWriter.GetAllInstancesInfo}
1639
    all_insts = self.GetAllInstancesInfo().values()
1640
    expanded_name = _MatchNameComponentIgnoreCase(
1641
                      short_name, [inst.name for inst in all_insts])
1642

    
1643
    if expanded_name is not None:
1644
      # there has to be exactly one instance with that name
1645
      inst = (filter(lambda n: n.name == expanded_name, all_insts)[0])
1646
      return (inst.uuid, inst.name)
1647
    else:
1648
      return (None, None)
1649

    
1650
  def _UnlockedGetInstanceInfo(self, inst_uuid):
1651
    """Returns information about an instance.
1652

1653
    This function is for internal use, when the config lock is already held.
1654

1655
    """
1656
    if inst_uuid not in self._config_data.instances:
1657
      return None
1658

    
1659
    return self._config_data.instances[inst_uuid]
1660

    
1661
  @locking.ssynchronized(_config_lock, shared=1)
1662
  def GetInstanceInfo(self, inst_uuid):
1663
    """Returns information about an instance.
1664

1665
    It takes the information from the configuration file. Other information of
1666
    an instance are taken from the live systems.
1667

1668
    @param inst_uuid: UUID of the instance
1669

1670
    @rtype: L{objects.Instance}
1671
    @return: the instance object
1672

1673
    """
1674
    return self._UnlockedGetInstanceInfo(inst_uuid)
1675

    
1676
  @locking.ssynchronized(_config_lock, shared=1)
1677
  def GetInstanceNodeGroups(self, inst_uuid, primary_only=False):
1678
    """Returns set of node group UUIDs for instance's nodes.
1679

1680
    @rtype: frozenset
1681

1682
    """
1683
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1684
    if not instance:
1685
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1686

    
1687
    if primary_only:
1688
      nodes = [instance.primary_node]
1689
    else:
1690
      nodes = instance.all_nodes
1691

    
1692
    return frozenset(self._UnlockedGetNodeInfo(node_uuid).group
1693
                     for node_uuid in nodes)
1694

    
1695
  @locking.ssynchronized(_config_lock, shared=1)
1696
  def GetInstanceNetworks(self, inst_uuid):
1697
    """Returns set of network UUIDs for instance's nics.
1698

1699
    @rtype: frozenset
1700

1701
    """
1702
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1703
    if not instance:
1704
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1705

    
1706
    networks = set()
1707
    for nic in instance.nics:
1708
      if nic.network:
1709
        networks.add(nic.network)
1710

    
1711
    return frozenset(networks)
1712

    
1713
  @locking.ssynchronized(_config_lock, shared=1)
1714
  def GetMultiInstanceInfo(self, inst_uuids):
1715
    """Get the configuration of multiple instances.
1716

1717
    @param inst_uuids: list of instance UUIDs
1718
    @rtype: list
1719
    @return: list of tuples (instance UUID, instance_info), where
1720
        instance_info is what would GetInstanceInfo return for the
1721
        node, while keeping the original order
1722

1723
    """
1724
    return [(uuid, self._UnlockedGetInstanceInfo(uuid)) for uuid in inst_uuids]
1725

    
1726
  @locking.ssynchronized(_config_lock, shared=1)
1727
  def GetMultiInstanceInfoByName(self, inst_names):
1728
    """Get the configuration of multiple instances.
1729

1730
    @param inst_names: list of instance names
1731
    @rtype: list
1732
    @return: list of tuples (instance, instance_info), where
1733
        instance_info is what would GetInstanceInfo return for the
1734
        node, while keeping the original order
1735

1736
    """
1737
    result = []
1738
    for name in inst_names:
1739
      instance = self._UnlockedGetInstanceInfoByName(name)
1740
      result.append((instance.uuid, instance))
1741
    return result
1742

    
1743
  @locking.ssynchronized(_config_lock, shared=1)
1744
  def GetAllInstancesInfo(self):
1745
    """Get the configuration of all instances.
1746

1747
    @rtype: dict
1748
    @return: dict of (instance, instance_info), where instance_info is what
1749
              would GetInstanceInfo return for the node
1750

1751
    """
1752
    return self._UnlockedGetAllInstancesInfo()
1753

    
1754
  def _UnlockedGetAllInstancesInfo(self):
1755
    my_dict = dict([(inst_uuid, self._UnlockedGetInstanceInfo(inst_uuid))
1756
                    for inst_uuid in self._UnlockedGetInstanceList()])
1757
    return my_dict
1758

    
1759
  @locking.ssynchronized(_config_lock, shared=1)
1760
  def GetInstancesInfoByFilter(self, filter_fn):
1761
    """Get instance configuration with a filter.
1762

1763
    @type filter_fn: callable
1764
    @param filter_fn: Filter function receiving instance object as parameter,
1765
      returning boolean. Important: this function is called while the
1766
      configuration locks is held. It must not do any complex work or call
1767
      functions potentially leading to a deadlock. Ideally it doesn't call any
1768
      other functions and just compares instance attributes.
1769

1770
    """
1771
    return dict((uuid, inst)
1772
                for (uuid, inst) in self._config_data.instances.items()
1773
                if filter_fn(inst))
1774

    
1775
  @locking.ssynchronized(_config_lock, shared=1)
1776
  def GetInstanceInfoByName(self, inst_name):
1777
    """Get the L{objects.Instance} object for a named instance.
1778

1779
    @param inst_name: name of the instance to get information for
1780
    @type inst_name: string
1781
    @return: the corresponding L{objects.Instance} instance or None if no
1782
          information is available
1783

1784
    """
1785
    return self._UnlockedGetInstanceInfoByName(inst_name)
1786

    
1787
  def _UnlockedGetInstanceInfoByName(self, inst_name):
1788
    for inst in self._UnlockedGetAllInstancesInfo().values():
1789
      if inst.name == inst_name:
1790
        return inst
1791
    return None
1792

    
1793
  def _UnlockedGetInstanceName(self, inst_uuid):
1794
    inst_info = self._UnlockedGetInstanceInfo(inst_uuid)
1795
    if inst_info is None:
1796
      raise errors.OpExecError("Unknown instance: %s" % inst_uuid)
1797
    return inst_info.name
1798

    
1799
  @locking.ssynchronized(_config_lock, shared=1)
1800
  def GetInstanceName(self, inst_uuid):
1801
    """Gets the instance name for the passed instance.
1802

1803
    @param inst_uuid: instance UUID to get name for
1804
    @type inst_uuid: string
1805
    @rtype: string
1806
    @return: instance name
1807

1808
    """
1809
    return self._UnlockedGetInstanceName(inst_uuid)
1810

    
1811
  @locking.ssynchronized(_config_lock, shared=1)
1812
  def GetInstanceNames(self, inst_uuids):
1813
    """Gets the instance names for the passed list of nodes.
1814

1815
    @param inst_uuids: list of instance UUIDs to get names for
1816
    @type inst_uuids: list of strings
1817
    @rtype: list of strings
1818
    @return: list of instance names
1819

1820
    """
1821
    return self._UnlockedGetInstanceNames(inst_uuids)
1822

    
1823
  def _UnlockedGetInstanceNames(self, inst_uuids):
1824
    return [self._UnlockedGetInstanceName(uuid) for uuid in inst_uuids]
1825

    
1826
  @locking.ssynchronized(_config_lock)
1827
  def AddNode(self, node, ec_id):
1828
    """Add a node to the configuration.
1829

1830
    @type node: L{objects.Node}
1831
    @param node: a Node instance
1832

1833
    """
1834
    logging.info("Adding node %s to configuration", node.name)
1835

    
1836
    self._EnsureUUID(node, ec_id)
1837

    
1838
    node.serial_no = 1
1839
    node.ctime = node.mtime = time.time()
1840
    self._UnlockedAddNodeToGroup(node.uuid, node.group)
1841
    self._config_data.nodes[node.uuid] = node
1842
    self._config_data.cluster.serial_no += 1
1843
    self._WriteConfig()
1844

    
1845
  @locking.ssynchronized(_config_lock)
1846
  def RemoveNode(self, node_uuid):
1847
    """Remove a node from the configuration.
1848

1849
    """
1850
    logging.info("Removing node %s from configuration", node_uuid)
1851

    
1852
    if node_uuid not in self._config_data.nodes:
1853
      raise errors.ConfigurationError("Unknown node '%s'" % node_uuid)
1854

    
1855
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_uuid])
1856
    del self._config_data.nodes[node_uuid]
1857
    self._config_data.cluster.serial_no += 1
1858
    self._WriteConfig()
1859

    
1860
  def ExpandNodeName(self, short_name):
1861
    """Attempt to expand an incomplete node name into a node UUID.
1862

1863
    """
1864
    # Locking is done in L{ConfigWriter.GetAllNodesInfo}
1865
    all_nodes = self.GetAllNodesInfo().values()
1866
    expanded_name = _MatchNameComponentIgnoreCase(
1867
                      short_name, [node.name for node in all_nodes])
1868

    
1869
    if expanded_name is not None:
1870
      # there has to be exactly one node with that name
1871
      node = (filter(lambda n: n.name == expanded_name, all_nodes)[0])
1872
      return (node.uuid, node.name)
1873
    else:
1874
      return (None, None)
1875

    
1876
  def _UnlockedGetNodeInfo(self, node_uuid):
1877
    """Get the configuration of a node, as stored in the config.
1878

1879
    This function is for internal use, when the config lock is already
1880
    held.
1881

1882
    @param node_uuid: the node UUID
1883

1884
    @rtype: L{objects.Node}
1885
    @return: the node object
1886

1887
    """
1888
    if node_uuid not in self._config_data.nodes:
1889
      return None
1890

    
1891
    return self._config_data.nodes[node_uuid]
1892

    
1893
  @locking.ssynchronized(_config_lock, shared=1)
1894
  def GetNodeInfo(self, node_uuid):
1895
    """Get the configuration of a node, as stored in the config.
1896

1897
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1898

1899
    @param node_uuid: the node UUID
1900

1901
    @rtype: L{objects.Node}
1902
    @return: the node object
1903

1904
    """
1905
    return self._UnlockedGetNodeInfo(node_uuid)
1906

    
1907
  @locking.ssynchronized(_config_lock, shared=1)
1908
  def GetNodeInstances(self, node_uuid):
1909
    """Get the instances of a node, as stored in the config.
1910

1911
    @param node_uuid: the node UUID
1912

1913
    @rtype: (list, list)
1914
    @return: a tuple with two lists: the primary and the secondary instances
1915

1916
    """
1917
    pri = []
1918
    sec = []
1919
    for inst in self._config_data.instances.values():
1920
      if inst.primary_node == node_uuid:
1921
        pri.append(inst.uuid)
1922
      if node_uuid in inst.secondary_nodes:
1923
        sec.append(inst.uuid)
1924
    return (pri, sec)
1925

    
1926
  @locking.ssynchronized(_config_lock, shared=1)
1927
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1928
    """Get the instances of a node group.
1929

1930
    @param uuid: Node group UUID
1931
    @param primary_only: Whether to only consider primary nodes
1932
    @rtype: frozenset
1933
    @return: List of instance UUIDs in node group
1934

1935
    """
1936
    if primary_only:
1937
      nodes_fn = lambda inst: [inst.primary_node]
1938
    else:
1939
      nodes_fn = lambda inst: inst.all_nodes
1940

    
1941
    return frozenset(inst.uuid
1942
                     for inst in self._config_data.instances.values()
1943
                     for node_uuid in nodes_fn(inst)
1944
                     if self._UnlockedGetNodeInfo(node_uuid).group == uuid)
1945

    
1946
  def _UnlockedGetHvparamsString(self, hvname):
1947
    """Return the string representation of the list of hyervisor parameters of
1948
    the given hypervisor.
1949

1950
    @see: C{GetHvparams}
1951

1952
    """
1953
    result = ""
1954
    hvparams = self._config_data.cluster.hvparams[hvname]
1955
    for key in hvparams:
1956
      result += "%s=%s\n" % (key, hvparams[key])
1957
    return result
1958

    
1959
  @locking.ssynchronized(_config_lock, shared=1)
1960
  def GetHvparamsString(self, hvname):
1961
    """Return the hypervisor parameters of the given hypervisor.
1962

1963
    @type hvname: string
1964
    @param hvname: name of a hypervisor
1965
    @rtype: string
1966
    @return: string containing key-value-pairs, one pair on each line;
1967
      format: KEY=VALUE
1968

1969
    """
1970
    return self._UnlockedGetHvparamsString(hvname)
1971

    
1972
  def _UnlockedGetNodeList(self):
1973
    """Return the list of nodes which are in the configuration.
1974

1975
    This function is for internal use, when the config lock is already
1976
    held.
1977

1978
    @rtype: list
1979

1980
    """
1981
    return self._config_data.nodes.keys()
1982

    
1983
  @locking.ssynchronized(_config_lock, shared=1)
1984
  def GetNodeList(self):
1985
    """Return the list of nodes which are in the configuration.
1986

1987
    """
1988
    return self._UnlockedGetNodeList()
1989

    
1990
  def _UnlockedGetOnlineNodeList(self):
1991
    """Return the list of nodes which are online.
1992

1993
    """
1994
    all_nodes = [self._UnlockedGetNodeInfo(node)
1995
                 for node in self._UnlockedGetNodeList()]
1996
    return [node.uuid for node in all_nodes if not node.offline]
1997

    
1998
  @locking.ssynchronized(_config_lock, shared=1)
1999
  def GetOnlineNodeList(self):
2000
    """Return the list of nodes which are online.
2001

2002
    """
2003
    return self._UnlockedGetOnlineNodeList()
2004

    
2005
  @locking.ssynchronized(_config_lock, shared=1)
2006
  def GetVmCapableNodeList(self):
2007
    """Return the list of nodes which are not vm capable.
2008

2009
    """
2010
    all_nodes = [self._UnlockedGetNodeInfo(node)
2011
                 for node in self._UnlockedGetNodeList()]
2012
    return [node.uuid for node in all_nodes if node.vm_capable]
2013

    
2014
  @locking.ssynchronized(_config_lock, shared=1)
2015
  def GetNonVmCapableNodeList(self):
2016
    """Return the list of nodes which are not vm capable.
2017

2018
    """
2019
    all_nodes = [self._UnlockedGetNodeInfo(node)
2020
                 for node in self._UnlockedGetNodeList()]
2021
    return [node.uuid for node in all_nodes if not node.vm_capable]
2022

    
2023
  @locking.ssynchronized(_config_lock, shared=1)
2024
  def GetMultiNodeInfo(self, node_uuids):
2025
    """Get the configuration of multiple nodes.
2026

2027
    @param node_uuids: list of node UUIDs
2028
    @rtype: list
2029
    @return: list of tuples of (node, node_info), where node_info is
2030
        what would GetNodeInfo return for the node, in the original
2031
        order
2032

2033
    """
2034
    return [(uuid, self._UnlockedGetNodeInfo(uuid)) for uuid in node_uuids]
2035

    
2036
  def _UnlockedGetAllNodesInfo(self):
2037
    """Gets configuration of all nodes.
2038

2039
    @note: See L{GetAllNodesInfo}
2040

2041
    """
2042
    return dict([(node_uuid, self._UnlockedGetNodeInfo(node_uuid))
2043
                 for node_uuid in self._UnlockedGetNodeList()])
2044

    
2045
  @locking.ssynchronized(_config_lock, shared=1)
2046
  def GetAllNodesInfo(self):
2047
    """Get the configuration of all nodes.
2048

2049
    @rtype: dict
2050
    @return: dict of (node, node_info), where node_info is what
2051
              would GetNodeInfo return for the node
2052

2053
    """
2054
    return self._UnlockedGetAllNodesInfo()
2055

    
2056
  def _UnlockedGetNodeInfoByName(self, node_name):
2057
    for node in self._UnlockedGetAllNodesInfo().values():
2058
      if node.name == node_name:
2059
        return node
2060
    return None
2061

    
2062
  @locking.ssynchronized(_config_lock, shared=1)
2063
  def GetNodeInfoByName(self, node_name):
2064
    """Get the L{objects.Node} object for a named node.
2065

2066
    @param node_name: name of the node to get information for
2067
    @type node_name: string
2068
    @return: the corresponding L{objects.Node} instance or None if no
2069
          information is available
2070

2071
    """
2072
    return self._UnlockedGetNodeInfoByName(node_name)
2073

    
2074
  @locking.ssynchronized(_config_lock, shared=1)
2075
  def GetNodeGroupInfoByName(self, nodegroup_name):
2076
    """Get the L{objects.NodeGroup} object for a named node group.
2077

2078
    @param nodegroup_name: name of the node group to get information for
2079
    @type nodegroup_name: string
2080
    @return: the corresponding L{objects.NodeGroup} instance or None if no
2081
          information is available
2082

2083
    """
2084
    for nodegroup in self._UnlockedGetAllNodeGroupsInfo().values():
2085
      if nodegroup.name == nodegroup_name:
2086
        return nodegroup
2087
    return None
2088

    
2089
  def _UnlockedGetNodeName(self, node_spec):
2090
    if isinstance(node_spec, objects.Node):
2091
      return node_spec.name
2092
    elif isinstance(node_spec, basestring):
2093
      node_info = self._UnlockedGetNodeInfo(node_spec)
2094
      if node_info is None:
2095
        raise errors.OpExecError("Unknown node: %s" % node_spec)
2096
      return node_info.name
2097
    else:
2098
      raise errors.ProgrammerError("Can't handle node spec '%s'" % node_spec)
2099

    
2100
  @locking.ssynchronized(_config_lock, shared=1)
2101
  def GetNodeName(self, node_spec):
2102
    """Gets the node name for the passed node.
2103

2104
    @param node_spec: node to get names for
2105
    @type node_spec: either node UUID or a L{objects.Node} object
2106
    @rtype: string
2107
    @return: node name
2108

2109
    """
2110
    return self._UnlockedGetNodeName(node_spec)
2111

    
2112
  def _UnlockedGetNodeNames(self, node_specs):
2113
    return [self._UnlockedGetNodeName(node_spec) for node_spec in node_specs]
2114

    
2115
  @locking.ssynchronized(_config_lock, shared=1)
2116
  def GetNodeNames(self, node_specs):
2117
    """Gets the node names for the passed list of nodes.
2118

2119
    @param node_specs: list of nodes to get names for
2120
    @type node_specs: list of either node UUIDs or L{objects.Node} objects
2121
    @rtype: list of strings
2122
    @return: list of node names
2123

2124
    """
2125
    return self._UnlockedGetNodeNames(node_specs)
2126

    
2127
  @locking.ssynchronized(_config_lock, shared=1)
2128
  def GetNodeGroupsFromNodes(self, node_uuids):
2129
    """Returns groups for a list of nodes.
2130

2131
    @type node_uuids: list of string
2132
    @param node_uuids: List of node UUIDs
2133
    @rtype: frozenset
2134

2135
    """
2136
    return frozenset(self._UnlockedGetNodeInfo(uuid).group
2137
                     for uuid in node_uuids)
2138

    
2139
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
2140
    """Get the number of current and maximum desired and possible candidates.
2141

2142
    @type exceptions: list
2143
    @param exceptions: if passed, list of nodes that should be ignored
2144
    @rtype: tuple
2145
    @return: tuple of (current, desired and possible, possible)
2146

2147
    """
2148
    mc_now = mc_should = mc_max = 0
2149
    for node in self._config_data.nodes.values():
2150
      if exceptions and node.uuid in exceptions:
2151
        continue
2152
      if not (node.offline or node.drained) and node.master_capable:
2153
        mc_max += 1
2154
      if node.master_candidate:
2155
        mc_now += 1
2156
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
2157
    return (mc_now, mc_should, mc_max)
2158

    
2159
  @locking.ssynchronized(_config_lock, shared=1)
2160
  def GetMasterCandidateStats(self, exceptions=None):
2161
    """Get the number of current and maximum possible candidates.
2162

2163
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
2164

2165
    @type exceptions: list
2166
    @param exceptions: if passed, list of nodes that should be ignored
2167
    @rtype: tuple
2168
    @return: tuple of (current, max)
2169

2170
    """
2171
    return self._UnlockedGetMasterCandidateStats(exceptions)
2172

    
2173
  @locking.ssynchronized(_config_lock)
2174
  def MaintainCandidatePool(self, exception_node_uuids):
2175
    """Try to grow the candidate pool to the desired size.
2176

2177
    @type exception_node_uuids: list
2178
    @param exception_node_uuids: if passed, list of nodes that should be ignored
2179
    @rtype: list
2180
    @return: list with the adjusted nodes (L{objects.Node} instances)
2181

2182
    """
2183
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(
2184
                          exception_node_uuids)
2185
    mod_list = []
2186
    if mc_now < mc_max:
2187
      node_list = self._config_data.nodes.keys()
2188
      random.shuffle(node_list)
2189
      for uuid in node_list:
2190
        if mc_now >= mc_max:
2191
          break
2192
        node = self._config_data.nodes[uuid]
2193
        if (node.master_candidate or node.offline or node.drained or
2194
            node.uuid in exception_node_uuids or not node.master_capable):
2195
          continue
2196
        mod_list.append(node)
2197
        node.master_candidate = True
2198
        node.serial_no += 1
2199
        mc_now += 1
2200
      if mc_now != mc_max:
2201
        # this should not happen
2202
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
2203
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
2204
      if mod_list:
2205
        self._config_data.cluster.serial_no += 1
2206
        self._WriteConfig()
2207

    
2208
    return mod_list
2209

    
2210
  def _UnlockedAddNodeToGroup(self, node_uuid, nodegroup_uuid):
2211
    """Add a given node to the specified group.
2212

2213
    """
2214
    if nodegroup_uuid not in self._config_data.nodegroups:
2215
      # This can happen if a node group gets deleted between its lookup and
2216
      # when we're adding the first node to it, since we don't keep a lock in
2217
      # the meantime. It's ok though, as we'll fail cleanly if the node group
2218
      # is not found anymore.
2219
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
2220
    if node_uuid not in self._config_data.nodegroups[nodegroup_uuid].members:
2221
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_uuid)
2222

    
2223
  def _UnlockedRemoveNodeFromGroup(self, node):
2224
    """Remove a given node from its group.
2225

2226
    """
2227
    nodegroup = node.group
2228
    if nodegroup not in self._config_data.nodegroups:
2229
      logging.warning("Warning: node '%s' has unknown node group '%s'"
2230
                      " (while being removed from it)", node.uuid, nodegroup)
2231
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
2232
    if node.uuid not in nodegroup_obj.members:
2233
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
2234
                      " (while being removed from it)", node.uuid, nodegroup)
2235
    else:
2236
      nodegroup_obj.members.remove(node.uuid)
2237

    
2238
  @locking.ssynchronized(_config_lock)
2239
  def AssignGroupNodes(self, mods):
2240
    """Changes the group of a number of nodes.
2241

2242
    @type mods: list of tuples; (node name, new group UUID)
2243
    @param mods: Node membership modifications
2244

2245
    """
2246
    groups = self._config_data.nodegroups
2247
    nodes = self._config_data.nodes
2248

    
2249
    resmod = []
2250

    
2251
    # Try to resolve UUIDs first
2252
    for (node_uuid, new_group_uuid) in mods:
2253
      try:
2254
        node = nodes[node_uuid]
2255
      except KeyError:
2256
        raise errors.ConfigurationError("Unable to find node '%s'" % node_uuid)
2257

    
2258
      if node.group == new_group_uuid:
2259
        # Node is being assigned to its current group
2260
        logging.debug("Node '%s' was assigned to its current group (%s)",
2261
                      node_uuid, node.group)
2262
        continue
2263

    
2264
      # Try to find current group of node
2265
      try:
2266
        old_group = groups[node.group]
2267
      except KeyError:
2268
        raise errors.ConfigurationError("Unable to find old group '%s'" %
2269
                                        node.group)
2270

    
2271
      # Try to find new group for node
2272
      try:
2273
        new_group = groups[new_group_uuid]
2274
      except KeyError:
2275
        raise errors.ConfigurationError("Unable to find new group '%s'" %
2276
                                        new_group_uuid)
2277

    
2278
      assert node.uuid in old_group.members, \
2279
        ("Inconsistent configuration: node '%s' not listed in members for its"
2280
         " old group '%s'" % (node.uuid, old_group.uuid))
2281
      assert node.uuid not in new_group.members, \
2282
        ("Inconsistent configuration: node '%s' already listed in members for"
2283
         " its new group '%s'" % (node.uuid, new_group.uuid))
2284

    
2285
      resmod.append((node, old_group, new_group))
2286

    
2287
    # Apply changes
2288
    for (node, old_group, new_group) in resmod:
2289
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
2290
        "Assigning to current group is not possible"
2291

    
2292
      node.group = new_group.uuid
2293

    
2294
      # Update members of involved groups
2295
      if node.uuid in old_group.members:
2296
        old_group.members.remove(node.uuid)
2297
      if node.uuid not in new_group.members:
2298
        new_group.members.append(node.uuid)
2299

    
2300
    # Update timestamps and serials (only once per node/group object)
2301
    now = time.time()
2302
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
2303
      obj.serial_no += 1
2304
      obj.mtime = now
2305

    
2306
    # Force ssconf update
2307
    self._config_data.cluster.serial_no += 1
2308

    
2309
    self._WriteConfig()
2310

    
2311
  def _BumpSerialNo(self):
2312
    """Bump up the serial number of the config.
2313

2314
    """
2315
    self._config_data.serial_no += 1
2316
    self._config_data.mtime = time.time()
2317

    
2318
  def _AllUUIDObjects(self):
2319
    """Returns all objects with uuid attributes.
2320

2321
    """
2322
    return (self._config_data.instances.values() +
2323
            self._config_data.nodes.values() +
2324
            self._config_data.nodegroups.values() +
2325
            self._config_data.networks.values() +
2326
            self._AllDisks() +
2327
            self._AllNICs() +
2328
            [self._config_data.cluster])
2329

    
2330
  def _OpenConfig(self, accept_foreign):
2331
    """Read the config data from disk.
2332

2333
    """
2334
    raw_data = utils.ReadFile(self._cfg_file)
2335

    
2336
    try:
2337
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
2338
    except Exception, err:
2339
      raise errors.ConfigurationError(err)
2340

    
2341
    # Make sure the configuration has the right version
2342
    _ValidateConfig(data)
2343

    
2344
    if (not hasattr(data, "cluster") or
2345
        not hasattr(data.cluster, "rsahostkeypub")):
2346
      raise errors.ConfigurationError("Incomplete configuration"
2347
                                      " (missing cluster.rsahostkeypub)")
2348

    
2349
    if not data.cluster.master_node in data.nodes:
2350
      msg = ("The configuration denotes node %s as master, but does not"
2351
             " contain information about this node" %
2352
             data.cluster.master_node)
2353
      raise errors.ConfigurationError(msg)
2354

    
2355
    master_info = data.nodes[data.cluster.master_node]
2356
    if master_info.name != self._my_hostname and not accept_foreign:
2357
      msg = ("The configuration denotes node %s as master, while my"
2358
             " hostname is %s; opening a foreign configuration is only"
2359
             " possible in accept_foreign mode" %
2360
             (master_info.name, self._my_hostname))
2361
      raise errors.ConfigurationError(msg)
2362

    
2363
    self._config_data = data
2364
    # reset the last serial as -1 so that the next write will cause
2365
    # ssconf update
2366
    self._last_cluster_serial = -1
2367

    
2368
    # Upgrade configuration if needed
2369
    self._UpgradeConfig()
2370

    
2371
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2372

    
2373
  def _UpgradeConfig(self):
2374
    """Run any upgrade steps.
2375

2376
    This method performs both in-object upgrades and also update some data
2377
    elements that need uniqueness across the whole configuration or interact
2378
    with other objects.
2379

2380
    @warning: this function will call L{_WriteConfig()}, but also
2381
        L{DropECReservations} so it needs to be called only from a
2382
        "safe" place (the constructor). If one wanted to call it with
2383
        the lock held, a DropECReservationUnlocked would need to be
2384
        created first, to avoid causing deadlock.
2385

2386
    """
2387
    # Keep a copy of the persistent part of _config_data to check for changes
2388
    # Serialization doesn't guarantee order in dictionaries
2389
    oldconf = copy.deepcopy(self._config_data.ToDict())
2390

    
2391
    # In-object upgrades
2392
    self._config_data.UpgradeConfig()
2393

    
2394
    for item in self._AllUUIDObjects():
2395
      if item.uuid is None:
2396
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
2397
    if not self._config_data.nodegroups:
2398
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
2399
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
2400
                                            members=[])
2401
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
2402
    for node in self._config_data.nodes.values():
2403
      if not node.group:
2404
        node.group = self.LookupNodeGroup(None)
2405
      # This is technically *not* an upgrade, but needs to be done both when
2406
      # nodegroups are being added, and upon normally loading the config,
2407
      # because the members list of a node group is discarded upon
2408
      # serializing/deserializing the object.
2409
      self._UnlockedAddNodeToGroup(node.uuid, node.group)
2410

    
2411
    modified = (oldconf != self._config_data.ToDict())
2412
    if modified:
2413
      self._WriteConfig()
2414
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
2415
      # only called at config init time, without the lock held
2416
      self.DropECReservations(_UPGRADE_CONFIG_JID)
2417
    else:
2418
      config_errors = self._UnlockedVerifyConfig()
2419
      if config_errors:
2420
        errmsg = ("Loaded configuration data is not consistent: %s" %
2421
                  (utils.CommaJoin(config_errors)))
2422
        logging.critical(errmsg)
2423

    
2424
  def _DistributeConfig(self, feedback_fn):
2425
    """Distribute the configuration to the other nodes.
2426

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

2430
    """
2431
    if self._offline:
2432
      return True
2433

    
2434
    bad = False
2435

    
2436
    node_list = []
2437
    addr_list = []
2438
    myhostname = self._my_hostname
2439
    # we can skip checking whether _UnlockedGetNodeInfo returns None
2440
    # since the node list comes from _UnlocketGetNodeList, and we are
2441
    # called with the lock held, so no modifications should take place
2442
    # in between
2443
    for node_uuid in self._UnlockedGetNodeList():
2444
      node_info = self._UnlockedGetNodeInfo(node_uuid)
2445
      if node_info.name == myhostname or not node_info.master_candidate:
2446
        continue
2447
      node_list.append(node_info.name)
2448
      addr_list.append(node_info.primary_ip)
2449

    
2450
    # TODO: Use dedicated resolver talking to config writer for name resolution
2451
    result = \
2452
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2453
    for to_node, to_result in result.items():
2454
      msg = to_result.fail_msg
2455
      if msg:
2456
        msg = ("Copy of file %s to node %s failed: %s" %
2457
               (self._cfg_file, to_node, msg))
2458
        logging.error(msg)
2459

    
2460
        if feedback_fn:
2461
          feedback_fn(msg)
2462

    
2463
        bad = True
2464

    
2465
    return not bad
2466

    
2467
  def _WriteConfig(self, destination=None, feedback_fn=None):
2468
    """Write the configuration data to persistent storage.
2469

2470
    """
2471
    assert feedback_fn is None or callable(feedback_fn)
2472

    
2473
    # Warn on config errors, but don't abort the save - the
2474
    # configuration has already been modified, and we can't revert;
2475
    # the best we can do is to warn the user and save as is, leaving
2476
    # recovery to the user
2477
    config_errors = self._UnlockedVerifyConfig()
2478
    if config_errors:
2479
      errmsg = ("Configuration data is not consistent: %s" %
2480
                (utils.CommaJoin(config_errors)))
2481
      logging.critical(errmsg)
2482
      if feedback_fn:
2483
        feedback_fn(errmsg)
2484

    
2485
    if destination is None:
2486
      destination = self._cfg_file
2487
    self._BumpSerialNo()
2488
    txt = serializer.Dump(self._config_data.ToDict())
2489

    
2490
    getents = self._getents()
2491
    try:
2492
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2493
                               close=False, gid=getents.confd_gid, mode=0640)
2494
    except errors.LockError:
2495
      raise errors.ConfigurationError("The configuration file has been"
2496
                                      " modified since the last write, cannot"
2497
                                      " update")
2498
    try:
2499
      self._cfg_id = utils.GetFileID(fd=fd)
2500
    finally:
2501
      os.close(fd)
2502

    
2503
    self.write_count += 1
2504

    
2505
    # and redistribute the config file to master candidates
2506
    self._DistributeConfig(feedback_fn)
2507

    
2508
    # Write ssconf files on all nodes (including locally)
2509
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2510
      if not self._offline:
2511
        result = self._GetRpc(None).call_write_ssconf_files(
2512
          self._UnlockedGetNodeNames(self._UnlockedGetOnlineNodeList()),
2513
          self._UnlockedGetSsconfValues())
2514

    
2515
        for nname, nresu in result.items():
2516
          msg = nresu.fail_msg
2517
          if msg:
2518
            errmsg = ("Error while uploading ssconf files to"
2519
                      " node %s: %s" % (nname, msg))
2520
            logging.warning(errmsg)
2521

    
2522
            if feedback_fn:
2523
              feedback_fn(errmsg)
2524

    
2525
      self._last_cluster_serial = self._config_data.cluster.serial_no
2526

    
2527
  def _GetAllHvparamsStrings(self, hypervisors):
2528
    """Get the hvparams of all given hypervisors from the config.
2529

2530
    @type hypervisors: list of string
2531
    @param hypervisors: list of hypervisor names
2532
    @rtype: dict of strings
2533
    @returns: dictionary mapping the hypervisor name to a string representation
2534
      of the hypervisor's hvparams
2535

2536
    """
2537
    hvparams = {}
2538
    for hv in hypervisors:
2539
      hvparams[hv] = self._UnlockedGetHvparamsString(hv)
2540
    return hvparams
2541

    
2542
  @staticmethod
2543
  def _ExtendByAllHvparamsStrings(ssconf_values, all_hvparams):
2544
    """Extends the ssconf_values dictionary by hvparams.
2545

2546
    @type ssconf_values: dict of strings
2547
    @param ssconf_values: dictionary mapping ssconf_keys to strings
2548
      representing the content of ssconf files
2549
    @type all_hvparams: dict of strings
2550
    @param all_hvparams: dictionary mapping hypervisor names to a string
2551
      representation of their hvparams
2552
    @rtype: same as ssconf_values
2553
    @returns: the ssconf_values dictionary extended by hvparams
2554

2555
    """
2556
    for hv in all_hvparams:
2557
      ssconf_key = constants.SS_HVPARAMS_PREF + hv
2558
      ssconf_values[ssconf_key] = all_hvparams[hv]
2559
    return ssconf_values
2560

    
2561
  def _UnlockedGetSsconfValues(self):
2562
    """Return the values needed by ssconf.
2563

2564
    @rtype: dict
2565
    @return: a dictionary with keys the ssconf names and values their
2566
        associated value
2567

2568
    """
2569
    fn = "\n".join
2570
    instance_names = utils.NiceSort(
2571
                       [inst.name for inst in
2572
                        self._UnlockedGetAllInstancesInfo().values()])
2573
    node_infos = self._UnlockedGetAllNodesInfo().values()
2574
    node_names = [node.name for node in node_infos]
2575
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2576
                    for ninfo in node_infos]
2577
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2578
                    for ninfo in node_infos]
2579

    
2580
    instance_data = fn(instance_names)
2581
    off_data = fn(node.name for node in node_infos if node.offline)
2582
    on_data = fn(node.name for node in node_infos if not node.offline)
2583
    mc_data = fn(node.name for node in node_infos if node.master_candidate)
2584
    mc_ips_data = fn(node.primary_ip for node in node_infos
2585
                     if node.master_candidate)
2586
    node_data = fn(node_names)
2587
    node_pri_ips_data = fn(node_pri_ips)
2588
    node_snd_ips_data = fn(node_snd_ips)
2589

    
2590
    cluster = self._config_data.cluster
2591
    cluster_tags = fn(cluster.GetTags())
2592

    
2593
    hypervisor_list = fn(cluster.enabled_hypervisors)
2594
    all_hvparams = self._GetAllHvparamsStrings(constants.HYPER_TYPES)
2595

    
2596
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2597

    
2598
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2599
                  self._config_data.nodegroups.values()]
2600
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2601
    networks = ["%s %s" % (net.uuid, net.name) for net in
2602
                self._config_data.networks.values()]
2603
    networks_data = fn(utils.NiceSort(networks))
2604

    
2605
    ssconf_values = {
2606
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
2607
      constants.SS_CLUSTER_TAGS: cluster_tags,
2608
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2609
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2610
      constants.SS_GLUSTER_STORAGE_DIR: cluster.gluster_storage_dir,
2611
      constants.SS_MASTER_CANDIDATES: mc_data,
2612
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2613
      constants.SS_MASTER_IP: cluster.master_ip,
2614
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
2615
      constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2616
      constants.SS_MASTER_NODE: self._UnlockedGetNodeName(cluster.master_node),
2617
      constants.SS_NODE_LIST: node_data,
2618
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2619
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2620
      constants.SS_OFFLINE_NODES: off_data,
2621
      constants.SS_ONLINE_NODES: on_data,
2622
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2623
      constants.SS_INSTANCE_LIST: instance_data,
2624
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2625
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
2626
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2627
      constants.SS_UID_POOL: uid_pool,
2628
      constants.SS_NODEGROUPS: nodegroups_data,
2629
      constants.SS_NETWORKS: networks_data,
2630
      }
2631
    ssconf_values = self._ExtendByAllHvparamsStrings(ssconf_values,
2632
                                                     all_hvparams)
2633
    bad_values = [(k, v) for k, v in ssconf_values.items()
2634
                  if not isinstance(v, (str, basestring))]
2635
    if bad_values:
2636
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2637
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2638
                                      " values: %s" % err)
2639
    return ssconf_values
2640

    
2641
  @locking.ssynchronized(_config_lock, shared=1)
2642
  def GetSsconfValues(self):
2643
    """Wrapper using lock around _UnlockedGetSsconf().
2644

2645
    """
2646
    return self._UnlockedGetSsconfValues()
2647

    
2648
  @locking.ssynchronized(_config_lock, shared=1)
2649
  def GetVGName(self):
2650
    """Return the volume group name.
2651

2652
    """
2653
    return self._config_data.cluster.volume_group_name
2654

    
2655
  @locking.ssynchronized(_config_lock)
2656
  def SetVGName(self, vg_name):
2657
    """Set the volume group name.
2658

2659
    """
2660
    self._config_data.cluster.volume_group_name = vg_name
2661
    self._config_data.cluster.serial_no += 1
2662
    self._WriteConfig()
2663

    
2664
  @locking.ssynchronized(_config_lock, shared=1)
2665
  def GetDRBDHelper(self):
2666
    """Return DRBD usermode helper.
2667

2668
    """
2669
    return self._config_data.cluster.drbd_usermode_helper
2670

    
2671
  @locking.ssynchronized(_config_lock)
2672
  def SetDRBDHelper(self, drbd_helper):
2673
    """Set DRBD usermode helper.
2674

2675
    """
2676
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2677
    self._config_data.cluster.serial_no += 1
2678
    self._WriteConfig()
2679

    
2680
  @locking.ssynchronized(_config_lock, shared=1)
2681
  def GetMACPrefix(self):
2682
    """Return the mac prefix.
2683

2684
    """
2685
    return self._config_data.cluster.mac_prefix
2686

    
2687
  @locking.ssynchronized(_config_lock, shared=1)
2688
  def GetClusterInfo(self):
2689
    """Returns information about the cluster
2690

2691
    @rtype: L{objects.Cluster}
2692
    @return: the cluster object
2693

2694
    """
2695
    return self._config_data.cluster
2696

    
2697
  @locking.ssynchronized(_config_lock, shared=1)
2698
  def HasAnyDiskOfType(self, dev_type):
2699
    """Check if in there is at disk of the given type in the configuration.
2700

2701
    """
2702
    return self._config_data.HasAnyDiskOfType(dev_type)
2703

    
2704
  @locking.ssynchronized(_config_lock)
2705
  def Update(self, target, feedback_fn, ec_id=None):
2706
    """Notify function to be called after updates.
2707

2708
    This function must be called when an object (as returned by
2709
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2710
    caller wants the modifications saved to the backing store. Note
2711
    that all modified objects will be saved, but the target argument
2712
    is the one the caller wants to ensure that it's saved.
2713

2714
    @param target: an instance of either L{objects.Cluster},
2715
        L{objects.Node} or L{objects.Instance} which is existing in
2716
        the cluster
2717
    @param feedback_fn: Callable feedback function
2718

2719
    """
2720
    if self._config_data is None:
2721
      raise errors.ProgrammerError("Configuration file not read,"
2722
                                   " cannot save.")
2723
    update_serial = False
2724
    if isinstance(target, objects.Cluster):
2725
      test = target == self._config_data.cluster
2726
    elif isinstance(target, objects.Node):
2727
      test = target in self._config_data.nodes.values()
2728
      update_serial = True
2729
    elif isinstance(target, objects.Instance):
2730
      test = target in self._config_data.instances.values()
2731
    elif isinstance(target, objects.NodeGroup):
2732
      test = target in self._config_data.nodegroups.values()
2733
    elif isinstance(target, objects.Network):
2734
      test = target in self._config_data.networks.values()
2735
    else:
2736
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2737
                                   " ConfigWriter.Update" % type(target))
2738
    if not test:
2739
      raise errors.ConfigurationError("Configuration updated since object"
2740
                                      " has been read or unknown object")
2741
    target.serial_no += 1
2742
    target.mtime = now = time.time()
2743

    
2744
    if update_serial:
2745
      # for node updates, we need to increase the cluster serial too
2746
      self._config_data.cluster.serial_no += 1
2747
      self._config_data.cluster.mtime = now
2748

    
2749
    if isinstance(target, objects.Instance):
2750
      self._UnlockedReleaseDRBDMinors(target.uuid)
2751

    
2752
    if ec_id is not None:
2753
      # Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
2754
      self._UnlockedCommitTemporaryIps(ec_id)
2755

    
2756
    self._WriteConfig(feedback_fn=feedback_fn)
2757

    
2758
  @locking.ssynchronized(_config_lock)
2759
  def DropECReservations(self, ec_id):
2760
    """Drop per-execution-context reservations
2761

2762
    """
2763
    for rm in self._all_rms:
2764
      rm.DropECReservations(ec_id)
2765

    
2766
  @locking.ssynchronized(_config_lock, shared=1)
2767
  def GetAllNetworksInfo(self):
2768
    """Get configuration info of all the networks.
2769

2770
    """
2771
    return dict(self._config_data.networks)
2772

    
2773
  def _UnlockedGetNetworkList(self):
2774
    """Get the list of networks.
2775

2776
    This function is for internal use, when the config lock is already held.
2777

2778
    """
2779
    return self._config_data.networks.keys()
2780

    
2781
  @locking.ssynchronized(_config_lock, shared=1)
2782
  def GetNetworkList(self):
2783
    """Get the list of networks.
2784

2785
    @return: array of networks, ex. ["main", "vlan100", "200]
2786

2787
    """
2788
    return self._UnlockedGetNetworkList()
2789

    
2790
  @locking.ssynchronized(_config_lock, shared=1)
2791
  def GetNetworkNames(self):
2792
    """Get a list of network names
2793

2794
    """
2795
    names = [net.name
2796
             for net in self._config_data.networks.values()]
2797
    return names
2798

    
2799
  def _UnlockedGetNetwork(self, uuid):
2800
    """Returns information about a network.
2801

2802
    This function is for internal use, when the config lock is already held.
2803

2804
    """
2805
    if uuid not in self._config_data.networks:
2806
      return None
2807

    
2808
    return self._config_data.networks[uuid]
2809

    
2810
  @locking.ssynchronized(_config_lock, shared=1)
2811
  def GetNetwork(self, uuid):
2812
    """Returns information about a network.
2813

2814
    It takes the information from the configuration file.
2815

2816
    @param uuid: UUID of the network
2817

2818
    @rtype: L{objects.Network}
2819
    @return: the network object
2820

2821
    """
2822
    return self._UnlockedGetNetwork(uuid)
2823

    
2824
  @locking.ssynchronized(_config_lock)
2825
  def AddNetwork(self, net, ec_id, check_uuid=True):
2826
    """Add a network to the configuration.
2827

2828
    @type net: L{objects.Network}
2829
    @param net: the Network object to add
2830
    @type ec_id: string
2831
    @param ec_id: unique id for the job to use when creating a missing UUID
2832

2833
    """
2834
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2835
    self._WriteConfig()
2836

    
2837
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2838
    """Add a network to the configuration.
2839

2840
    """
2841
    logging.info("Adding network %s to configuration", net.name)
2842

    
2843
    if check_uuid:
2844
      self._EnsureUUID(net, ec_id)
2845

    
2846
    net.serial_no = 1
2847
    net.ctime = net.mtime = time.time()
2848
    self._config_data.networks[net.uuid] = net
2849
    self._config_data.cluster.serial_no += 1
2850

    
2851
  def _UnlockedLookupNetwork(self, target):
2852
    """Lookup a network's UUID.
2853

2854
    @type target: string
2855
    @param target: network name or UUID
2856
    @rtype: string
2857
    @return: network UUID
2858
    @raises errors.OpPrereqError: when the target network cannot be found
2859

2860
    """
2861
    if target is None:
2862
      return None
2863
    if target in self._config_data.networks:
2864
      return target
2865
    for net in self._config_data.networks.values():
2866
      if net.name == target:
2867
        return net.uuid
2868
    raise errors.OpPrereqError("Network '%s' not found" % target,
2869
                               errors.ECODE_NOENT)
2870

    
2871
  @locking.ssynchronized(_config_lock, shared=1)
2872
  def LookupNetwork(self, target):
2873
    """Lookup a network's UUID.
2874

2875
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2876

2877
    @type target: string
2878
    @param target: network name or UUID
2879
    @rtype: string
2880
    @return: network UUID
2881

2882
    """
2883
    return self._UnlockedLookupNetwork(target)
2884

    
2885
  @locking.ssynchronized(_config_lock)
2886
  def RemoveNetwork(self, network_uuid):
2887
    """Remove a network from the configuration.
2888

2889
    @type network_uuid: string
2890
    @param network_uuid: the UUID of the network to remove
2891

2892
    """
2893
    logging.info("Removing network %s from configuration", network_uuid)
2894

    
2895
    if network_uuid not in self._config_data.networks:
2896
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2897

    
2898
    del self._config_data.networks[network_uuid]
2899
    self._config_data.cluster.serial_no += 1
2900
    self._WriteConfig()
2901

    
2902
  def _UnlockedGetGroupNetParams(self, net_uuid, node_uuid):
2903
    """Get the netparams (mode, link) of a network.
2904

2905
    Get a network's netparams for a given node.
2906

2907
    @type net_uuid: string
2908
    @param net_uuid: network uuid
2909
    @type node_uuid: string
2910
    @param node_uuid: node UUID
2911
    @rtype: dict or None
2912
    @return: netparams
2913

2914
    """
2915
    node_info = self._UnlockedGetNodeInfo(node_uuid)
2916
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2917
    netparams = nodegroup_info.networks.get(net_uuid, None)
2918

    
2919
    return netparams
2920

    
2921
  @locking.ssynchronized(_config_lock, shared=1)
2922
  def GetGroupNetParams(self, net_uuid, node_uuid):
2923
    """Locking wrapper of _UnlockedGetGroupNetParams()
2924

2925
    """
2926
    return self._UnlockedGetGroupNetParams(net_uuid, node_uuid)
2927

    
2928
  @locking.ssynchronized(_config_lock, shared=1)
2929
  def CheckIPInNodeGroup(self, ip, node_uuid):
2930
    """Check IP uniqueness in nodegroup.
2931

2932
    Check networks that are connected in the node's node group
2933
    if ip is contained in any of them. Used when creating/adding
2934
    a NIC to ensure uniqueness among nodegroups.
2935

2936
    @type ip: string
2937
    @param ip: ip address
2938
    @type node_uuid: string
2939
    @param node_uuid: node UUID
2940
    @rtype: (string, dict) or (None, None)
2941
    @return: (network name, netparams)
2942

2943
    """
2944
    if ip is None:
2945
      return (None, None)
2946
    node_info = self._UnlockedGetNodeInfo(node_uuid)
2947
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2948
    for net_uuid in nodegroup_info.networks.keys():
2949
      net_info = self._UnlockedGetNetwork(net_uuid)
2950
      pool = network.AddressPool(net_info)
2951
      if pool.Contains(ip):
2952
        return (net_info.name, nodegroup_info.networks[net_uuid])
2953

    
2954
    return (None, None)