Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ a9f33339

History | View | Annotate | Download (96.3 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
    if constants.DT_RBD in cluster.diskparams:
682
      access = cluster.diskparams[constants.DT_RBD][constants.RBD_ACCESS]
683
      if access not in constants.DISK_VALID_ACCESS_MODES:
684
        result.append(
685
          "Invalid value of '%s:%s': '%s' (expected one of %s)" % (
686
            constants.DT_RBD, constants.RBD_ACCESS, access,
687
            utils.CommaJoin(constants.DISK_VALID_ACCESS_MODES)
688
          )
689
        )
690

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

    
717
      # disk template checks
718
      if not instance.disk_template in data.cluster.enabled_disk_templates:
719
        result.append("instance '%s' uses the disabled disk template '%s'." %
720
                      (instance.name, instance.disk_template))
721

    
722
      # parameter checks
723
      if instance.beparams:
724
        _helper("instance %s" % instance.name, "beparams",
725
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
726

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

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

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

    
753
        result.append("Instance '%s' has wrongly named disks: %s" %
754
                      (instance.name, tmp))
755

    
756
    # cluster-wide pool of free ports
757
    for free_port in cluster.tcpudp_port_pool:
758
      if free_port not in ports:
759
        ports[free_port] = []
760
      ports[free_port].append(("cluster", "port marked as free"))
761

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

    
771
    # highest used tcp port check
772
    if keys:
773
      if keys[-1] > cluster.highest_used_port:
774
        result.append("Highest used port mismatch, saved %s, computed %s" %
775
                      (cluster.highest_used_port, keys[-1]))
776

    
777
    if not data.nodes[cluster.master_node].master_candidate:
778
      result.append("Master node is not a master candidate")
779

    
780
    # master candidate checks
781
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
782
    if mc_now < mc_max:
783
      result.append("Not enough master candidates: actual %d, target %d" %
784
                    (mc_now, mc_max))
785

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

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

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

    
836
    # IP checks
837
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
838
    ips = {}
839

    
840
    def _AddIpAddress(ip, name):
841
      ips.setdefault(ip, []).append(name)
842

    
843
    _AddIpAddress(cluster.master_ip, "cluster_ip")
844

    
845
    for node in data.nodes.values():
846
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
847
      if node.secondary_ip != node.primary_ip:
848
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
849

    
850
    for instance in data.instances.values():
851
      for idx, nic in enumerate(instance.nics):
852
        if nic.ip is None:
853
          continue
854

    
855
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
856
        nic_mode = nicparams[constants.NIC_MODE]
857
        nic_link = nicparams[constants.NIC_LINK]
858

    
859
        if nic_mode == constants.NIC_MODE_BRIDGED:
860
          link = "bridge:%s" % nic_link
861
        elif nic_mode == constants.NIC_MODE_ROUTED:
862
          link = "route:%s" % nic_link
863
        else:
864
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
865

    
866
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
867
                      "instance:%s/nic:%d" % (instance.name, idx))
868

    
869
    for ip, owners in ips.items():
870
      if len(owners) > 1:
871
        result.append("IP address %s is used by multiple owners: %s" %
872
                      (ip, utils.CommaJoin(owners)))
873

    
874
    return result
875

    
876
  @locking.ssynchronized(_config_lock, shared=1)
877
  def VerifyConfig(self):
878
    """Verify function.
879

880
    This is just a wrapper over L{_UnlockedVerifyConfig}.
881

882
    @rtype: list
883
    @return: a list of error messages; a non-empty list signifies
884
        configuration errors
885

886
    """
887
    return self._UnlockedVerifyConfig()
888

    
889
  @locking.ssynchronized(_config_lock)
890
  def AddTcpUdpPort(self, port):
891
    """Adds a new port to the available port pool.
892

893
    @warning: this method does not "flush" the configuration (via
894
        L{_WriteConfig}); callers should do that themselves once the
895
        configuration is stable
896

897
    """
898
    if not isinstance(port, int):
899
      raise errors.ProgrammerError("Invalid type passed for port")
900

    
901
    self._config_data.cluster.tcpudp_port_pool.add(port)
902

    
903
  @locking.ssynchronized(_config_lock, shared=1)
904
  def GetPortList(self):
905
    """Returns a copy of the current port list.
906

907
    """
908
    return self._config_data.cluster.tcpudp_port_pool.copy()
909

    
910
  @locking.ssynchronized(_config_lock)
911
  def AllocatePort(self):
912
    """Allocate a port.
913

914
    The port will be taken from the available port pool or from the
915
    default port range (and in this case we increase
916
    highest_used_port).
917

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

    
930
    self._WriteConfig()
931
    return port
932

    
933
  def _UnlockedComputeDRBDMap(self):
934
    """Compute the used DRBD minor/nodes.
935

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

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

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

    
977
  @locking.ssynchronized(_config_lock)
978
  def ComputeDRBDMap(self):
979
    """Compute the used DRBD minor/nodes.
980

981
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
982

983
    @return: dictionary of node_uuid: dict of minor: instance_uuid;
984
        the returned dict will have all the nodes in it (even if with
985
        an empty list).
986

987
    """
988
    d_map, duplicates = self._UnlockedComputeDRBDMap()
989
    if duplicates:
990
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
991
                                      str(duplicates))
992
    return d_map
993

    
994
  @locking.ssynchronized(_config_lock)
995
  def AllocateDRBDMinor(self, node_uuids, inst_uuid):
996
    """Allocate a drbd minor.
997

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

1003
    @type inst_uuid: string
1004
    @param inst_uuid: the instance for which we allocate minors
1005

1006
    """
1007
    assert isinstance(inst_uuid, basestring), \
1008
           "Invalid argument '%s' passed to AllocateDRBDMinor" % inst_uuid
1009

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

    
1050
  def _UnlockedReleaseDRBDMinors(self, inst_uuid):
1051
    """Release temporary drbd minors allocated for a given instance.
1052

1053
    @type inst_uuid: string
1054
    @param inst_uuid: the instance for which temporary minors should be
1055
                      released
1056

1057
    """
1058
    assert isinstance(inst_uuid, basestring), \
1059
           "Invalid argument passed to ReleaseDRBDMinors"
1060
    for key, uuid in self._temporary_drbds.items():
1061
      if uuid == inst_uuid:
1062
        del self._temporary_drbds[key]
1063

    
1064
  @locking.ssynchronized(_config_lock)
1065
  def ReleaseDRBDMinors(self, inst_uuid):
1066
    """Release temporary drbd minors allocated for a given instance.
1067

1068
    This should be called on the error paths, on the success paths
1069
    it's automatically called by the ConfigWriter add and update
1070
    functions.
1071

1072
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1073

1074
    @type inst_uuid: string
1075
    @param inst_uuid: the instance for which temporary minors should be
1076
                      released
1077

1078
    """
1079
    self._UnlockedReleaseDRBDMinors(inst_uuid)
1080

    
1081
  @locking.ssynchronized(_config_lock, shared=1)
1082
  def GetConfigVersion(self):
1083
    """Get the configuration version.
1084

1085
    @return: Config version
1086

1087
    """
1088
    return self._config_data.version
1089

    
1090
  @locking.ssynchronized(_config_lock, shared=1)
1091
  def GetClusterName(self):
1092
    """Get cluster name.
1093

1094
    @return: Cluster name
1095

1096
    """
1097
    return self._config_data.cluster.cluster_name
1098

    
1099
  @locking.ssynchronized(_config_lock, shared=1)
1100
  def GetMasterNode(self):
1101
    """Get the UUID of the master node for this cluster.
1102

1103
    @return: Master node UUID
1104

1105
    """
1106
    return self._config_data.cluster.master_node
1107

    
1108
  @locking.ssynchronized(_config_lock, shared=1)
1109
  def GetMasterNodeName(self):
1110
    """Get the hostname of the master node for this cluster.
1111

1112
    @return: Master node hostname
1113

1114
    """
1115
    return self._UnlockedGetNodeName(self._config_data.cluster.master_node)
1116

    
1117
  @locking.ssynchronized(_config_lock, shared=1)
1118
  def GetMasterNodeInfo(self):
1119
    """Get the master node information for this cluster.
1120

1121
    @rtype: objects.Node
1122
    @return: Master node L{objects.Node} object
1123

1124
    """
1125
    return self._UnlockedGetNodeInfo(self._config_data.cluster.master_node)
1126

    
1127
  @locking.ssynchronized(_config_lock, shared=1)
1128
  def GetMasterIP(self):
1129
    """Get the IP of the master node for this cluster.
1130

1131
    @return: Master IP
1132

1133
    """
1134
    return self._config_data.cluster.master_ip
1135

    
1136
  @locking.ssynchronized(_config_lock, shared=1)
1137
  def GetMasterNetdev(self):
1138
    """Get the master network device for this cluster.
1139

1140
    """
1141
    return self._config_data.cluster.master_netdev
1142

    
1143
  @locking.ssynchronized(_config_lock, shared=1)
1144
  def GetMasterNetmask(self):
1145
    """Get the netmask of the master node for this cluster.
1146

1147
    """
1148
    return self._config_data.cluster.master_netmask
1149

    
1150
  @locking.ssynchronized(_config_lock, shared=1)
1151
  def GetUseExternalMipScript(self):
1152
    """Get flag representing whether to use the external master IP setup script.
1153

1154
    """
1155
    return self._config_data.cluster.use_external_mip_script
1156

    
1157
  @locking.ssynchronized(_config_lock, shared=1)
1158
  def GetFileStorageDir(self):
1159
    """Get the file storage dir for this cluster.
1160

1161
    """
1162
    return self._config_data.cluster.file_storage_dir
1163

    
1164
  @locking.ssynchronized(_config_lock, shared=1)
1165
  def GetSharedFileStorageDir(self):
1166
    """Get the shared file storage dir for this cluster.
1167

1168
    """
1169
    return self._config_data.cluster.shared_file_storage_dir
1170

    
1171
  @locking.ssynchronized(_config_lock, shared=1)
1172
  def GetHypervisorType(self):
1173
    """Get the hypervisor type for this cluster.
1174

1175
    """
1176
    return self._config_data.cluster.enabled_hypervisors[0]
1177

    
1178
  @locking.ssynchronized(_config_lock, shared=1)
1179
  def GetRsaHostKey(self):
1180
    """Return the rsa hostkey from the config.
1181

1182
    @rtype: string
1183
    @return: the rsa hostkey
1184

1185
    """
1186
    return self._config_data.cluster.rsahostkeypub
1187

    
1188
  @locking.ssynchronized(_config_lock, shared=1)
1189
  def GetDsaHostKey(self):
1190
    """Return the dsa hostkey from the config.
1191

1192
    @rtype: string
1193
    @return: the dsa hostkey
1194

1195
    """
1196
    return self._config_data.cluster.dsahostkeypub
1197

    
1198
  @locking.ssynchronized(_config_lock, shared=1)
1199
  def GetDefaultIAllocator(self):
1200
    """Get the default instance allocator for this cluster.
1201

1202
    """
1203
    return self._config_data.cluster.default_iallocator
1204

    
1205
  @locking.ssynchronized(_config_lock, shared=1)
1206
  def GetPrimaryIPFamily(self):
1207
    """Get cluster primary ip family.
1208

1209
    @return: primary ip family
1210

1211
    """
1212
    return self._config_data.cluster.primary_ip_family
1213

    
1214
  @locking.ssynchronized(_config_lock, shared=1)
1215
  def GetMasterNetworkParameters(self):
1216
    """Get network parameters of the master node.
1217

1218
    @rtype: L{object.MasterNetworkParameters}
1219
    @return: network parameters of the master node
1220

1221
    """
1222
    cluster = self._config_data.cluster
1223
    result = objects.MasterNetworkParameters(
1224
      uuid=cluster.master_node, ip=cluster.master_ip,
1225
      netmask=cluster.master_netmask, netdev=cluster.master_netdev,
1226
      ip_family=cluster.primary_ip_family)
1227

    
1228
    return result
1229

    
1230
  @locking.ssynchronized(_config_lock)
1231
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1232
    """Add a node group to the configuration.
1233

1234
    This method calls group.UpgradeConfig() to fill any missing attributes
1235
    according to their default values.
1236

1237
    @type group: L{objects.NodeGroup}
1238
    @param group: the NodeGroup object to add
1239
    @type ec_id: string
1240
    @param ec_id: unique id for the job to use when creating a missing UUID
1241
    @type check_uuid: bool
1242
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1243
                       it does, ensure that it does not exist in the
1244
                       configuration already
1245

1246
    """
1247
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1248
    self._WriteConfig()
1249

    
1250
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1251
    """Add a node group to the configuration.
1252

1253
    """
1254
    logging.info("Adding node group %s to configuration", group.name)
1255

    
1256
    # Some code might need to add a node group with a pre-populated UUID
1257
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1258
    # the "does this UUID" exist already check.
1259
    if check_uuid:
1260
      self._EnsureUUID(group, ec_id)
1261

    
1262
    try:
1263
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1264
    except errors.OpPrereqError:
1265
      pass
1266
    else:
1267
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1268
                                 " node group (UUID: %s)" %
1269
                                 (group.name, existing_uuid),
1270
                                 errors.ECODE_EXISTS)
1271

    
1272
    group.serial_no = 1
1273
    group.ctime = group.mtime = time.time()
1274
    group.UpgradeConfig()
1275

    
1276
    self._config_data.nodegroups[group.uuid] = group
1277
    self._config_data.cluster.serial_no += 1
1278

    
1279
  @locking.ssynchronized(_config_lock)
1280
  def RemoveNodeGroup(self, group_uuid):
1281
    """Remove a node group from the configuration.
1282

1283
    @type group_uuid: string
1284
    @param group_uuid: the UUID of the node group to remove
1285

1286
    """
1287
    logging.info("Removing node group %s from configuration", group_uuid)
1288

    
1289
    if group_uuid not in self._config_data.nodegroups:
1290
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1291

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

    
1295
    del self._config_data.nodegroups[group_uuid]
1296
    self._config_data.cluster.serial_no += 1
1297
    self._WriteConfig()
1298

    
1299
  def _UnlockedLookupNodeGroup(self, target):
1300
    """Lookup a node group's UUID.
1301

1302
    @type target: string or None
1303
    @param target: group name or UUID or None to look for the default
1304
    @rtype: string
1305
    @return: nodegroup UUID
1306
    @raises errors.OpPrereqError: when the target group cannot be found
1307

1308
    """
1309
    if target is None:
1310
      if len(self._config_data.nodegroups) != 1:
1311
        raise errors.OpPrereqError("More than one node group exists. Target"
1312
                                   " group must be specified explicitly.")
1313
      else:
1314
        return self._config_data.nodegroups.keys()[0]
1315
    if target in self._config_data.nodegroups:
1316
      return target
1317
    for nodegroup in self._config_data.nodegroups.values():
1318
      if nodegroup.name == target:
1319
        return nodegroup.uuid
1320
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1321
                               errors.ECODE_NOENT)
1322

    
1323
  @locking.ssynchronized(_config_lock, shared=1)
1324
  def LookupNodeGroup(self, target):
1325
    """Lookup a node group's UUID.
1326

1327
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1328

1329
    @type target: string or None
1330
    @param target: group name or UUID or None to look for the default
1331
    @rtype: string
1332
    @return: nodegroup UUID
1333

1334
    """
1335
    return self._UnlockedLookupNodeGroup(target)
1336

    
1337
  def _UnlockedGetNodeGroup(self, uuid):
1338
    """Lookup a node group.
1339

1340
    @type uuid: string
1341
    @param uuid: group UUID
1342
    @rtype: L{objects.NodeGroup} or None
1343
    @return: nodegroup object, or None if not found
1344

1345
    """
1346
    if uuid not in self._config_data.nodegroups:
1347
      return None
1348

    
1349
    return self._config_data.nodegroups[uuid]
1350

    
1351
  @locking.ssynchronized(_config_lock, shared=1)
1352
  def GetNodeGroup(self, uuid):
1353
    """Lookup a node group.
1354

1355
    @type uuid: string
1356
    @param uuid: group UUID
1357
    @rtype: L{objects.NodeGroup} or None
1358
    @return: nodegroup object, or None if not found
1359

1360
    """
1361
    return self._UnlockedGetNodeGroup(uuid)
1362

    
1363
  def _UnlockedGetAllNodeGroupsInfo(self):
1364
    """Get the configuration of all node groups.
1365

1366
    """
1367
    return dict(self._config_data.nodegroups)
1368

    
1369
  @locking.ssynchronized(_config_lock, shared=1)
1370
  def GetAllNodeGroupsInfo(self):
1371
    """Get the configuration of all node groups.
1372

1373
    """
1374
    return self._UnlockedGetAllNodeGroupsInfo()
1375

    
1376
  @locking.ssynchronized(_config_lock, shared=1)
1377
  def GetAllNodeGroupsInfoDict(self):
1378
    """Get the configuration of all node groups expressed as a dictionary of
1379
    dictionaries.
1380

1381
    """
1382
    return dict(map(lambda (uuid, ng): (uuid, ng.ToDict()),
1383
                    self._UnlockedGetAllNodeGroupsInfo().items()))
1384

    
1385
  @locking.ssynchronized(_config_lock, shared=1)
1386
  def GetNodeGroupList(self):
1387
    """Get a list of node groups.
1388

1389
    """
1390
    return self._config_data.nodegroups.keys()
1391

    
1392
  @locking.ssynchronized(_config_lock, shared=1)
1393
  def GetNodeGroupMembersByNodes(self, nodes):
1394
    """Get nodes which are member in the same nodegroups as the given nodes.
1395

1396
    """
1397
    ngfn = lambda node_uuid: self._UnlockedGetNodeInfo(node_uuid).group
1398
    return frozenset(member_uuid
1399
                     for node_uuid in nodes
1400
                     for member_uuid in
1401
                       self._UnlockedGetNodeGroup(ngfn(node_uuid)).members)
1402

    
1403
  @locking.ssynchronized(_config_lock, shared=1)
1404
  def GetMultiNodeGroupInfo(self, group_uuids):
1405
    """Get the configuration of multiple node groups.
1406

1407
    @param group_uuids: List of node group UUIDs
1408
    @rtype: list
1409
    @return: List of tuples of (group_uuid, group_info)
1410

1411
    """
1412
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1413

    
1414
  @locking.ssynchronized(_config_lock)
1415
  def AddInstance(self, instance, ec_id):
1416
    """Add an instance to the config.
1417

1418
    This should be used after creating a new instance.
1419

1420
    @type instance: L{objects.Instance}
1421
    @param instance: the instance object
1422

1423
    """
1424
    if not isinstance(instance, objects.Instance):
1425
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1426

    
1427
    if instance.disk_template != constants.DT_DISKLESS:
1428
      all_lvs = instance.MapLVsByNode()
1429
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1430

    
1431
    all_macs = self._AllMACs()
1432
    for nic in instance.nics:
1433
      if nic.mac in all_macs:
1434
        raise errors.ConfigurationError("Cannot add instance %s:"
1435
                                        " MAC address '%s' already in use." %
1436
                                        (instance.name, nic.mac))
1437

    
1438
    self._CheckUniqueUUID(instance, include_temporary=False)
1439

    
1440
    instance.serial_no = 1
1441
    instance.ctime = instance.mtime = time.time()
1442
    self._config_data.instances[instance.uuid] = instance
1443
    self._config_data.cluster.serial_no += 1
1444
    self._UnlockedReleaseDRBDMinors(instance.uuid)
1445
    self._UnlockedCommitTemporaryIps(ec_id)
1446
    self._WriteConfig()
1447

    
1448
  def _EnsureUUID(self, item, ec_id):
1449
    """Ensures a given object has a valid UUID.
1450

1451
    @param item: the instance or node to be checked
1452
    @param ec_id: the execution context id for the uuid reservation
1453

1454
    """
1455
    if not item.uuid:
1456
      item.uuid = self._GenerateUniqueID(ec_id)
1457
    else:
1458
      self._CheckUniqueUUID(item, include_temporary=True)
1459

    
1460
  def _CheckUniqueUUID(self, item, include_temporary):
1461
    """Checks that the UUID of the given object is unique.
1462

1463
    @param item: the instance or node to be checked
1464
    @param include_temporary: whether temporarily generated UUID's should be
1465
              included in the check. If the UUID of the item to be checked is
1466
              a temporarily generated one, this has to be C{False}.
1467

1468
    """
1469
    if not item.uuid:
1470
      raise errors.ConfigurationError("'%s' must have an UUID" % (item.name,))
1471
    if item.uuid in self._AllIDs(include_temporary=include_temporary):
1472
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1473
                                      " in use" % (item.name, item.uuid))
1474

    
1475
  def _SetInstanceStatus(self, inst_uuid, status, disks_active):
1476
    """Set the instance's status to a given value.
1477

1478
    """
1479
    if inst_uuid not in self._config_data.instances:
1480
      raise errors.ConfigurationError("Unknown instance '%s'" %
1481
                                      inst_uuid)
1482
    instance = self._config_data.instances[inst_uuid]
1483

    
1484
    if status is None:
1485
      status = instance.admin_state
1486
    if disks_active is None:
1487
      disks_active = instance.disks_active
1488

    
1489
    assert status in constants.ADMINST_ALL, \
1490
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1491

    
1492
    if instance.admin_state != status or \
1493
       instance.disks_active != disks_active:
1494
      instance.admin_state = status
1495
      instance.disks_active = disks_active
1496
      instance.serial_no += 1
1497
      instance.mtime = time.time()
1498
      self._WriteConfig()
1499

    
1500
  @locking.ssynchronized(_config_lock)
1501
  def MarkInstanceUp(self, inst_uuid):
1502
    """Mark the instance status to up in the config.
1503

1504
    This also sets the instance disks active flag.
1505

1506
    """
1507
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_UP, True)
1508

    
1509
  @locking.ssynchronized(_config_lock)
1510
  def MarkInstanceOffline(self, inst_uuid):
1511
    """Mark the instance status to down in the config.
1512

1513
    This also clears the instance disks active flag.
1514

1515
    """
1516
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_OFFLINE, False)
1517

    
1518
  @locking.ssynchronized(_config_lock)
1519
  def RemoveInstance(self, inst_uuid):
1520
    """Remove the instance from the configuration.
1521

1522
    """
1523
    if inst_uuid not in self._config_data.instances:
1524
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1525

    
1526
    # If a network port has been allocated to the instance,
1527
    # return it to the pool of free ports.
1528
    inst = self._config_data.instances[inst_uuid]
1529
    network_port = getattr(inst, "network_port", None)
1530
    if network_port is not None:
1531
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1532

    
1533
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1534

    
1535
    for nic in instance.nics:
1536
      if nic.network and nic.ip:
1537
        # Return all IP addresses to the respective address pools
1538
        self._UnlockedCommitIp(constants.RELEASE_ACTION, nic.network, nic.ip)
1539

    
1540
    del self._config_data.instances[inst_uuid]
1541
    self._config_data.cluster.serial_no += 1
1542
    self._WriteConfig()
1543

    
1544
  @locking.ssynchronized(_config_lock)
1545
  def RenameInstance(self, inst_uuid, new_name):
1546
    """Rename an instance.
1547

1548
    This needs to be done in ConfigWriter and not by RemoveInstance
1549
    combined with AddInstance as only we can guarantee an atomic
1550
    rename.
1551

1552
    """
1553
    if inst_uuid not in self._config_data.instances:
1554
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1555

    
1556
    inst = self._config_data.instances[inst_uuid]
1557
    inst.name = new_name
1558

    
1559
    for (idx, disk) in enumerate(inst.disks):
1560
      if disk.dev_type in [constants.DT_FILE, constants.DT_SHARED_FILE]:
1561
        # rename the file paths in logical and physical id
1562
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1563
        disk.logical_id = (disk.logical_id[0],
1564
                           utils.PathJoin(file_storage_dir, inst.name,
1565
                                          "disk%s" % idx))
1566

    
1567
    # Force update of ssconf files
1568
    self._config_data.cluster.serial_no += 1
1569

    
1570
    self._WriteConfig()
1571

    
1572
  @locking.ssynchronized(_config_lock)
1573
  def MarkInstanceDown(self, inst_uuid):
1574
    """Mark the status of an instance to down in the configuration.
1575

1576
    This does not touch the instance disks active flag, as shut down instances
1577
    can still have active disks.
1578

1579
    """
1580
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_DOWN, None)
1581

    
1582
  @locking.ssynchronized(_config_lock)
1583
  def MarkInstanceDisksActive(self, inst_uuid):
1584
    """Mark the status of instance disks active.
1585

1586
    """
1587
    self._SetInstanceStatus(inst_uuid, None, True)
1588

    
1589
  @locking.ssynchronized(_config_lock)
1590
  def MarkInstanceDisksInactive(self, inst_uuid):
1591
    """Mark the status of instance disks inactive.
1592

1593
    """
1594
    self._SetInstanceStatus(inst_uuid, None, False)
1595

    
1596
  def _UnlockedGetInstanceList(self):
1597
    """Get the list of instances.
1598

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

1601
    """
1602
    return self._config_data.instances.keys()
1603

    
1604
  @locking.ssynchronized(_config_lock, shared=1)
1605
  def GetInstanceList(self):
1606
    """Get the list of instances.
1607

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

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

    
1613
  def ExpandInstanceName(self, short_name):
1614
    """Attempt to expand an incomplete instance name.
1615

1616
    """
1617
    # Locking is done in L{ConfigWriter.GetAllInstancesInfo}
1618
    all_insts = self.GetAllInstancesInfo().values()
1619
    expanded_name = _MatchNameComponentIgnoreCase(
1620
                      short_name, [inst.name for inst in all_insts])
1621

    
1622
    if expanded_name is not None:
1623
      # there has to be exactly one instance with that name
1624
      inst = (filter(lambda n: n.name == expanded_name, all_insts)[0])
1625
      return (inst.uuid, inst.name)
1626
    else:
1627
      return (None, None)
1628

    
1629
  def _UnlockedGetInstanceInfo(self, inst_uuid):
1630
    """Returns information about an instance.
1631

1632
    This function is for internal use, when the config lock is already held.
1633

1634
    """
1635
    if inst_uuid not in self._config_data.instances:
1636
      return None
1637

    
1638
    return self._config_data.instances[inst_uuid]
1639

    
1640
  @locking.ssynchronized(_config_lock, shared=1)
1641
  def GetInstanceInfo(self, inst_uuid):
1642
    """Returns information about an instance.
1643

1644
    It takes the information from the configuration file. Other information of
1645
    an instance are taken from the live systems.
1646

1647
    @param inst_uuid: UUID of the instance
1648

1649
    @rtype: L{objects.Instance}
1650
    @return: the instance object
1651

1652
    """
1653
    return self._UnlockedGetInstanceInfo(inst_uuid)
1654

    
1655
  @locking.ssynchronized(_config_lock, shared=1)
1656
  def GetInstanceNodeGroups(self, inst_uuid, primary_only=False):
1657
    """Returns set of node group UUIDs for instance's nodes.
1658

1659
    @rtype: frozenset
1660

1661
    """
1662
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1663
    if not instance:
1664
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1665

    
1666
    if primary_only:
1667
      nodes = [instance.primary_node]
1668
    else:
1669
      nodes = instance.all_nodes
1670

    
1671
    return frozenset(self._UnlockedGetNodeInfo(node_uuid).group
1672
                     for node_uuid in nodes)
1673

    
1674
  @locking.ssynchronized(_config_lock, shared=1)
1675
  def GetInstanceNetworks(self, inst_uuid):
1676
    """Returns set of network UUIDs for instance's nics.
1677

1678
    @rtype: frozenset
1679

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

    
1685
    networks = set()
1686
    for nic in instance.nics:
1687
      if nic.network:
1688
        networks.add(nic.network)
1689

    
1690
    return frozenset(networks)
1691

    
1692
  @locking.ssynchronized(_config_lock, shared=1)
1693
  def GetMultiInstanceInfo(self, inst_uuids):
1694
    """Get the configuration of multiple instances.
1695

1696
    @param inst_uuids: list of instance UUIDs
1697
    @rtype: list
1698
    @return: list of tuples (instance UUID, instance_info), where
1699
        instance_info is what would GetInstanceInfo return for the
1700
        node, while keeping the original order
1701

1702
    """
1703
    return [(uuid, self._UnlockedGetInstanceInfo(uuid)) for uuid in inst_uuids]
1704

    
1705
  @locking.ssynchronized(_config_lock, shared=1)
1706
  def GetMultiInstanceInfoByName(self, inst_names):
1707
    """Get the configuration of multiple instances.
1708

1709
    @param inst_names: list of instance names
1710
    @rtype: list
1711
    @return: list of tuples (instance, instance_info), where
1712
        instance_info is what would GetInstanceInfo return for the
1713
        node, while keeping the original order
1714

1715
    """
1716
    result = []
1717
    for name in inst_names:
1718
      instance = self._UnlockedGetInstanceInfoByName(name)
1719
      result.append((instance.uuid, instance))
1720
    return result
1721

    
1722
  @locking.ssynchronized(_config_lock, shared=1)
1723
  def GetAllInstancesInfo(self):
1724
    """Get the configuration of all instances.
1725

1726
    @rtype: dict
1727
    @return: dict of (instance, instance_info), where instance_info is what
1728
              would GetInstanceInfo return for the node
1729

1730
    """
1731
    return self._UnlockedGetAllInstancesInfo()
1732

    
1733
  def _UnlockedGetAllInstancesInfo(self):
1734
    my_dict = dict([(inst_uuid, self._UnlockedGetInstanceInfo(inst_uuid))
1735
                    for inst_uuid in self._UnlockedGetInstanceList()])
1736
    return my_dict
1737

    
1738
  @locking.ssynchronized(_config_lock, shared=1)
1739
  def GetInstancesInfoByFilter(self, filter_fn):
1740
    """Get instance configuration with a filter.
1741

1742
    @type filter_fn: callable
1743
    @param filter_fn: Filter function receiving instance object as parameter,
1744
      returning boolean. Important: this function is called while the
1745
      configuration locks is held. It must not do any complex work or call
1746
      functions potentially leading to a deadlock. Ideally it doesn't call any
1747
      other functions and just compares instance attributes.
1748

1749
    """
1750
    return dict((uuid, inst)
1751
                for (uuid, inst) in self._config_data.instances.items()
1752
                if filter_fn(inst))
1753

    
1754
  @locking.ssynchronized(_config_lock, shared=1)
1755
  def GetInstanceInfoByName(self, inst_name):
1756
    """Get the L{objects.Instance} object for a named instance.
1757

1758
    @param inst_name: name of the instance to get information for
1759
    @type inst_name: string
1760
    @return: the corresponding L{objects.Instance} instance or None if no
1761
          information is available
1762

1763
    """
1764
    return self._UnlockedGetInstanceInfoByName(inst_name)
1765

    
1766
  def _UnlockedGetInstanceInfoByName(self, inst_name):
1767
    for inst in self._UnlockedGetAllInstancesInfo().values():
1768
      if inst.name == inst_name:
1769
        return inst
1770
    return None
1771

    
1772
  def _UnlockedGetInstanceName(self, inst_uuid):
1773
    inst_info = self._UnlockedGetInstanceInfo(inst_uuid)
1774
    if inst_info is None:
1775
      raise errors.OpExecError("Unknown instance: %s" % inst_uuid)
1776
    return inst_info.name
1777

    
1778
  @locking.ssynchronized(_config_lock, shared=1)
1779
  def GetInstanceName(self, inst_uuid):
1780
    """Gets the instance name for the passed instance.
1781

1782
    @param inst_uuid: instance UUID to get name for
1783
    @type inst_uuid: string
1784
    @rtype: string
1785
    @return: instance name
1786

1787
    """
1788
    return self._UnlockedGetInstanceName(inst_uuid)
1789

    
1790
  @locking.ssynchronized(_config_lock, shared=1)
1791
  def GetInstanceNames(self, inst_uuids):
1792
    """Gets the instance names for the passed list of nodes.
1793

1794
    @param inst_uuids: list of instance UUIDs to get names for
1795
    @type inst_uuids: list of strings
1796
    @rtype: list of strings
1797
    @return: list of instance names
1798

1799
    """
1800
    return self._UnlockedGetInstanceNames(inst_uuids)
1801

    
1802
  def _UnlockedGetInstanceNames(self, inst_uuids):
1803
    return [self._UnlockedGetInstanceName(uuid) for uuid in inst_uuids]
1804

    
1805
  @locking.ssynchronized(_config_lock)
1806
  def AddNode(self, node, ec_id):
1807
    """Add a node to the configuration.
1808

1809
    @type node: L{objects.Node}
1810
    @param node: a Node instance
1811

1812
    """
1813
    logging.info("Adding node %s to configuration", node.name)
1814

    
1815
    self._EnsureUUID(node, ec_id)
1816

    
1817
    node.serial_no = 1
1818
    node.ctime = node.mtime = time.time()
1819
    self._UnlockedAddNodeToGroup(node.uuid, node.group)
1820
    self._config_data.nodes[node.uuid] = node
1821
    self._config_data.cluster.serial_no += 1
1822
    self._WriteConfig()
1823

    
1824
  @locking.ssynchronized(_config_lock)
1825
  def RemoveNode(self, node_uuid):
1826
    """Remove a node from the configuration.
1827

1828
    """
1829
    logging.info("Removing node %s from configuration", node_uuid)
1830

    
1831
    if node_uuid not in self._config_data.nodes:
1832
      raise errors.ConfigurationError("Unknown node '%s'" % node_uuid)
1833

    
1834
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_uuid])
1835
    del self._config_data.nodes[node_uuid]
1836
    self._config_data.cluster.serial_no += 1
1837
    self._WriteConfig()
1838

    
1839
  def ExpandNodeName(self, short_name):
1840
    """Attempt to expand an incomplete node name into a node UUID.
1841

1842
    """
1843
    # Locking is done in L{ConfigWriter.GetAllNodesInfo}
1844
    all_nodes = self.GetAllNodesInfo().values()
1845
    expanded_name = _MatchNameComponentIgnoreCase(
1846
                      short_name, [node.name for node in all_nodes])
1847

    
1848
    if expanded_name is not None:
1849
      # there has to be exactly one node with that name
1850
      node = (filter(lambda n: n.name == expanded_name, all_nodes)[0])
1851
      return (node.uuid, node.name)
1852
    else:
1853
      return (None, None)
1854

    
1855
  def _UnlockedGetNodeInfo(self, node_uuid):
1856
    """Get the configuration of a node, as stored in the config.
1857

1858
    This function is for internal use, when the config lock is already
1859
    held.
1860

1861
    @param node_uuid: the node UUID
1862

1863
    @rtype: L{objects.Node}
1864
    @return: the node object
1865

1866
    """
1867
    if node_uuid not in self._config_data.nodes:
1868
      return None
1869

    
1870
    return self._config_data.nodes[node_uuid]
1871

    
1872
  @locking.ssynchronized(_config_lock, shared=1)
1873
  def GetNodeInfo(self, node_uuid):
1874
    """Get the configuration of a node, as stored in the config.
1875

1876
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1877

1878
    @param node_uuid: the node UUID
1879

1880
    @rtype: L{objects.Node}
1881
    @return: the node object
1882

1883
    """
1884
    return self._UnlockedGetNodeInfo(node_uuid)
1885

    
1886
  @locking.ssynchronized(_config_lock, shared=1)
1887
  def GetNodeInstances(self, node_uuid):
1888
    """Get the instances of a node, as stored in the config.
1889

1890
    @param node_uuid: the node UUID
1891

1892
    @rtype: (list, list)
1893
    @return: a tuple with two lists: the primary and the secondary instances
1894

1895
    """
1896
    pri = []
1897
    sec = []
1898
    for inst in self._config_data.instances.values():
1899
      if inst.primary_node == node_uuid:
1900
        pri.append(inst.uuid)
1901
      if node_uuid in inst.secondary_nodes:
1902
        sec.append(inst.uuid)
1903
    return (pri, sec)
1904

    
1905
  @locking.ssynchronized(_config_lock, shared=1)
1906
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1907
    """Get the instances of a node group.
1908

1909
    @param uuid: Node group UUID
1910
    @param primary_only: Whether to only consider primary nodes
1911
    @rtype: frozenset
1912
    @return: List of instance UUIDs in node group
1913

1914
    """
1915
    if primary_only:
1916
      nodes_fn = lambda inst: [inst.primary_node]
1917
    else:
1918
      nodes_fn = lambda inst: inst.all_nodes
1919

    
1920
    return frozenset(inst.uuid
1921
                     for inst in self._config_data.instances.values()
1922
                     for node_uuid in nodes_fn(inst)
1923
                     if self._UnlockedGetNodeInfo(node_uuid).group == uuid)
1924

    
1925
  def _UnlockedGetHvparamsString(self, hvname):
1926
    """Return the string representation of the list of hyervisor parameters of
1927
    the given hypervisor.
1928

1929
    @see: C{GetHvparams}
1930

1931
    """
1932
    result = ""
1933
    hvparams = self._config_data.cluster.hvparams[hvname]
1934
    for key in hvparams:
1935
      result += "%s=%s\n" % (key, hvparams[key])
1936
    return result
1937

    
1938
  @locking.ssynchronized(_config_lock, shared=1)
1939
  def GetHvparamsString(self, hvname):
1940
    """Return the hypervisor parameters of the given hypervisor.
1941

1942
    @type hvname: string
1943
    @param hvname: name of a hypervisor
1944
    @rtype: string
1945
    @return: string containing key-value-pairs, one pair on each line;
1946
      format: KEY=VALUE
1947

1948
    """
1949
    return self._UnlockedGetHvparamsString(hvname)
1950

    
1951
  def _UnlockedGetNodeList(self):
1952
    """Return the list of nodes which are in the configuration.
1953

1954
    This function is for internal use, when the config lock is already
1955
    held.
1956

1957
    @rtype: list
1958

1959
    """
1960
    return self._config_data.nodes.keys()
1961

    
1962
  @locking.ssynchronized(_config_lock, shared=1)
1963
  def GetNodeList(self):
1964
    """Return the list of nodes which are in the configuration.
1965

1966
    """
1967
    return self._UnlockedGetNodeList()
1968

    
1969
  def _UnlockedGetOnlineNodeList(self):
1970
    """Return the list of nodes which are online.
1971

1972
    """
1973
    all_nodes = [self._UnlockedGetNodeInfo(node)
1974
                 for node in self._UnlockedGetNodeList()]
1975
    return [node.uuid for node in all_nodes if not node.offline]
1976

    
1977
  @locking.ssynchronized(_config_lock, shared=1)
1978
  def GetOnlineNodeList(self):
1979
    """Return the list of nodes which are online.
1980

1981
    """
1982
    return self._UnlockedGetOnlineNodeList()
1983

    
1984
  @locking.ssynchronized(_config_lock, shared=1)
1985
  def GetVmCapableNodeList(self):
1986
    """Return the list of nodes which are not vm capable.
1987

1988
    """
1989
    all_nodes = [self._UnlockedGetNodeInfo(node)
1990
                 for node in self._UnlockedGetNodeList()]
1991
    return [node.uuid for node in all_nodes if node.vm_capable]
1992

    
1993
  @locking.ssynchronized(_config_lock, shared=1)
1994
  def GetNonVmCapableNodeList(self):
1995
    """Return the list of nodes which are not vm capable.
1996

1997
    """
1998
    all_nodes = [self._UnlockedGetNodeInfo(node)
1999
                 for node in self._UnlockedGetNodeList()]
2000
    return [node.uuid for node in all_nodes if not node.vm_capable]
2001

    
2002
  @locking.ssynchronized(_config_lock, shared=1)
2003
  def GetMultiNodeInfo(self, node_uuids):
2004
    """Get the configuration of multiple nodes.
2005

2006
    @param node_uuids: list of node UUIDs
2007
    @rtype: list
2008
    @return: list of tuples of (node, node_info), where node_info is
2009
        what would GetNodeInfo return for the node, in the original
2010
        order
2011

2012
    """
2013
    return [(uuid, self._UnlockedGetNodeInfo(uuid)) for uuid in node_uuids]
2014

    
2015
  def _UnlockedGetAllNodesInfo(self):
2016
    """Gets configuration of all nodes.
2017

2018
    @note: See L{GetAllNodesInfo}
2019

2020
    """
2021
    return dict([(node_uuid, self._UnlockedGetNodeInfo(node_uuid))
2022
                 for node_uuid in self._UnlockedGetNodeList()])
2023

    
2024
  @locking.ssynchronized(_config_lock, shared=1)
2025
  def GetAllNodesInfo(self):
2026
    """Get the configuration of all nodes.
2027

2028
    @rtype: dict
2029
    @return: dict of (node, node_info), where node_info is what
2030
              would GetNodeInfo return for the node
2031

2032
    """
2033
    return self._UnlockedGetAllNodesInfo()
2034

    
2035
  def _UnlockedGetNodeInfoByName(self, node_name):
2036
    for node in self._UnlockedGetAllNodesInfo().values():
2037
      if node.name == node_name:
2038
        return node
2039
    return None
2040

    
2041
  @locking.ssynchronized(_config_lock, shared=1)
2042
  def GetNodeInfoByName(self, node_name):
2043
    """Get the L{objects.Node} object for a named node.
2044

2045
    @param node_name: name of the node to get information for
2046
    @type node_name: string
2047
    @return: the corresponding L{objects.Node} instance or None if no
2048
          information is available
2049

2050
    """
2051
    return self._UnlockedGetNodeInfoByName(node_name)
2052

    
2053
  @locking.ssynchronized(_config_lock, shared=1)
2054
  def GetNodeGroupInfoByName(self, nodegroup_name):
2055
    """Get the L{objects.NodeGroup} object for a named node group.
2056

2057
    @param nodegroup_name: name of the node group to get information for
2058
    @type nodegroup_name: string
2059
    @return: the corresponding L{objects.NodeGroup} instance or None if no
2060
          information is available
2061

2062
    """
2063
    for nodegroup in self._UnlockedGetAllNodeGroupsInfo().values():
2064
      if nodegroup.name == nodegroup_name:
2065
        return nodegroup
2066
    return None
2067

    
2068
  def _UnlockedGetNodeName(self, node_spec):
2069
    if isinstance(node_spec, objects.Node):
2070
      return node_spec.name
2071
    elif isinstance(node_spec, basestring):
2072
      node_info = self._UnlockedGetNodeInfo(node_spec)
2073
      if node_info is None:
2074
        raise errors.OpExecError("Unknown node: %s" % node_spec)
2075
      return node_info.name
2076
    else:
2077
      raise errors.ProgrammerError("Can't handle node spec '%s'" % node_spec)
2078

    
2079
  @locking.ssynchronized(_config_lock, shared=1)
2080
  def GetNodeName(self, node_spec):
2081
    """Gets the node name for the passed node.
2082

2083
    @param node_spec: node to get names for
2084
    @type node_spec: either node UUID or a L{objects.Node} object
2085
    @rtype: string
2086
    @return: node name
2087

2088
    """
2089
    return self._UnlockedGetNodeName(node_spec)
2090

    
2091
  def _UnlockedGetNodeNames(self, node_specs):
2092
    return [self._UnlockedGetNodeName(node_spec) for node_spec in node_specs]
2093

    
2094
  @locking.ssynchronized(_config_lock, shared=1)
2095
  def GetNodeNames(self, node_specs):
2096
    """Gets the node names for the passed list of nodes.
2097

2098
    @param node_specs: list of nodes to get names for
2099
    @type node_specs: list of either node UUIDs or L{objects.Node} objects
2100
    @rtype: list of strings
2101
    @return: list of node names
2102

2103
    """
2104
    return self._UnlockedGetNodeNames(node_specs)
2105

    
2106
  @locking.ssynchronized(_config_lock, shared=1)
2107
  def GetNodeGroupsFromNodes(self, node_uuids):
2108
    """Returns groups for a list of nodes.
2109

2110
    @type node_uuids: list of string
2111
    @param node_uuids: List of node UUIDs
2112
    @rtype: frozenset
2113

2114
    """
2115
    return frozenset(self._UnlockedGetNodeInfo(uuid).group
2116
                     for uuid in node_uuids)
2117

    
2118
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
2119
    """Get the number of current and maximum desired and possible candidates.
2120

2121
    @type exceptions: list
2122
    @param exceptions: if passed, list of nodes that should be ignored
2123
    @rtype: tuple
2124
    @return: tuple of (current, desired and possible, possible)
2125

2126
    """
2127
    mc_now = mc_should = mc_max = 0
2128
    for node in self._config_data.nodes.values():
2129
      if exceptions and node.uuid in exceptions:
2130
        continue
2131
      if not (node.offline or node.drained) and node.master_capable:
2132
        mc_max += 1
2133
      if node.master_candidate:
2134
        mc_now += 1
2135
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
2136
    return (mc_now, mc_should, mc_max)
2137

    
2138
  @locking.ssynchronized(_config_lock, shared=1)
2139
  def GetMasterCandidateStats(self, exceptions=None):
2140
    """Get the number of current and maximum possible candidates.
2141

2142
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
2143

2144
    @type exceptions: list
2145
    @param exceptions: if passed, list of nodes that should be ignored
2146
    @rtype: tuple
2147
    @return: tuple of (current, max)
2148

2149
    """
2150
    return self._UnlockedGetMasterCandidateStats(exceptions)
2151

    
2152
  @locking.ssynchronized(_config_lock)
2153
  def MaintainCandidatePool(self, exception_node_uuids):
2154
    """Try to grow the candidate pool to the desired size.
2155

2156
    @type exception_node_uuids: list
2157
    @param exception_node_uuids: if passed, list of nodes that should be ignored
2158
    @rtype: list
2159
    @return: list with the adjusted nodes (L{objects.Node} instances)
2160

2161
    """
2162
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(
2163
                          exception_node_uuids)
2164
    mod_list = []
2165
    if mc_now < mc_max:
2166
      node_list = self._config_data.nodes.keys()
2167
      random.shuffle(node_list)
2168
      for uuid in node_list:
2169
        if mc_now >= mc_max:
2170
          break
2171
        node = self._config_data.nodes[uuid]
2172
        if (node.master_candidate or node.offline or node.drained or
2173
            node.uuid in exception_node_uuids or not node.master_capable):
2174
          continue
2175
        mod_list.append(node)
2176
        node.master_candidate = True
2177
        node.serial_no += 1
2178
        mc_now += 1
2179
      if mc_now != mc_max:
2180
        # this should not happen
2181
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
2182
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
2183
      if mod_list:
2184
        self._config_data.cluster.serial_no += 1
2185
        self._WriteConfig()
2186

    
2187
    return mod_list
2188

    
2189
  def _UnlockedAddNodeToGroup(self, node_uuid, nodegroup_uuid):
2190
    """Add a given node to the specified group.
2191

2192
    """
2193
    if nodegroup_uuid not in self._config_data.nodegroups:
2194
      # This can happen if a node group gets deleted between its lookup and
2195
      # when we're adding the first node to it, since we don't keep a lock in
2196
      # the meantime. It's ok though, as we'll fail cleanly if the node group
2197
      # is not found anymore.
2198
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
2199
    if node_uuid not in self._config_data.nodegroups[nodegroup_uuid].members:
2200
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_uuid)
2201

    
2202
  def _UnlockedRemoveNodeFromGroup(self, node):
2203
    """Remove a given node from its group.
2204

2205
    """
2206
    nodegroup = node.group
2207
    if nodegroup not in self._config_data.nodegroups:
2208
      logging.warning("Warning: node '%s' has unknown node group '%s'"
2209
                      " (while being removed from it)", node.uuid, nodegroup)
2210
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
2211
    if node.uuid not in nodegroup_obj.members:
2212
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
2213
                      " (while being removed from it)", node.uuid, nodegroup)
2214
    else:
2215
      nodegroup_obj.members.remove(node.uuid)
2216

    
2217
  @locking.ssynchronized(_config_lock)
2218
  def AssignGroupNodes(self, mods):
2219
    """Changes the group of a number of nodes.
2220

2221
    @type mods: list of tuples; (node name, new group UUID)
2222
    @param mods: Node membership modifications
2223

2224
    """
2225
    groups = self._config_data.nodegroups
2226
    nodes = self._config_data.nodes
2227

    
2228
    resmod = []
2229

    
2230
    # Try to resolve UUIDs first
2231
    for (node_uuid, new_group_uuid) in mods:
2232
      try:
2233
        node = nodes[node_uuid]
2234
      except KeyError:
2235
        raise errors.ConfigurationError("Unable to find node '%s'" % node_uuid)
2236

    
2237
      if node.group == new_group_uuid:
2238
        # Node is being assigned to its current group
2239
        logging.debug("Node '%s' was assigned to its current group (%s)",
2240
                      node_uuid, node.group)
2241
        continue
2242

    
2243
      # Try to find current group of node
2244
      try:
2245
        old_group = groups[node.group]
2246
      except KeyError:
2247
        raise errors.ConfigurationError("Unable to find old group '%s'" %
2248
                                        node.group)
2249

    
2250
      # Try to find new group for node
2251
      try:
2252
        new_group = groups[new_group_uuid]
2253
      except KeyError:
2254
        raise errors.ConfigurationError("Unable to find new group '%s'" %
2255
                                        new_group_uuid)
2256

    
2257
      assert node.uuid in old_group.members, \
2258
        ("Inconsistent configuration: node '%s' not listed in members for its"
2259
         " old group '%s'" % (node.uuid, old_group.uuid))
2260
      assert node.uuid not in new_group.members, \
2261
        ("Inconsistent configuration: node '%s' already listed in members for"
2262
         " its new group '%s'" % (node.uuid, new_group.uuid))
2263

    
2264
      resmod.append((node, old_group, new_group))
2265

    
2266
    # Apply changes
2267
    for (node, old_group, new_group) in resmod:
2268
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
2269
        "Assigning to current group is not possible"
2270

    
2271
      node.group = new_group.uuid
2272

    
2273
      # Update members of involved groups
2274
      if node.uuid in old_group.members:
2275
        old_group.members.remove(node.uuid)
2276
      if node.uuid not in new_group.members:
2277
        new_group.members.append(node.uuid)
2278

    
2279
    # Update timestamps and serials (only once per node/group object)
2280
    now = time.time()
2281
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
2282
      obj.serial_no += 1
2283
      obj.mtime = now
2284

    
2285
    # Force ssconf update
2286
    self._config_data.cluster.serial_no += 1
2287

    
2288
    self._WriteConfig()
2289

    
2290
  def _BumpSerialNo(self):
2291
    """Bump up the serial number of the config.
2292

2293
    """
2294
    self._config_data.serial_no += 1
2295
    self._config_data.mtime = time.time()
2296

    
2297
  def _AllUUIDObjects(self):
2298
    """Returns all objects with uuid attributes.
2299

2300
    """
2301
    return (self._config_data.instances.values() +
2302
            self._config_data.nodes.values() +
2303
            self._config_data.nodegroups.values() +
2304
            self._config_data.networks.values() +
2305
            self._AllDisks() +
2306
            self._AllNICs() +
2307
            [self._config_data.cluster])
2308

    
2309
  def _OpenConfig(self, accept_foreign):
2310
    """Read the config data from disk.
2311

2312
    """
2313
    raw_data = utils.ReadFile(self._cfg_file)
2314

    
2315
    try:
2316
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
2317
    except Exception, err:
2318
      raise errors.ConfigurationError(err)
2319

    
2320
    # Make sure the configuration has the right version
2321
    _ValidateConfig(data)
2322

    
2323
    if (not hasattr(data, "cluster") or
2324
        not hasattr(data.cluster, "rsahostkeypub")):
2325
      raise errors.ConfigurationError("Incomplete configuration"
2326
                                      " (missing cluster.rsahostkeypub)")
2327

    
2328
    if not data.cluster.master_node in data.nodes:
2329
      msg = ("The configuration denotes node %s as master, but does not"
2330
             " contain information about this node" %
2331
             data.cluster.master_node)
2332
      raise errors.ConfigurationError(msg)
2333

    
2334
    master_info = data.nodes[data.cluster.master_node]
2335
    if master_info.name != self._my_hostname and not accept_foreign:
2336
      msg = ("The configuration denotes node %s as master, while my"
2337
             " hostname is %s; opening a foreign configuration is only"
2338
             " possible in accept_foreign mode" %
2339
             (master_info.name, self._my_hostname))
2340
      raise errors.ConfigurationError(msg)
2341

    
2342
    self._config_data = data
2343
    # reset the last serial as -1 so that the next write will cause
2344
    # ssconf update
2345
    self._last_cluster_serial = -1
2346

    
2347
    # Upgrade configuration if needed
2348
    self._UpgradeConfig()
2349

    
2350
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2351

    
2352
  def _UpgradeConfig(self):
2353
    """Run any upgrade steps.
2354

2355
    This method performs both in-object upgrades and also update some data
2356
    elements that need uniqueness across the whole configuration or interact
2357
    with other objects.
2358

2359
    @warning: this function will call L{_WriteConfig()}, but also
2360
        L{DropECReservations} so it needs to be called only from a
2361
        "safe" place (the constructor). If one wanted to call it with
2362
        the lock held, a DropECReservationUnlocked would need to be
2363
        created first, to avoid causing deadlock.
2364

2365
    """
2366
    # Keep a copy of the persistent part of _config_data to check for changes
2367
    # Serialization doesn't guarantee order in dictionaries
2368
    oldconf = copy.deepcopy(self._config_data.ToDict())
2369

    
2370
    # In-object upgrades
2371
    self._config_data.UpgradeConfig()
2372

    
2373
    for item in self._AllUUIDObjects():
2374
      if item.uuid is None:
2375
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
2376
    if not self._config_data.nodegroups:
2377
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
2378
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
2379
                                            members=[])
2380
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
2381
    for node in self._config_data.nodes.values():
2382
      if not node.group:
2383
        node.group = self.LookupNodeGroup(None)
2384
      # This is technically *not* an upgrade, but needs to be done both when
2385
      # nodegroups are being added, and upon normally loading the config,
2386
      # because the members list of a node group is discarded upon
2387
      # serializing/deserializing the object.
2388
      self._UnlockedAddNodeToGroup(node.uuid, node.group)
2389

    
2390
    modified = (oldconf != self._config_data.ToDict())
2391
    if modified:
2392
      self._WriteConfig()
2393
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
2394
      # only called at config init time, without the lock held
2395
      self.DropECReservations(_UPGRADE_CONFIG_JID)
2396
    else:
2397
      config_errors = self._UnlockedVerifyConfig()
2398
      if config_errors:
2399
        errmsg = ("Loaded configuration data is not consistent: %s" %
2400
                  (utils.CommaJoin(config_errors)))
2401
        logging.critical(errmsg)
2402

    
2403
  def _DistributeConfig(self, feedback_fn):
2404
    """Distribute the configuration to the other nodes.
2405

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

2409
    """
2410
    if self._offline:
2411
      return True
2412

    
2413
    bad = False
2414

    
2415
    node_list = []
2416
    addr_list = []
2417
    myhostname = self._my_hostname
2418
    # we can skip checking whether _UnlockedGetNodeInfo returns None
2419
    # since the node list comes from _UnlocketGetNodeList, and we are
2420
    # called with the lock held, so no modifications should take place
2421
    # in between
2422
    for node_uuid in self._UnlockedGetNodeList():
2423
      node_info = self._UnlockedGetNodeInfo(node_uuid)
2424
      if node_info.name == myhostname or not node_info.master_candidate:
2425
        continue
2426
      node_list.append(node_info.name)
2427
      addr_list.append(node_info.primary_ip)
2428

    
2429
    # TODO: Use dedicated resolver talking to config writer for name resolution
2430
    result = \
2431
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2432
    for to_node, to_result in result.items():
2433
      msg = to_result.fail_msg
2434
      if msg:
2435
        msg = ("Copy of file %s to node %s failed: %s" %
2436
               (self._cfg_file, to_node, msg))
2437
        logging.error(msg)
2438

    
2439
        if feedback_fn:
2440
          feedback_fn(msg)
2441

    
2442
        bad = True
2443

    
2444
    return not bad
2445

    
2446
  def _WriteConfig(self, destination=None, feedback_fn=None):
2447
    """Write the configuration data to persistent storage.
2448

2449
    """
2450
    assert feedback_fn is None or callable(feedback_fn)
2451

    
2452
    # Warn on config errors, but don't abort the save - the
2453
    # configuration has already been modified, and we can't revert;
2454
    # the best we can do is to warn the user and save as is, leaving
2455
    # recovery to the user
2456
    config_errors = self._UnlockedVerifyConfig()
2457
    if config_errors:
2458
      errmsg = ("Configuration data is not consistent: %s" %
2459
                (utils.CommaJoin(config_errors)))
2460
      logging.critical(errmsg)
2461
      if feedback_fn:
2462
        feedback_fn(errmsg)
2463

    
2464
    if destination is None:
2465
      destination = self._cfg_file
2466
    self._BumpSerialNo()
2467
    txt = serializer.Dump(self._config_data.ToDict())
2468

    
2469
    getents = self._getents()
2470
    try:
2471
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2472
                               close=False, gid=getents.confd_gid, mode=0640)
2473
    except errors.LockError:
2474
      raise errors.ConfigurationError("The configuration file has been"
2475
                                      " modified since the last write, cannot"
2476
                                      " update")
2477
    try:
2478
      self._cfg_id = utils.GetFileID(fd=fd)
2479
    finally:
2480
      os.close(fd)
2481

    
2482
    self.write_count += 1
2483

    
2484
    # and redistribute the config file to master candidates
2485
    self._DistributeConfig(feedback_fn)
2486

    
2487
    # Write ssconf files on all nodes (including locally)
2488
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2489
      if not self._offline:
2490
        result = self._GetRpc(None).call_write_ssconf_files(
2491
          self._UnlockedGetNodeNames(self._UnlockedGetOnlineNodeList()),
2492
          self._UnlockedGetSsconfValues())
2493

    
2494
        for nname, nresu in result.items():
2495
          msg = nresu.fail_msg
2496
          if msg:
2497
            errmsg = ("Error while uploading ssconf files to"
2498
                      " node %s: %s" % (nname, msg))
2499
            logging.warning(errmsg)
2500

    
2501
            if feedback_fn:
2502
              feedback_fn(errmsg)
2503

    
2504
      self._last_cluster_serial = self._config_data.cluster.serial_no
2505

    
2506
  def _GetAllHvparamsStrings(self, hypervisors):
2507
    """Get the hvparams of all given hypervisors from the config.
2508

2509
    @type hypervisors: list of string
2510
    @param hypervisors: list of hypervisor names
2511
    @rtype: dict of strings
2512
    @returns: dictionary mapping the hypervisor name to a string representation
2513
      of the hypervisor's hvparams
2514

2515
    """
2516
    hvparams = {}
2517
    for hv in hypervisors:
2518
      hvparams[hv] = self._UnlockedGetHvparamsString(hv)
2519
    return hvparams
2520

    
2521
  @staticmethod
2522
  def _ExtendByAllHvparamsStrings(ssconf_values, all_hvparams):
2523
    """Extends the ssconf_values dictionary by hvparams.
2524

2525
    @type ssconf_values: dict of strings
2526
    @param ssconf_values: dictionary mapping ssconf_keys to strings
2527
      representing the content of ssconf files
2528
    @type all_hvparams: dict of strings
2529
    @param all_hvparams: dictionary mapping hypervisor names to a string
2530
      representation of their hvparams
2531
    @rtype: same as ssconf_values
2532
    @returns: the ssconf_values dictionary extended by hvparams
2533

2534
    """
2535
    for hv in all_hvparams:
2536
      ssconf_key = constants.SS_HVPARAMS_PREF + hv
2537
      ssconf_values[ssconf_key] = all_hvparams[hv]
2538
    return ssconf_values
2539

    
2540
  def _UnlockedGetSsconfValues(self):
2541
    """Return the values needed by ssconf.
2542

2543
    @rtype: dict
2544
    @return: a dictionary with keys the ssconf names and values their
2545
        associated value
2546

2547
    """
2548
    fn = "\n".join
2549
    instance_names = utils.NiceSort(
2550
                       [inst.name for inst in
2551
                        self._UnlockedGetAllInstancesInfo().values()])
2552
    node_infos = self._UnlockedGetAllNodesInfo().values()
2553
    node_names = [node.name for node in node_infos]
2554
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2555
                    for ninfo in node_infos]
2556
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2557
                    for ninfo in node_infos]
2558

    
2559
    instance_data = fn(instance_names)
2560
    off_data = fn(node.name for node in node_infos if node.offline)
2561
    on_data = fn(node.name for node in node_infos if not node.offline)
2562
    mc_data = fn(node.name for node in node_infos if node.master_candidate)
2563
    mc_ips_data = fn(node.primary_ip for node in node_infos
2564
                     if node.master_candidate)
2565
    node_data = fn(node_names)
2566
    node_pri_ips_data = fn(node_pri_ips)
2567
    node_snd_ips_data = fn(node_snd_ips)
2568

    
2569
    cluster = self._config_data.cluster
2570
    cluster_tags = fn(cluster.GetTags())
2571

    
2572
    hypervisor_list = fn(cluster.enabled_hypervisors)
2573
    all_hvparams = self._GetAllHvparamsStrings(constants.HYPER_TYPES)
2574

    
2575
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2576

    
2577
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2578
                  self._config_data.nodegroups.values()]
2579
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2580
    networks = ["%s %s" % (net.uuid, net.name) for net in
2581
                self._config_data.networks.values()]
2582
    networks_data = fn(utils.NiceSort(networks))
2583

    
2584
    ssconf_values = {
2585
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
2586
      constants.SS_CLUSTER_TAGS: cluster_tags,
2587
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2588
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2589
      constants.SS_MASTER_CANDIDATES: mc_data,
2590
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2591
      constants.SS_MASTER_IP: cluster.master_ip,
2592
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
2593
      constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2594
      constants.SS_MASTER_NODE: self._UnlockedGetNodeName(cluster.master_node),
2595
      constants.SS_NODE_LIST: node_data,
2596
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2597
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2598
      constants.SS_OFFLINE_NODES: off_data,
2599
      constants.SS_ONLINE_NODES: on_data,
2600
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2601
      constants.SS_INSTANCE_LIST: instance_data,
2602
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2603
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
2604
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2605
      constants.SS_UID_POOL: uid_pool,
2606
      constants.SS_NODEGROUPS: nodegroups_data,
2607
      constants.SS_NETWORKS: networks_data,
2608
      }
2609
    ssconf_values = self._ExtendByAllHvparamsStrings(ssconf_values,
2610
                                                     all_hvparams)
2611
    bad_values = [(k, v) for k, v in ssconf_values.items()
2612
                  if not isinstance(v, (str, basestring))]
2613
    if bad_values:
2614
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2615
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2616
                                      " values: %s" % err)
2617
    return ssconf_values
2618

    
2619
  @locking.ssynchronized(_config_lock, shared=1)
2620
  def GetSsconfValues(self):
2621
    """Wrapper using lock around _UnlockedGetSsconf().
2622

2623
    """
2624
    return self._UnlockedGetSsconfValues()
2625

    
2626
  @locking.ssynchronized(_config_lock, shared=1)
2627
  def GetVGName(self):
2628
    """Return the volume group name.
2629

2630
    """
2631
    return self._config_data.cluster.volume_group_name
2632

    
2633
  @locking.ssynchronized(_config_lock)
2634
  def SetVGName(self, vg_name):
2635
    """Set the volume group name.
2636

2637
    """
2638
    self._config_data.cluster.volume_group_name = vg_name
2639
    self._config_data.cluster.serial_no += 1
2640
    self._WriteConfig()
2641

    
2642
  @locking.ssynchronized(_config_lock, shared=1)
2643
  def GetDRBDHelper(self):
2644
    """Return DRBD usermode helper.
2645

2646
    """
2647
    return self._config_data.cluster.drbd_usermode_helper
2648

    
2649
  @locking.ssynchronized(_config_lock)
2650
  def SetDRBDHelper(self, drbd_helper):
2651
    """Set DRBD usermode helper.
2652

2653
    """
2654
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2655
    self._config_data.cluster.serial_no += 1
2656
    self._WriteConfig()
2657

    
2658
  @locking.ssynchronized(_config_lock, shared=1)
2659
  def GetMACPrefix(self):
2660
    """Return the mac prefix.
2661

2662
    """
2663
    return self._config_data.cluster.mac_prefix
2664

    
2665
  @locking.ssynchronized(_config_lock, shared=1)
2666
  def GetClusterInfo(self):
2667
    """Returns information about the cluster
2668

2669
    @rtype: L{objects.Cluster}
2670
    @return: the cluster object
2671

2672
    """
2673
    return self._config_data.cluster
2674

    
2675
  @locking.ssynchronized(_config_lock, shared=1)
2676
  def HasAnyDiskOfType(self, dev_type):
2677
    """Check if in there is at disk of the given type in the configuration.
2678

2679
    """
2680
    return self._config_data.HasAnyDiskOfType(dev_type)
2681

    
2682
  @locking.ssynchronized(_config_lock)
2683
  def Update(self, target, feedback_fn, ec_id=None):
2684
    """Notify function to be called after updates.
2685

2686
    This function must be called when an object (as returned by
2687
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2688
    caller wants the modifications saved to the backing store. Note
2689
    that all modified objects will be saved, but the target argument
2690
    is the one the caller wants to ensure that it's saved.
2691

2692
    @param target: an instance of either L{objects.Cluster},
2693
        L{objects.Node} or L{objects.Instance} which is existing in
2694
        the cluster
2695
    @param feedback_fn: Callable feedback function
2696

2697
    """
2698
    if self._config_data is None:
2699
      raise errors.ProgrammerError("Configuration file not read,"
2700
                                   " cannot save.")
2701
    update_serial = False
2702
    if isinstance(target, objects.Cluster):
2703
      test = target == self._config_data.cluster
2704
    elif isinstance(target, objects.Node):
2705
      test = target in self._config_data.nodes.values()
2706
      update_serial = True
2707
    elif isinstance(target, objects.Instance):
2708
      test = target in self._config_data.instances.values()
2709
    elif isinstance(target, objects.NodeGroup):
2710
      test = target in self._config_data.nodegroups.values()
2711
    elif isinstance(target, objects.Network):
2712
      test = target in self._config_data.networks.values()
2713
    else:
2714
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2715
                                   " ConfigWriter.Update" % type(target))
2716
    if not test:
2717
      raise errors.ConfigurationError("Configuration updated since object"
2718
                                      " has been read or unknown object")
2719
    target.serial_no += 1
2720
    target.mtime = now = time.time()
2721

    
2722
    if update_serial:
2723
      # for node updates, we need to increase the cluster serial too
2724
      self._config_data.cluster.serial_no += 1
2725
      self._config_data.cluster.mtime = now
2726

    
2727
    if isinstance(target, objects.Instance):
2728
      self._UnlockedReleaseDRBDMinors(target.uuid)
2729

    
2730
    if ec_id is not None:
2731
      # Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
2732
      self._UnlockedCommitTemporaryIps(ec_id)
2733

    
2734
    self._WriteConfig(feedback_fn=feedback_fn)
2735

    
2736
  @locking.ssynchronized(_config_lock)
2737
  def DropECReservations(self, ec_id):
2738
    """Drop per-execution-context reservations
2739

2740
    """
2741
    for rm in self._all_rms:
2742
      rm.DropECReservations(ec_id)
2743

    
2744
  @locking.ssynchronized(_config_lock, shared=1)
2745
  def GetAllNetworksInfo(self):
2746
    """Get configuration info of all the networks.
2747

2748
    """
2749
    return dict(self._config_data.networks)
2750

    
2751
  def _UnlockedGetNetworkList(self):
2752
    """Get the list of networks.
2753

2754
    This function is for internal use, when the config lock is already held.
2755

2756
    """
2757
    return self._config_data.networks.keys()
2758

    
2759
  @locking.ssynchronized(_config_lock, shared=1)
2760
  def GetNetworkList(self):
2761
    """Get the list of networks.
2762

2763
    @return: array of networks, ex. ["main", "vlan100", "200]
2764

2765
    """
2766
    return self._UnlockedGetNetworkList()
2767

    
2768
  @locking.ssynchronized(_config_lock, shared=1)
2769
  def GetNetworkNames(self):
2770
    """Get a list of network names
2771

2772
    """
2773
    names = [net.name
2774
             for net in self._config_data.networks.values()]
2775
    return names
2776

    
2777
  def _UnlockedGetNetwork(self, uuid):
2778
    """Returns information about a network.
2779

2780
    This function is for internal use, when the config lock is already held.
2781

2782
    """
2783
    if uuid not in self._config_data.networks:
2784
      return None
2785

    
2786
    return self._config_data.networks[uuid]
2787

    
2788
  @locking.ssynchronized(_config_lock, shared=1)
2789
  def GetNetwork(self, uuid):
2790
    """Returns information about a network.
2791

2792
    It takes the information from the configuration file.
2793

2794
    @param uuid: UUID of the network
2795

2796
    @rtype: L{objects.Network}
2797
    @return: the network object
2798

2799
    """
2800
    return self._UnlockedGetNetwork(uuid)
2801

    
2802
  @locking.ssynchronized(_config_lock)
2803
  def AddNetwork(self, net, ec_id, check_uuid=True):
2804
    """Add a network to the configuration.
2805

2806
    @type net: L{objects.Network}
2807
    @param net: the Network object to add
2808
    @type ec_id: string
2809
    @param ec_id: unique id for the job to use when creating a missing UUID
2810

2811
    """
2812
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2813
    self._WriteConfig()
2814

    
2815
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2816
    """Add a network to the configuration.
2817

2818
    """
2819
    logging.info("Adding network %s to configuration", net.name)
2820

    
2821
    if check_uuid:
2822
      self._EnsureUUID(net, ec_id)
2823

    
2824
    net.serial_no = 1
2825
    net.ctime = net.mtime = time.time()
2826
    self._config_data.networks[net.uuid] = net
2827
    self._config_data.cluster.serial_no += 1
2828

    
2829
  def _UnlockedLookupNetwork(self, target):
2830
    """Lookup a network's UUID.
2831

2832
    @type target: string
2833
    @param target: network name or UUID
2834
    @rtype: string
2835
    @return: network UUID
2836
    @raises errors.OpPrereqError: when the target network cannot be found
2837

2838
    """
2839
    if target is None:
2840
      return None
2841
    if target in self._config_data.networks:
2842
      return target
2843
    for net in self._config_data.networks.values():
2844
      if net.name == target:
2845
        return net.uuid
2846
    raise errors.OpPrereqError("Network '%s' not found" % target,
2847
                               errors.ECODE_NOENT)
2848

    
2849
  @locking.ssynchronized(_config_lock, shared=1)
2850
  def LookupNetwork(self, target):
2851
    """Lookup a network's UUID.
2852

2853
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2854

2855
    @type target: string
2856
    @param target: network name or UUID
2857
    @rtype: string
2858
    @return: network UUID
2859

2860
    """
2861
    return self._UnlockedLookupNetwork(target)
2862

    
2863
  @locking.ssynchronized(_config_lock)
2864
  def RemoveNetwork(self, network_uuid):
2865
    """Remove a network from the configuration.
2866

2867
    @type network_uuid: string
2868
    @param network_uuid: the UUID of the network to remove
2869

2870
    """
2871
    logging.info("Removing network %s from configuration", network_uuid)
2872

    
2873
    if network_uuid not in self._config_data.networks:
2874
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2875

    
2876
    del self._config_data.networks[network_uuid]
2877
    self._config_data.cluster.serial_no += 1
2878
    self._WriteConfig()
2879

    
2880
  def _UnlockedGetGroupNetParams(self, net_uuid, node_uuid):
2881
    """Get the netparams (mode, link) of a network.
2882

2883
    Get a network's netparams for a given node.
2884

2885
    @type net_uuid: string
2886
    @param net_uuid: network uuid
2887
    @type node_uuid: string
2888
    @param node_uuid: node UUID
2889
    @rtype: dict or None
2890
    @return: netparams
2891

2892
    """
2893
    node_info = self._UnlockedGetNodeInfo(node_uuid)
2894
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2895
    netparams = nodegroup_info.networks.get(net_uuid, None)
2896

    
2897
    return netparams
2898

    
2899
  @locking.ssynchronized(_config_lock, shared=1)
2900
  def GetGroupNetParams(self, net_uuid, node_uuid):
2901
    """Locking wrapper of _UnlockedGetGroupNetParams()
2902

2903
    """
2904
    return self._UnlockedGetGroupNetParams(net_uuid, node_uuid)
2905

    
2906
  @locking.ssynchronized(_config_lock, shared=1)
2907
  def CheckIPInNodeGroup(self, ip, node_uuid):
2908
    """Check IP uniqueness in nodegroup.
2909

2910
    Check networks that are connected in the node's node group
2911
    if ip is contained in any of them. Used when creating/adding
2912
    a NIC to ensure uniqueness among nodegroups.
2913

2914
    @type ip: string
2915
    @param ip: ip address
2916
    @type node_uuid: string
2917
    @param node_uuid: node UUID
2918
    @rtype: (string, dict) or (None, None)
2919
    @return: (network name, netparams)
2920

2921
    """
2922
    if ip is None:
2923
      return (None, None)
2924
    node_info = self._UnlockedGetNodeInfo(node_uuid)
2925
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2926
    for net_uuid in nodegroup_info.networks.keys():
2927
      net_info = self._UnlockedGetNetwork(net_uuid)
2928
      pool = network.AddressPool(net_info)
2929
      if pool.Contains(ip):
2930
        return (net_info.name, nodegroup_info.networks[net_uuid])
2931

    
2932
    return (None, None)