Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 2dc0acb9

History | View | Annotate | Download (95.2 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 dict 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,
75
                                       data['version'])
76

    
77

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

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

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

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

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

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

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

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

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

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

127
    """
128
    assert callable(generate_one_fn)
129

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

    
143

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

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

    
150

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

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

160
  """
161
  result = []
162

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

    
168
  return result
169

    
170

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

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

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

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

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

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

217
    """
218
    self._context = context
219

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

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

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

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

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

    
240
  @locking.ssynchronized(_config_lock, shared=1)
241
  def GetInstanceDiskParams(self, instance):
242
    """Get the disk params populated with inherit chain.
243

244
    @type instance: L{objects.Instance}
245
    @param instance: The instance we want to know the params for
246
    @return: A dict with the filled in disk params
247

248
    """
249
    node = self._UnlockedGetNodeInfo(instance.primary_node)
250
    nodegroup = self._UnlockedGetNodeGroup(node.group)
251
    return self._UnlockedGetGroupDiskParams(nodegroup)
252

    
253
  @locking.ssynchronized(_config_lock, shared=1)
254
  def GetGroupDiskParams(self, group):
255
    """Get the disk params populated with inherit chain.
256

257
    @type group: L{objects.NodeGroup}
258
    @param group: The group we want to know the params for
259
    @return: A dict with the filled in disk params
260

261
    """
262
    return self._UnlockedGetGroupDiskParams(group)
263

    
264
  def _UnlockedGetGroupDiskParams(self, group):
265
    """Get the disk params populated with inherit chain down to node-group.
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._config_data.cluster.SimpleFillDP(group.diskparams)
273

    
274
  def _UnlockedGetNetworkMACPrefix(self, net_uuid):
275
    """Return the network mac prefix if it exists or the cluster level default.
276

277
    """
278
    prefix = None
279
    if net_uuid:
280
      nobj = self._UnlockedGetNetwork(net_uuid)
281
      if nobj.mac_prefix:
282
        prefix = nobj.mac_prefix
283

    
284
    return prefix
285

    
286
  def _GenerateOneMAC(self, prefix=None):
287
    """Return a function that randomly generates a MAC suffic
288
       and appends it to the given prefix. If prefix is not given get
289
       the cluster level default.
290

291
    """
292
    if not prefix:
293
      prefix = self._config_data.cluster.mac_prefix
294

    
295
    def GenMac():
296
      byte1 = random.randrange(0, 256)
297
      byte2 = random.randrange(0, 256)
298
      byte3 = random.randrange(0, 256)
299
      mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
300
      return mac
301

    
302
    return GenMac
303

    
304
  @locking.ssynchronized(_config_lock, shared=1)
305
  def GenerateMAC(self, net_uuid, ec_id):
306
    """Generate a MAC for an instance.
307

308
    This should check the current instances for duplicates.
309

310
    """
311
    existing = self._AllMACs()
312
    prefix = self._UnlockedGetNetworkMACPrefix(net_uuid)
313
    gen_mac = self._GenerateOneMAC(prefix)
314
    return self._temporary_ids.Generate(existing, gen_mac, ec_id)
315

    
316
  @locking.ssynchronized(_config_lock, shared=1)
317
  def ReserveMAC(self, mac, ec_id):
318
    """Reserve a MAC for an instance.
319

320
    This only checks instances managed by this cluster, it does not
321
    check for potential collisions elsewhere.
322

323
    """
324
    all_macs = self._AllMACs()
325
    if mac in all_macs:
326
      raise errors.ReservationError("mac already in use")
327
    else:
328
      self._temporary_macs.Reserve(ec_id, mac)
329

    
330
  def _UnlockedCommitTemporaryIps(self, ec_id):
331
    """Commit all reserved IP address to their respective pools
332

333
    """
334
    for action, address, net_uuid in self._temporary_ips.GetECReserved(ec_id):
335
      self._UnlockedCommitIp(action, net_uuid, address)
336

    
337
  def _UnlockedCommitIp(self, action, net_uuid, address):
338
    """Commit a reserved IP address to an IP pool.
339

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

342
    """
343
    nobj = self._UnlockedGetNetwork(net_uuid)
344
    pool = network.AddressPool(nobj)
345
    if action == constants.RESERVE_ACTION:
346
      pool.Reserve(address)
347
    elif action == constants.RELEASE_ACTION:
348
      pool.Release(address)
349

    
350
  def _UnlockedReleaseIp(self, net_uuid, address, ec_id):
351
    """Give a specific IP address back to an IP pool.
352

353
    The IP address is returned to the IP pool designated by pool_id and marked
354
    as reserved.
355

356
    """
357
    self._temporary_ips.Reserve(ec_id,
358
                                (constants.RELEASE_ACTION, address, net_uuid))
359

    
360
  @locking.ssynchronized(_config_lock, shared=1)
361
  def ReleaseIp(self, net_uuid, address, ec_id):
362
    """Give a specified IP address back to an IP pool.
363

364
    This is just a wrapper around _UnlockedReleaseIp.
365

366
    """
367
    if net_uuid:
368
      self._UnlockedReleaseIp(net_uuid, address, ec_id)
369

    
370
  @locking.ssynchronized(_config_lock, shared=1)
371
  def GenerateIp(self, net_uuid, ec_id):
372
    """Find a free IPv4 address for an instance.
373

374
    """
375
    nobj = self._UnlockedGetNetwork(net_uuid)
376
    pool = network.AddressPool(nobj)
377

    
378
    def gen_one():
379
      try:
380
        ip = pool.GenerateFree()
381
      except errors.AddressPoolError:
382
        raise errors.ReservationError("Cannot generate IP. Network is full")
383
      return (constants.RESERVE_ACTION, ip, net_uuid)
384

    
385
    _, address, _ = self._temporary_ips.Generate([], gen_one, ec_id)
386
    return address
387

    
388
  def _UnlockedReserveIp(self, net_uuid, address, ec_id, check=True):
389
    """Reserve a given IPv4 address for use by an instance.
390

391
    """
392
    nobj = self._UnlockedGetNetwork(net_uuid)
393
    pool = network.AddressPool(nobj)
394
    try:
395
      isreserved = pool.IsReserved(address)
396
      isextreserved = pool.IsReserved(address, external=True)
397
    except errors.AddressPoolError:
398
      raise errors.ReservationError("IP address not in network")
399
    if isreserved:
400
      raise errors.ReservationError("IP address already in use")
401
    if check and isextreserved:
402
      raise errors.ReservationError("IP is externally reserved")
403

    
404
    return self._temporary_ips.Reserve(ec_id,
405
                                       (constants.RESERVE_ACTION,
406
                                        address, net_uuid))
407

    
408
  @locking.ssynchronized(_config_lock, shared=1)
409
  def ReserveIp(self, net_uuid, address, ec_id, check=True):
410
    """Reserve a given IPv4 address for use by an instance.
411

412
    """
413
    if net_uuid:
414
      return self._UnlockedReserveIp(net_uuid, address, ec_id, check)
415

    
416
  @locking.ssynchronized(_config_lock, shared=1)
417
  def ReserveLV(self, lv_name, ec_id):
418
    """Reserve an VG/LV pair for an instance.
419

420
    @type lv_name: string
421
    @param lv_name: the logical volume name to reserve
422

423
    """
424
    all_lvs = self._AllLVs()
425
    if lv_name in all_lvs:
426
      raise errors.ReservationError("LV already in use")
427
    else:
428
      self._temporary_lvs.Reserve(ec_id, lv_name)
429

    
430
  @locking.ssynchronized(_config_lock, shared=1)
431
  def GenerateDRBDSecret(self, ec_id):
432
    """Generate a DRBD secret.
433

434
    This checks the current disks for duplicates.
435

436
    """
437
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
438
                                            utils.GenerateSecret,
439
                                            ec_id)
440

    
441
  def _AllLVs(self):
442
    """Compute the list of all LVs.
443

444
    """
445
    lvnames = set()
446
    for instance in self._config_data.instances.values():
447
      node_data = instance.MapLVsByNode()
448
      for lv_list in node_data.values():
449
        lvnames.update(lv_list)
450
    return lvnames
451

    
452
  def _AllDisks(self):
453
    """Compute the list of all Disks (recursively, including children).
454

455
    """
456
    def DiskAndAllChildren(disk):
457
      """Returns a list containing the given disk and all of his children.
458

459
      """
460
      disks = [disk]
461
      if disk.children:
462
        for child_disk in disk.children:
463
          disks.extend(DiskAndAllChildren(child_disk))
464
      return disks
465

    
466
    disks = []
467
    for instance in self._config_data.instances.values():
468
      for disk in instance.disks:
469
        disks.extend(DiskAndAllChildren(disk))
470
    return disks
471

    
472
  def _AllNICs(self):
473
    """Compute the list of all NICs.
474

475
    """
476
    nics = []
477
    for instance in self._config_data.instances.values():
478
      nics.extend(instance.nics)
479
    return nics
480

    
481
  def _AllIDs(self, include_temporary):
482
    """Compute the list of all UUIDs and names we have.
483

484
    @type include_temporary: boolean
485
    @param include_temporary: whether to include the _temporary_ids set
486
    @rtype: set
487
    @return: a set of IDs
488

489
    """
490
    existing = set()
491
    if include_temporary:
492
      existing.update(self._temporary_ids.GetReserved())
493
    existing.update(self._AllLVs())
494
    existing.update(self._config_data.instances.keys())
495
    existing.update(self._config_data.nodes.keys())
496
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
497
    return existing
498

    
499
  def _GenerateUniqueID(self, ec_id):
500
    """Generate an unique UUID.
501

502
    This checks the current node, instances and disk names for
503
    duplicates.
504

505
    @rtype: string
506
    @return: the unique id
507

508
    """
509
    existing = self._AllIDs(include_temporary=False)
510
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
511

    
512
  @locking.ssynchronized(_config_lock, shared=1)
513
  def GenerateUniqueID(self, ec_id):
514
    """Generate an unique ID.
515

516
    This is just a wrapper over the unlocked version.
517

518
    @type ec_id: string
519
    @param ec_id: unique id for the job to reserve the id to
520

521
    """
522
    return self._GenerateUniqueID(ec_id)
523

    
524
  def _AllMACs(self):
525
    """Return all MACs present in the config.
526

527
    @rtype: list
528
    @return: the list of all MACs
529

530
    """
531
    result = []
532
    for instance in self._config_data.instances.values():
533
      for nic in instance.nics:
534
        result.append(nic.mac)
535

    
536
    return result
537

    
538
  def _AllDRBDSecrets(self):
539
    """Return all DRBD secrets present in the config.
540

541
    @rtype: list
542
    @return: the list of all DRBD secrets
543

544
    """
545
    def helper(disk, result):
546
      """Recursively gather secrets from this disk."""
547
      if disk.dev_type == constants.DT_DRBD8:
548
        result.append(disk.logical_id[5])
549
      if disk.children:
550
        for child in disk.children:
551
          helper(child, result)
552

    
553
    result = []
554
    for instance in self._config_data.instances.values():
555
      for disk in instance.disks:
556
        helper(disk, result)
557

    
558
    return result
559

    
560
  def _CheckDiskIDs(self, disk, l_ids):
561
    """Compute duplicate disk IDs
562

563
    @type disk: L{objects.Disk}
564
    @param disk: the disk at which to start searching
565
    @type l_ids: list
566
    @param l_ids: list of current logical ids
567
    @rtype: list
568
    @return: a list of error messages
569

570
    """
571
    result = []
572
    if disk.logical_id is not None:
573
      if disk.logical_id in l_ids:
574
        result.append("duplicate logical id %s" % str(disk.logical_id))
575
      else:
576
        l_ids.append(disk.logical_id)
577

    
578
    if disk.children:
579
      for child in disk.children:
580
        result.extend(self._CheckDiskIDs(child, l_ids))
581
    return result
582

    
583
  def _UnlockedVerifyConfig(self):
584
    """Verify function.
585

586
    @rtype: list
587
    @return: a list of error messages; a non-empty list signifies
588
        configuration errors
589

590
    """
591
    # pylint: disable=R0914
592
    result = []
593
    seen_macs = []
594
    ports = {}
595
    data = self._config_data
596
    cluster = data.cluster
597
    seen_lids = []
598

    
599
    # global cluster checks
600
    if not cluster.enabled_hypervisors:
601
      result.append("enabled hypervisors list doesn't have any entries")
602
    invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
603
    if invalid_hvs:
604
      result.append("enabled hypervisors contains invalid entries: %s" %
605
                    utils.CommaJoin(invalid_hvs))
606
    missing_hvp = (set(cluster.enabled_hypervisors) -
607
                   set(cluster.hvparams.keys()))
608
    if missing_hvp:
609
      result.append("hypervisor parameters missing for the enabled"
610
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
611

    
612
    if not cluster.enabled_disk_templates:
613
      result.append("enabled disk templates list doesn't have any entries")
614
    invalid_disk_templates = set(cluster.enabled_disk_templates) \
615
                               - constants.DISK_TEMPLATES
616
    if invalid_disk_templates:
617
      result.append("enabled disk templates list contains invalid entries:"
618
                    " %s" % utils.CommaJoin(invalid_disk_templates))
619

    
620
    if cluster.master_node not in data.nodes:
621
      result.append("cluster has invalid primary node '%s'" %
622
                    cluster.master_node)
623

    
624
    def _helper(owner, attr, value, template):
625
      try:
626
        utils.ForceDictType(value, template)
627
      except errors.GenericError, err:
628
        result.append("%s has invalid %s: %s" % (owner, attr, err))
629

    
630
    def _helper_nic(owner, params):
631
      try:
632
        objects.NIC.CheckParameterSyntax(params)
633
      except errors.ConfigurationError, err:
634
        result.append("%s has invalid nicparams: %s" % (owner, err))
635

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

    
659
    def _helper_ispecs(owner, parentkey, params):
660
      for (key, value) in params.items():
661
        fullkey = "/".join([parentkey, key])
662
        _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
663

    
664
    # check cluster parameters
665
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
666
            constants.BES_PARAMETER_TYPES)
667
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
668
            constants.NICS_PARAMETER_TYPES)
669
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
670
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
671
            constants.NDS_PARAMETER_TYPES)
672
    _helper_ipolicy("cluster", cluster.ipolicy, True)
673

    
674
    if constants.DT_RBD in cluster.diskparams:
675
      access = cluster.diskparams[constants.DT_RBD][constants.RBD_ACCESS]
676
      if access not in constants.DISK_VALID_ACCESS_MODES:
677
        result.append(
678
          "Invalid value of '%s:%s': '%s' (expected one of %s)" % (
679
            constants.DT_RBD, constants.RBD_ACCESS, access,
680
            utils.CommaJoin(constants.DISK_VALID_ACCESS_MODES)
681
          )
682
        )
683

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

    
710
      # disk template checks
711
      if not instance.disk_template in data.cluster.enabled_disk_templates:
712
        result.append("instance '%s' uses the disabled disk template '%s'." %
713
                      (instance.name, instance.disk_template))
714

    
715
      # parameter checks
716
      if instance.beparams:
717
        _helper("instance %s" % instance.name, "beparams",
718
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
719

    
720
      # gather the drbd ports for duplicate checks
721
      for (idx, dsk) in enumerate(instance.disks):
722
        if dsk.dev_type in constants.DTS_DRBD:
723
          tcp_port = dsk.logical_id[2]
724
          if tcp_port not in ports:
725
            ports[tcp_port] = []
726
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
727
      # gather network port reservation
728
      net_port = getattr(instance, "network_port", None)
729
      if net_port is not None:
730
        if net_port not in ports:
731
          ports[net_port] = []
732
        ports[net_port].append((instance.name, "network port"))
733

    
734
      # instance disk verify
735
      for idx, disk in enumerate(instance.disks):
736
        result.extend(["instance '%s' disk %d error: %s" %
737
                       (instance.name, idx, msg) for msg in disk.Verify()])
738
        result.extend(self._CheckDiskIDs(disk, seen_lids))
739

    
740
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
741
      if wrong_names:
742
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
743
                         (idx, exp_name, actual_name))
744
                        for (idx, exp_name, actual_name) in wrong_names)
745

    
746
        result.append("Instance '%s' has wrongly named disks: %s" %
747
                      (instance.name, tmp))
748

    
749
    # cluster-wide pool of free ports
750
    for free_port in cluster.tcpudp_port_pool:
751
      if free_port not in ports:
752
        ports[free_port] = []
753
      ports[free_port].append(("cluster", "port marked as free"))
754

    
755
    # compute tcp/udp duplicate ports
756
    keys = ports.keys()
757
    keys.sort()
758
    for pnum in keys:
759
      pdata = ports[pnum]
760
      if len(pdata) > 1:
761
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
762
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
763

    
764
    # highest used tcp port check
765
    if keys:
766
      if keys[-1] > cluster.highest_used_port:
767
        result.append("Highest used port mismatch, saved %s, computed %s" %
768
                      (cluster.highest_used_port, keys[-1]))
769

    
770
    if not data.nodes[cluster.master_node].master_candidate:
771
      result.append("Master node is not a master candidate")
772

    
773
    # master candidate checks
774
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
775
    if mc_now < mc_max:
776
      result.append("Not enough master candidates: actual %d, target %d" %
777
                    (mc_now, mc_max))
778

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

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

    
823
    # drbd minors check
824
    _, duplicates = self._UnlockedComputeDRBDMap()
825
    for node, minor, instance_a, instance_b in duplicates:
826
      result.append("DRBD minor %d on node %s is assigned twice to instances"
827
                    " %s and %s" % (minor, node, instance_a, instance_b))
828

    
829
    # IP checks
830
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
831
    ips = {}
832

    
833
    def _AddIpAddress(ip, name):
834
      ips.setdefault(ip, []).append(name)
835

    
836
    _AddIpAddress(cluster.master_ip, "cluster_ip")
837

    
838
    for node in data.nodes.values():
839
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
840
      if node.secondary_ip != node.primary_ip:
841
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
842

    
843
    for instance in data.instances.values():
844
      for idx, nic in enumerate(instance.nics):
845
        if nic.ip is None:
846
          continue
847

    
848
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
849
        nic_mode = nicparams[constants.NIC_MODE]
850
        nic_link = nicparams[constants.NIC_LINK]
851

    
852
        if nic_mode == constants.NIC_MODE_BRIDGED:
853
          link = "bridge:%s" % nic_link
854
        elif nic_mode == constants.NIC_MODE_ROUTED:
855
          link = "route:%s" % nic_link
856
        else:
857
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
858

    
859
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
860
                      "instance:%s/nic:%d" % (instance.name, idx))
861

    
862
    for ip, owners in ips.items():
863
      if len(owners) > 1:
864
        result.append("IP address %s is used by multiple owners: %s" %
865
                      (ip, utils.CommaJoin(owners)))
866

    
867
    return result
868

    
869
  @locking.ssynchronized(_config_lock, shared=1)
870
  def VerifyConfig(self):
871
    """Verify function.
872

873
    This is just a wrapper over L{_UnlockedVerifyConfig}.
874

875
    @rtype: list
876
    @return: a list of error messages; a non-empty list signifies
877
        configuration errors
878

879
    """
880
    return self._UnlockedVerifyConfig()
881

    
882
  @locking.ssynchronized(_config_lock)
883
  def AddTcpUdpPort(self, port):
884
    """Adds a new port to the available port pool.
885

886
    @warning: this method does not "flush" the configuration (via
887
        L{_WriteConfig}); callers should do that themselves once the
888
        configuration is stable
889

890
    """
891
    if not isinstance(port, int):
892
      raise errors.ProgrammerError("Invalid type passed for port")
893

    
894
    self._config_data.cluster.tcpudp_port_pool.add(port)
895

    
896
  @locking.ssynchronized(_config_lock, shared=1)
897
  def GetPortList(self):
898
    """Returns a copy of the current port list.
899

900
    """
901
    return self._config_data.cluster.tcpudp_port_pool.copy()
902

    
903
  @locking.ssynchronized(_config_lock)
904
  def AllocatePort(self):
905
    """Allocate a port.
906

907
    The port will be taken from the available port pool or from the
908
    default port range (and in this case we increase
909
    highest_used_port).
910

911
    """
912
    # If there are TCP/IP ports configured, we use them first.
913
    if self._config_data.cluster.tcpudp_port_pool:
914
      port = self._config_data.cluster.tcpudp_port_pool.pop()
915
    else:
916
      port = self._config_data.cluster.highest_used_port + 1
917
      if port >= constants.LAST_DRBD_PORT:
918
        raise errors.ConfigurationError("The highest used port is greater"
919
                                        " than %s. Aborting." %
920
                                        constants.LAST_DRBD_PORT)
921
      self._config_data.cluster.highest_used_port = port
922

    
923
    self._WriteConfig()
924
    return port
925

    
926
  def _UnlockedComputeDRBDMap(self):
927
    """Compute the used DRBD minor/nodes.
928

929
    @rtype: (dict, list)
930
    @return: dictionary of node_uuid: dict of minor: instance_uuid;
931
        the returned dict will have all the nodes in it (even if with
932
        an empty list), and a list of duplicates; if the duplicates
933
        list is not empty, the configuration is corrupted and its caller
934
        should raise an exception
935

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

    
956
    duplicates = []
957
    my_dict = dict((node_uuid, {}) for node_uuid in self._config_data.nodes)
958
    for instance in self._config_data.instances.itervalues():
959
      for disk in instance.disks:
960
        duplicates.extend(_AppendUsedMinors(self._UnlockedGetNodeName,
961
                                            instance, disk, my_dict))
962
    for (node_uuid, minor), inst_uuid in self._temporary_drbds.iteritems():
963
      if minor in my_dict[node_uuid] and my_dict[node_uuid][minor] != inst_uuid:
964
        duplicates.append((node_uuid, minor, inst_uuid,
965
                           my_dict[node_uuid][minor]))
966
      else:
967
        my_dict[node_uuid][minor] = inst_uuid
968
    return my_dict, duplicates
969

    
970
  @locking.ssynchronized(_config_lock)
971
  def ComputeDRBDMap(self):
972
    """Compute the used DRBD minor/nodes.
973

974
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
975

976
    @return: dictionary of node_uuid: dict of minor: instance_uuid;
977
        the returned dict will have all the nodes in it (even if with
978
        an empty list).
979

980
    """
981
    d_map, duplicates = self._UnlockedComputeDRBDMap()
982
    if duplicates:
983
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
984
                                      str(duplicates))
985
    return d_map
986

    
987
  @locking.ssynchronized(_config_lock)
988
  def AllocateDRBDMinor(self, node_uuids, inst_uuid):
989
    """Allocate a drbd minor.
990

991
    The free minor will be automatically computed from the existing
992
    devices. A node can be given multiple times in order to allocate
993
    multiple minors. The result is the list of minors, in the same
994
    order as the passed nodes.
995

996
    @type inst_uuid: string
997
    @param inst_uuid: the instance for which we allocate minors
998

999
    """
1000
    assert isinstance(inst_uuid, basestring), \
1001
           "Invalid argument '%s' passed to AllocateDRBDMinor" % inst_uuid
1002

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

    
1043
  def _UnlockedReleaseDRBDMinors(self, inst_uuid):
1044
    """Release temporary drbd minors allocated for a given instance.
1045

1046
    @type inst_uuid: string
1047
    @param inst_uuid: the instance for which temporary minors should be
1048
                      released
1049

1050
    """
1051
    assert isinstance(inst_uuid, basestring), \
1052
           "Invalid argument passed to ReleaseDRBDMinors"
1053
    for key, uuid in self._temporary_drbds.items():
1054
      if uuid == inst_uuid:
1055
        del self._temporary_drbds[key]
1056

    
1057
  @locking.ssynchronized(_config_lock)
1058
  def ReleaseDRBDMinors(self, inst_uuid):
1059
    """Release temporary drbd minors allocated for a given instance.
1060

1061
    This should be called on the error paths, on the success paths
1062
    it's automatically called by the ConfigWriter add and update
1063
    functions.
1064

1065
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1066

1067
    @type inst_uuid: string
1068
    @param inst_uuid: the instance for which temporary minors should be
1069
                      released
1070

1071
    """
1072
    self._UnlockedReleaseDRBDMinors(inst_uuid)
1073

    
1074
  @locking.ssynchronized(_config_lock, shared=1)
1075
  def GetConfigVersion(self):
1076
    """Get the configuration version.
1077

1078
    @return: Config version
1079

1080
    """
1081
    return self._config_data.version
1082

    
1083
  @locking.ssynchronized(_config_lock, shared=1)
1084
  def GetClusterName(self):
1085
    """Get cluster name.
1086

1087
    @return: Cluster name
1088

1089
    """
1090
    return self._config_data.cluster.cluster_name
1091

    
1092
  @locking.ssynchronized(_config_lock, shared=1)
1093
  def GetMasterNode(self):
1094
    """Get the UUID of the master node for this cluster.
1095

1096
    @return: Master node UUID
1097

1098
    """
1099
    return self._config_data.cluster.master_node
1100

    
1101
  @locking.ssynchronized(_config_lock, shared=1)
1102
  def GetMasterNodeName(self):
1103
    """Get the hostname of the master node for this cluster.
1104

1105
    @return: Master node hostname
1106

1107
    """
1108
    return self._UnlockedGetNodeName(self._config_data.cluster.master_node)
1109

    
1110
  @locking.ssynchronized(_config_lock, shared=1)
1111
  def GetMasterNodeInfo(self):
1112
    """Get the master node information for this cluster.
1113

1114
    @rtype: objects.Node
1115
    @return: Master node L{objects.Node} object
1116

1117
    """
1118
    return self._UnlockedGetNodeInfo(self._config_data.cluster.master_node)
1119

    
1120
  @locking.ssynchronized(_config_lock, shared=1)
1121
  def GetMasterIP(self):
1122
    """Get the IP of the master node for this cluster.
1123

1124
    @return: Master IP
1125

1126
    """
1127
    return self._config_data.cluster.master_ip
1128

    
1129
  @locking.ssynchronized(_config_lock, shared=1)
1130
  def GetMasterNetdev(self):
1131
    """Get the master network device for this cluster.
1132

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

    
1136
  @locking.ssynchronized(_config_lock, shared=1)
1137
  def GetMasterNetmask(self):
1138
    """Get the netmask of the master node for this cluster.
1139

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

    
1143
  @locking.ssynchronized(_config_lock, shared=1)
1144
  def GetUseExternalMipScript(self):
1145
    """Get flag representing whether to use the external master IP setup script.
1146

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

    
1150
  @locking.ssynchronized(_config_lock, shared=1)
1151
  def GetFileStorageDir(self):
1152
    """Get the file storage dir for this cluster.
1153

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

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

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

    
1164
  @locking.ssynchronized(_config_lock, shared=1)
1165
  def GetHypervisorType(self):
1166
    """Get the hypervisor type for this cluster.
1167

1168
    """
1169
    return self._config_data.cluster.enabled_hypervisors[0]
1170

    
1171
  @locking.ssynchronized(_config_lock, shared=1)
1172
  def GetRsaHostKey(self):
1173
    """Return the rsa hostkey from the config.
1174

1175
    @rtype: string
1176
    @return: the rsa hostkey
1177

1178
    """
1179
    return self._config_data.cluster.rsahostkeypub
1180

    
1181
  @locking.ssynchronized(_config_lock, shared=1)
1182
  def GetDsaHostKey(self):
1183
    """Return the dsa hostkey from the config.
1184

1185
    @rtype: string
1186
    @return: the dsa hostkey
1187

1188
    """
1189
    return self._config_data.cluster.dsahostkeypub
1190

    
1191
  @locking.ssynchronized(_config_lock, shared=1)
1192
  def GetDefaultIAllocator(self):
1193
    """Get the default instance allocator for this cluster.
1194

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

    
1198
  @locking.ssynchronized(_config_lock, shared=1)
1199
  def GetPrimaryIPFamily(self):
1200
    """Get cluster primary ip family.
1201

1202
    @return: primary ip family
1203

1204
    """
1205
    return self._config_data.cluster.primary_ip_family
1206

    
1207
  @locking.ssynchronized(_config_lock, shared=1)
1208
  def GetMasterNetworkParameters(self):
1209
    """Get network parameters of the master node.
1210

1211
    @rtype: L{object.MasterNetworkParameters}
1212
    @return: network parameters of the master node
1213

1214
    """
1215
    cluster = self._config_data.cluster
1216
    result = objects.MasterNetworkParameters(
1217
      uuid=cluster.master_node, ip=cluster.master_ip,
1218
      netmask=cluster.master_netmask, netdev=cluster.master_netdev,
1219
      ip_family=cluster.primary_ip_family)
1220

    
1221
    return result
1222

    
1223
  @locking.ssynchronized(_config_lock)
1224
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1225
    """Add a node group to the configuration.
1226

1227
    This method calls group.UpgradeConfig() to fill any missing attributes
1228
    according to their default values.
1229

1230
    @type group: L{objects.NodeGroup}
1231
    @param group: the NodeGroup object to add
1232
    @type ec_id: string
1233
    @param ec_id: unique id for the job to use when creating a missing UUID
1234
    @type check_uuid: bool
1235
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1236
                       it does, ensure that it does not exist in the
1237
                       configuration already
1238

1239
    """
1240
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1241
    self._WriteConfig()
1242

    
1243
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1244
    """Add a node group to the configuration.
1245

1246
    """
1247
    logging.info("Adding node group %s to configuration", group.name)
1248

    
1249
    # Some code might need to add a node group with a pre-populated UUID
1250
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1251
    # the "does this UUID" exist already check.
1252
    if check_uuid:
1253
      self._EnsureUUID(group, ec_id)
1254

    
1255
    try:
1256
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1257
    except errors.OpPrereqError:
1258
      pass
1259
    else:
1260
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1261
                                 " node group (UUID: %s)" %
1262
                                 (group.name, existing_uuid),
1263
                                 errors.ECODE_EXISTS)
1264

    
1265
    group.serial_no = 1
1266
    group.ctime = group.mtime = time.time()
1267
    group.UpgradeConfig()
1268

    
1269
    self._config_data.nodegroups[group.uuid] = group
1270
    self._config_data.cluster.serial_no += 1
1271

    
1272
  @locking.ssynchronized(_config_lock)
1273
  def RemoveNodeGroup(self, group_uuid):
1274
    """Remove a node group from the configuration.
1275

1276
    @type group_uuid: string
1277
    @param group_uuid: the UUID of the node group to remove
1278

1279
    """
1280
    logging.info("Removing node group %s from configuration", group_uuid)
1281

    
1282
    if group_uuid not in self._config_data.nodegroups:
1283
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1284

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

    
1288
    del self._config_data.nodegroups[group_uuid]
1289
    self._config_data.cluster.serial_no += 1
1290
    self._WriteConfig()
1291

    
1292
  def _UnlockedLookupNodeGroup(self, target):
1293
    """Lookup a node group's UUID.
1294

1295
    @type target: string or None
1296
    @param target: group name or UUID or None to look for the default
1297
    @rtype: string
1298
    @return: nodegroup UUID
1299
    @raises errors.OpPrereqError: when the target group cannot be found
1300

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

    
1316
  @locking.ssynchronized(_config_lock, shared=1)
1317
  def LookupNodeGroup(self, target):
1318
    """Lookup a node group's UUID.
1319

1320
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1321

1322
    @type target: string or None
1323
    @param target: group name or UUID or None to look for the default
1324
    @rtype: string
1325
    @return: nodegroup UUID
1326

1327
    """
1328
    return self._UnlockedLookupNodeGroup(target)
1329

    
1330
  def _UnlockedGetNodeGroup(self, uuid):
1331
    """Lookup a node group.
1332

1333
    @type uuid: string
1334
    @param uuid: group UUID
1335
    @rtype: L{objects.NodeGroup} or None
1336
    @return: nodegroup object, or None if not found
1337

1338
    """
1339
    if uuid not in self._config_data.nodegroups:
1340
      return None
1341

    
1342
    return self._config_data.nodegroups[uuid]
1343

    
1344
  @locking.ssynchronized(_config_lock, shared=1)
1345
  def GetNodeGroup(self, uuid):
1346
    """Lookup a node group.
1347

1348
    @type uuid: string
1349
    @param uuid: group UUID
1350
    @rtype: L{objects.NodeGroup} or None
1351
    @return: nodegroup object, or None if not found
1352

1353
    """
1354
    return self._UnlockedGetNodeGroup(uuid)
1355

    
1356
  @locking.ssynchronized(_config_lock, shared=1)
1357
  def GetAllNodeGroupsInfo(self):
1358
    """Get the configuration of all node groups.
1359

1360
    """
1361
    return dict(self._config_data.nodegroups)
1362

    
1363
  @locking.ssynchronized(_config_lock, shared=1)
1364
  def GetNodeGroupList(self):
1365
    """Get a list of node groups.
1366

1367
    """
1368
    return self._config_data.nodegroups.keys()
1369

    
1370
  @locking.ssynchronized(_config_lock, shared=1)
1371
  def GetNodeGroupMembersByNodes(self, nodes):
1372
    """Get nodes which are member in the same nodegroups as the given nodes.
1373

1374
    """
1375
    ngfn = lambda node_uuid: self._UnlockedGetNodeInfo(node_uuid).group
1376
    return frozenset(member_uuid
1377
                     for node_uuid in nodes
1378
                     for member_uuid in
1379
                       self._UnlockedGetNodeGroup(ngfn(node_uuid)).members)
1380

    
1381
  @locking.ssynchronized(_config_lock, shared=1)
1382
  def GetMultiNodeGroupInfo(self, group_uuids):
1383
    """Get the configuration of multiple node groups.
1384

1385
    @param group_uuids: List of node group UUIDs
1386
    @rtype: list
1387
    @return: List of tuples of (group_uuid, group_info)
1388

1389
    """
1390
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1391

    
1392
  @locking.ssynchronized(_config_lock)
1393
  def AddInstance(self, instance, ec_id):
1394
    """Add an instance to the config.
1395

1396
    This should be used after creating a new instance.
1397

1398
    @type instance: L{objects.Instance}
1399
    @param instance: the instance object
1400

1401
    """
1402
    if not isinstance(instance, objects.Instance):
1403
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1404

    
1405
    if instance.disk_template != constants.DT_DISKLESS:
1406
      all_lvs = instance.MapLVsByNode()
1407
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1408

    
1409
    all_macs = self._AllMACs()
1410
    for nic in instance.nics:
1411
      if nic.mac in all_macs:
1412
        raise errors.ConfigurationError("Cannot add instance %s:"
1413
                                        " MAC address '%s' already in use." %
1414
                                        (instance.name, nic.mac))
1415

    
1416
    self._CheckUniqueUUID(instance, include_temporary=False)
1417

    
1418
    instance.serial_no = 1
1419
    instance.ctime = instance.mtime = time.time()
1420
    self._config_data.instances[instance.uuid] = instance
1421
    self._config_data.cluster.serial_no += 1
1422
    self._UnlockedReleaseDRBDMinors(instance.uuid)
1423
    self._UnlockedCommitTemporaryIps(ec_id)
1424
    self._WriteConfig()
1425

    
1426
  def _EnsureUUID(self, item, ec_id):
1427
    """Ensures a given object has a valid UUID.
1428

1429
    @param item: the instance or node to be checked
1430
    @param ec_id: the execution context id for the uuid reservation
1431

1432
    """
1433
    if not item.uuid:
1434
      item.uuid = self._GenerateUniqueID(ec_id)
1435
    else:
1436
      self._CheckUniqueUUID(item, include_temporary=True)
1437

    
1438
  def _CheckUniqueUUID(self, item, include_temporary):
1439
    """Checks that the UUID of the given object is unique.
1440

1441
    @param item: the instance or node to be checked
1442
    @param include_temporary: whether temporarily generated UUID's should be
1443
              included in the check. If the UUID of the item to be checked is
1444
              a temporarily generated one, this has to be C{False}.
1445

1446
    """
1447
    if not item.uuid:
1448
      raise errors.ConfigurationError("'%s' must have an UUID" % (item.name,))
1449
    if item.uuid in self._AllIDs(include_temporary=include_temporary):
1450
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1451
                                      " in use" % (item.name, item.uuid))
1452

    
1453
  def _SetInstanceStatus(self, inst_uuid, status, disks_active):
1454
    """Set the instance's status to a given value.
1455

1456
    """
1457
    if inst_uuid not in self._config_data.instances:
1458
      raise errors.ConfigurationError("Unknown instance '%s'" %
1459
                                      inst_uuid)
1460
    instance = self._config_data.instances[inst_uuid]
1461

    
1462
    if status is None:
1463
      status = instance.admin_state
1464
    if disks_active is None:
1465
      disks_active = instance.disks_active
1466

    
1467
    assert status in constants.ADMINST_ALL, \
1468
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1469

    
1470
    if instance.admin_state != status or \
1471
       instance.disks_active != disks_active:
1472
      instance.admin_state = status
1473
      instance.disks_active = disks_active
1474
      instance.serial_no += 1
1475
      instance.mtime = time.time()
1476
      self._WriteConfig()
1477

    
1478
  @locking.ssynchronized(_config_lock)
1479
  def MarkInstanceUp(self, inst_uuid):
1480
    """Mark the instance status to up in the config.
1481

1482
    This also sets the instance disks active flag.
1483

1484
    """
1485
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_UP, True)
1486

    
1487
  @locking.ssynchronized(_config_lock)
1488
  def MarkInstanceOffline(self, inst_uuid):
1489
    """Mark the instance status to down in the config.
1490

1491
    This also clears the instance disks active flag.
1492

1493
    """
1494
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_OFFLINE, False)
1495

    
1496
  @locking.ssynchronized(_config_lock)
1497
  def RemoveInstance(self, inst_uuid):
1498
    """Remove the instance from the configuration.
1499

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

    
1504
    # If a network port has been allocated to the instance,
1505
    # return it to the pool of free ports.
1506
    inst = self._config_data.instances[inst_uuid]
1507
    network_port = getattr(inst, "network_port", None)
1508
    if network_port is not None:
1509
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1510

    
1511
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1512

    
1513
    for nic in instance.nics:
1514
      if nic.network and nic.ip:
1515
        # Return all IP addresses to the respective address pools
1516
        self._UnlockedCommitIp(constants.RELEASE_ACTION, nic.network, nic.ip)
1517

    
1518
    del self._config_data.instances[inst_uuid]
1519
    self._config_data.cluster.serial_no += 1
1520
    self._WriteConfig()
1521

    
1522
  @locking.ssynchronized(_config_lock)
1523
  def RenameInstance(self, inst_uuid, new_name):
1524
    """Rename an instance.
1525

1526
    This needs to be done in ConfigWriter and not by RemoveInstance
1527
    combined with AddInstance as only we can guarantee an atomic
1528
    rename.
1529

1530
    """
1531
    if inst_uuid not in self._config_data.instances:
1532
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1533

    
1534
    inst = self._config_data.instances[inst_uuid]
1535
    inst.name = new_name
1536

    
1537
    for (_, disk) in enumerate(inst.disks):
1538
      if disk.dev_type in [constants.DT_FILE, constants.DT_SHARED_FILE]:
1539
        # rename the file paths in logical and physical id
1540
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1541
        disk.logical_id = (disk.logical_id[0],
1542
                           utils.PathJoin(file_storage_dir, inst.name,
1543
                                          os.path.basename(disk.logical_id[1])))
1544

    
1545
    # Force update of ssconf files
1546
    self._config_data.cluster.serial_no += 1
1547

    
1548
    self._WriteConfig()
1549

    
1550
  @locking.ssynchronized(_config_lock)
1551
  def MarkInstanceDown(self, inst_uuid):
1552
    """Mark the status of an instance to down in the configuration.
1553

1554
    This does not touch the instance disks active flag, as shut down instances
1555
    can still have active disks.
1556

1557
    """
1558
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_DOWN, None)
1559

    
1560
  @locking.ssynchronized(_config_lock)
1561
  def MarkInstanceDisksActive(self, inst_uuid):
1562
    """Mark the status of instance disks active.
1563

1564
    """
1565
    self._SetInstanceStatus(inst_uuid, None, True)
1566

    
1567
  @locking.ssynchronized(_config_lock)
1568
  def MarkInstanceDisksInactive(self, inst_uuid):
1569
    """Mark the status of instance disks inactive.
1570

1571
    """
1572
    self._SetInstanceStatus(inst_uuid, None, False)
1573

    
1574
  def _UnlockedGetInstanceList(self):
1575
    """Get the list of instances.
1576

1577
    This function is for internal use, when the config lock is already held.
1578

1579
    """
1580
    return self._config_data.instances.keys()
1581

    
1582
  @locking.ssynchronized(_config_lock, shared=1)
1583
  def GetInstanceList(self):
1584
    """Get the list of instances.
1585

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

1588
    """
1589
    return self._UnlockedGetInstanceList()
1590

    
1591
  def ExpandInstanceName(self, short_name):
1592
    """Attempt to expand an incomplete instance name.
1593

1594
    """
1595
    # Locking is done in L{ConfigWriter.GetAllInstancesInfo}
1596
    all_insts = self.GetAllInstancesInfo().values()
1597
    expanded_name = _MatchNameComponentIgnoreCase(
1598
                      short_name, [inst.name for inst in all_insts])
1599

    
1600
    if expanded_name is not None:
1601
      # there has to be exactly one instance with that name
1602
      inst = (filter(lambda n: n.name == expanded_name, all_insts)[0])
1603
      return (inst.uuid, inst.name)
1604
    else:
1605
      return (None, None)
1606

    
1607
  def _UnlockedGetInstanceInfo(self, inst_uuid):
1608
    """Returns information about an instance.
1609

1610
    This function is for internal use, when the config lock is already held.
1611

1612
    """
1613
    if inst_uuid not in self._config_data.instances:
1614
      return None
1615

    
1616
    return self._config_data.instances[inst_uuid]
1617

    
1618
  @locking.ssynchronized(_config_lock, shared=1)
1619
  def GetInstanceInfo(self, inst_uuid):
1620
    """Returns information about an instance.
1621

1622
    It takes the information from the configuration file. Other information of
1623
    an instance are taken from the live systems.
1624

1625
    @param inst_uuid: UUID of the instance
1626

1627
    @rtype: L{objects.Instance}
1628
    @return: the instance object
1629

1630
    """
1631
    return self._UnlockedGetInstanceInfo(inst_uuid)
1632

    
1633
  @locking.ssynchronized(_config_lock, shared=1)
1634
  def GetInstanceNodeGroups(self, inst_uuid, primary_only=False):
1635
    """Returns set of node group UUIDs for instance's nodes.
1636

1637
    @rtype: frozenset
1638

1639
    """
1640
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1641
    if not instance:
1642
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1643

    
1644
    if primary_only:
1645
      nodes = [instance.primary_node]
1646
    else:
1647
      nodes = instance.all_nodes
1648

    
1649
    return frozenset(self._UnlockedGetNodeInfo(node_uuid).group
1650
                     for node_uuid in nodes)
1651

    
1652
  @locking.ssynchronized(_config_lock, shared=1)
1653
  def GetInstanceNetworks(self, inst_uuid):
1654
    """Returns set of network UUIDs for instance's nics.
1655

1656
    @rtype: frozenset
1657

1658
    """
1659
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1660
    if not instance:
1661
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1662

    
1663
    networks = set()
1664
    for nic in instance.nics:
1665
      if nic.network:
1666
        networks.add(nic.network)
1667

    
1668
    return frozenset(networks)
1669

    
1670
  @locking.ssynchronized(_config_lock, shared=1)
1671
  def GetMultiInstanceInfo(self, inst_uuids):
1672
    """Get the configuration of multiple instances.
1673

1674
    @param inst_uuids: list of instance UUIDs
1675
    @rtype: list
1676
    @return: list of tuples (instance UUID, instance_info), where
1677
        instance_info is what would GetInstanceInfo return for the
1678
        node, while keeping the original order
1679

1680
    """
1681
    return [(uuid, self._UnlockedGetInstanceInfo(uuid)) for uuid in inst_uuids]
1682

    
1683
  @locking.ssynchronized(_config_lock, shared=1)
1684
  def GetMultiInstanceInfoByName(self, inst_names):
1685
    """Get the configuration of multiple instances.
1686

1687
    @param inst_names: list of instance names
1688
    @rtype: list
1689
    @return: list of tuples (instance, instance_info), where
1690
        instance_info is what would GetInstanceInfo return for the
1691
        node, while keeping the original order
1692

1693
    """
1694
    result = []
1695
    for name in inst_names:
1696
      instance = self._UnlockedGetInstanceInfoByName(name)
1697
      result.append((instance.uuid, instance))
1698
    return result
1699

    
1700
  @locking.ssynchronized(_config_lock, shared=1)
1701
  def GetAllInstancesInfo(self):
1702
    """Get the configuration of all instances.
1703

1704
    @rtype: dict
1705
    @return: dict of (instance, instance_info), where instance_info is what
1706
              would GetInstanceInfo return for the node
1707

1708
    """
1709
    return self._UnlockedGetAllInstancesInfo()
1710

    
1711
  def _UnlockedGetAllInstancesInfo(self):
1712
    my_dict = dict([(inst_uuid, self._UnlockedGetInstanceInfo(inst_uuid))
1713
                    for inst_uuid in self._UnlockedGetInstanceList()])
1714
    return my_dict
1715

    
1716
  @locking.ssynchronized(_config_lock, shared=1)
1717
  def GetInstancesInfoByFilter(self, filter_fn):
1718
    """Get instance configuration with a filter.
1719

1720
    @type filter_fn: callable
1721
    @param filter_fn: Filter function receiving instance object as parameter,
1722
      returning boolean. Important: this function is called while the
1723
      configuration locks is held. It must not do any complex work or call
1724
      functions potentially leading to a deadlock. Ideally it doesn't call any
1725
      other functions and just compares instance attributes.
1726

1727
    """
1728
    return dict((uuid, inst)
1729
                for (uuid, inst) in self._config_data.instances.items()
1730
                if filter_fn(inst))
1731

    
1732
  @locking.ssynchronized(_config_lock, shared=1)
1733
  def GetInstanceInfoByName(self, inst_name):
1734
    """Get the L{objects.Instance} object for a named instance.
1735

1736
    @param inst_name: name of the instance to get information for
1737
    @type inst_name: string
1738
    @return: the corresponding L{objects.Instance} instance or None if no
1739
          information is available
1740

1741
    """
1742
    return self._UnlockedGetInstanceInfoByName(inst_name)
1743

    
1744
  def _UnlockedGetInstanceInfoByName(self, inst_name):
1745
    for inst in self._UnlockedGetAllInstancesInfo().values():
1746
      if inst.name == inst_name:
1747
        return inst
1748
    return None
1749

    
1750
  def _UnlockedGetInstanceName(self, inst_uuid):
1751
    inst_info = self._UnlockedGetInstanceInfo(inst_uuid)
1752
    if inst_info is None:
1753
      raise errors.OpExecError("Unknown instance: %s" % inst_uuid)
1754
    return inst_info.name
1755

    
1756
  @locking.ssynchronized(_config_lock, shared=1)
1757
  def GetInstanceName(self, inst_uuid):
1758
    """Gets the instance name for the passed instance.
1759

1760
    @param inst_uuid: instance UUID to get name for
1761
    @type inst_uuid: string
1762
    @rtype: string
1763
    @return: instance name
1764

1765
    """
1766
    return self._UnlockedGetInstanceName(inst_uuid)
1767

    
1768
  @locking.ssynchronized(_config_lock, shared=1)
1769
  def GetInstanceNames(self, inst_uuids):
1770
    """Gets the instance names for the passed list of nodes.
1771

1772
    @param inst_uuids: list of instance UUIDs to get names for
1773
    @type inst_uuids: list of strings
1774
    @rtype: list of strings
1775
    @return: list of instance names
1776

1777
    """
1778
    return self._UnlockedGetInstanceNames(inst_uuids)
1779

    
1780
  def _UnlockedGetInstanceNames(self, inst_uuids):
1781
    return [self._UnlockedGetInstanceName(uuid) for uuid in inst_uuids]
1782

    
1783
  @locking.ssynchronized(_config_lock)
1784
  def AddNode(self, node, ec_id):
1785
    """Add a node to the configuration.
1786

1787
    @type node: L{objects.Node}
1788
    @param node: a Node instance
1789

1790
    """
1791
    logging.info("Adding node %s to configuration", node.name)
1792

    
1793
    self._EnsureUUID(node, ec_id)
1794

    
1795
    node.serial_no = 1
1796
    node.ctime = node.mtime = time.time()
1797
    self._UnlockedAddNodeToGroup(node.uuid, node.group)
1798
    self._config_data.nodes[node.uuid] = node
1799
    self._config_data.cluster.serial_no += 1
1800
    self._WriteConfig()
1801

    
1802
  @locking.ssynchronized(_config_lock)
1803
  def RemoveNode(self, node_uuid):
1804
    """Remove a node from the configuration.
1805

1806
    """
1807
    logging.info("Removing node %s from configuration", node_uuid)
1808

    
1809
    if node_uuid not in self._config_data.nodes:
1810
      raise errors.ConfigurationError("Unknown node '%s'" % node_uuid)
1811

    
1812
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_uuid])
1813
    del self._config_data.nodes[node_uuid]
1814
    self._config_data.cluster.serial_no += 1
1815
    self._WriteConfig()
1816

    
1817
  def ExpandNodeName(self, short_name):
1818
    """Attempt to expand an incomplete node name into a node UUID.
1819

1820
    """
1821
    # Locking is done in L{ConfigWriter.GetAllNodesInfo}
1822
    all_nodes = self.GetAllNodesInfo().values()
1823
    expanded_name = _MatchNameComponentIgnoreCase(
1824
                      short_name, [node.name for node in all_nodes])
1825

    
1826
    if expanded_name is not None:
1827
      # there has to be exactly one node with that name
1828
      node = (filter(lambda n: n.name == expanded_name, all_nodes)[0])
1829
      return (node.uuid, node.name)
1830
    else:
1831
      return (None, None)
1832

    
1833
  def _UnlockedGetNodeInfo(self, node_uuid):
1834
    """Get the configuration of a node, as stored in the config.
1835

1836
    This function is for internal use, when the config lock is already
1837
    held.
1838

1839
    @param node_uuid: the node UUID
1840

1841
    @rtype: L{objects.Node}
1842
    @return: the node object
1843

1844
    """
1845
    if node_uuid not in self._config_data.nodes:
1846
      return None
1847

    
1848
    return self._config_data.nodes[node_uuid]
1849

    
1850
  @locking.ssynchronized(_config_lock, shared=1)
1851
  def GetNodeInfo(self, node_uuid):
1852
    """Get the configuration of a node, as stored in the config.
1853

1854
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1855

1856
    @param node_uuid: the node UUID
1857

1858
    @rtype: L{objects.Node}
1859
    @return: the node object
1860

1861
    """
1862
    return self._UnlockedGetNodeInfo(node_uuid)
1863

    
1864
  @locking.ssynchronized(_config_lock, shared=1)
1865
  def GetNodeInstances(self, node_uuid):
1866
    """Get the instances of a node, as stored in the config.
1867

1868
    @param node_uuid: the node UUID
1869

1870
    @rtype: (list, list)
1871
    @return: a tuple with two lists: the primary and the secondary instances
1872

1873
    """
1874
    pri = []
1875
    sec = []
1876
    for inst in self._config_data.instances.values():
1877
      if inst.primary_node == node_uuid:
1878
        pri.append(inst.uuid)
1879
      if node_uuid in inst.secondary_nodes:
1880
        sec.append(inst.uuid)
1881
    return (pri, sec)
1882

    
1883
  @locking.ssynchronized(_config_lock, shared=1)
1884
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1885
    """Get the instances of a node group.
1886

1887
    @param uuid: Node group UUID
1888
    @param primary_only: Whether to only consider primary nodes
1889
    @rtype: frozenset
1890
    @return: List of instance UUIDs in node group
1891

1892
    """
1893
    if primary_only:
1894
      nodes_fn = lambda inst: [inst.primary_node]
1895
    else:
1896
      nodes_fn = lambda inst: inst.all_nodes
1897

    
1898
    return frozenset(inst.uuid
1899
                     for inst in self._config_data.instances.values()
1900
                     for node_uuid in nodes_fn(inst)
1901
                     if self._UnlockedGetNodeInfo(node_uuid).group == uuid)
1902

    
1903
  def _UnlockedGetHvparamsString(self, hvname):
1904
    """Return the string representation of the list of hyervisor parameters of
1905
    the given hypervisor.
1906

1907
    @see: C{GetHvparams}
1908

1909
    """
1910
    result = ""
1911
    hvparams = self._config_data.cluster.hvparams[hvname]
1912
    for key in hvparams:
1913
      result += "%s=%s\n" % (key, hvparams[key])
1914
    return result
1915

    
1916
  @locking.ssynchronized(_config_lock, shared=1)
1917
  def GetHvparamsString(self, hvname):
1918
    """Return the hypervisor parameters of the given hypervisor.
1919

1920
    @type hvname: string
1921
    @param hvname: name of a hypervisor
1922
    @rtype: string
1923
    @return: string containing key-value-pairs, one pair on each line;
1924
      format: KEY=VALUE
1925

1926
    """
1927
    return self._UnlockedGetHvparamsString(hvname)
1928

    
1929
  def _UnlockedGetNodeList(self):
1930
    """Return the list of nodes which are in the configuration.
1931

1932
    This function is for internal use, when the config lock is already
1933
    held.
1934

1935
    @rtype: list
1936

1937
    """
1938
    return self._config_data.nodes.keys()
1939

    
1940
  @locking.ssynchronized(_config_lock, shared=1)
1941
  def GetNodeList(self):
1942
    """Return the list of nodes which are in the configuration.
1943

1944
    """
1945
    return self._UnlockedGetNodeList()
1946

    
1947
  def _UnlockedGetOnlineNodeList(self):
1948
    """Return the list of nodes which are online.
1949

1950
    """
1951
    all_nodes = [self._UnlockedGetNodeInfo(node)
1952
                 for node in self._UnlockedGetNodeList()]
1953
    return [node.uuid for node in all_nodes if not node.offline]
1954

    
1955
  @locking.ssynchronized(_config_lock, shared=1)
1956
  def GetOnlineNodeList(self):
1957
    """Return the list of nodes which are online.
1958

1959
    """
1960
    return self._UnlockedGetOnlineNodeList()
1961

    
1962
  @locking.ssynchronized(_config_lock, shared=1)
1963
  def GetVmCapableNodeList(self):
1964
    """Return the list of nodes which are not vm capable.
1965

1966
    """
1967
    all_nodes = [self._UnlockedGetNodeInfo(node)
1968
                 for node in self._UnlockedGetNodeList()]
1969
    return [node.uuid for node in all_nodes if node.vm_capable]
1970

    
1971
  @locking.ssynchronized(_config_lock, shared=1)
1972
  def GetNonVmCapableNodeList(self):
1973
    """Return the list of nodes which are not vm capable.
1974

1975
    """
1976
    all_nodes = [self._UnlockedGetNodeInfo(node)
1977
                 for node in self._UnlockedGetNodeList()]
1978
    return [node.uuid for node in all_nodes if not node.vm_capable]
1979

    
1980
  @locking.ssynchronized(_config_lock, shared=1)
1981
  def GetMultiNodeInfo(self, node_uuids):
1982
    """Get the configuration of multiple nodes.
1983

1984
    @param node_uuids: list of node UUIDs
1985
    @rtype: list
1986
    @return: list of tuples of (node, node_info), where node_info is
1987
        what would GetNodeInfo return for the node, in the original
1988
        order
1989

1990
    """
1991
    return [(uuid, self._UnlockedGetNodeInfo(uuid)) for uuid in node_uuids]
1992

    
1993
  def _UnlockedGetAllNodesInfo(self):
1994
    """Gets configuration of all nodes.
1995

1996
    @note: See L{GetAllNodesInfo}
1997

1998
    """
1999
    return dict([(node_uuid, self._UnlockedGetNodeInfo(node_uuid))
2000
                 for node_uuid in self._UnlockedGetNodeList()])
2001

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

2006
    @rtype: dict
2007
    @return: dict of (node, node_info), where node_info is what
2008
              would GetNodeInfo return for the node
2009

2010
    """
2011
    return self._UnlockedGetAllNodesInfo()
2012

    
2013
  def _UnlockedGetNodeInfoByName(self, node_name):
2014
    for node in self._UnlockedGetAllNodesInfo().values():
2015
      if node.name == node_name:
2016
        return node
2017
    return None
2018

    
2019
  @locking.ssynchronized(_config_lock, shared=1)
2020
  def GetNodeInfoByName(self, node_name):
2021
    """Get the L{objects.Node} object for a named node.
2022

2023
    @param node_name: name of the node to get information for
2024
    @type node_name: string
2025
    @return: the corresponding L{objects.Node} instance or None if no
2026
          information is available
2027

2028
    """
2029
    return self._UnlockedGetNodeInfoByName(node_name)
2030

    
2031
  def _UnlockedGetNodeName(self, node_spec):
2032
    if isinstance(node_spec, objects.Node):
2033
      return node_spec.name
2034
    elif isinstance(node_spec, basestring):
2035
      node_info = self._UnlockedGetNodeInfo(node_spec)
2036
      if node_info is None:
2037
        raise errors.OpExecError("Unknown node: %s" % node_spec)
2038
      return node_info.name
2039
    else:
2040
      raise errors.ProgrammerError("Can't handle node spec '%s'" % node_spec)
2041

    
2042
  @locking.ssynchronized(_config_lock, shared=1)
2043
  def GetNodeName(self, node_spec):
2044
    """Gets the node name for the passed node.
2045

2046
    @param node_spec: node to get names for
2047
    @type node_spec: either node UUID or a L{objects.Node} object
2048
    @rtype: string
2049
    @return: node name
2050

2051
    """
2052
    return self._UnlockedGetNodeName(node_spec)
2053

    
2054
  def _UnlockedGetNodeNames(self, node_specs):
2055
    return [self._UnlockedGetNodeName(node_spec) for node_spec in node_specs]
2056

    
2057
  @locking.ssynchronized(_config_lock, shared=1)
2058
  def GetNodeNames(self, node_specs):
2059
    """Gets the node names for the passed list of nodes.
2060

2061
    @param node_specs: list of nodes to get names for
2062
    @type node_specs: list of either node UUIDs or L{objects.Node} objects
2063
    @rtype: list of strings
2064
    @return: list of node names
2065

2066
    """
2067
    return self._UnlockedGetNodeNames(node_specs)
2068

    
2069
  @locking.ssynchronized(_config_lock, shared=1)
2070
  def GetNodeGroupsFromNodes(self, node_uuids):
2071
    """Returns groups for a list of nodes.
2072

2073
    @type node_uuids: list of string
2074
    @param node_uuids: List of node UUIDs
2075
    @rtype: frozenset
2076

2077
    """
2078
    return frozenset(self._UnlockedGetNodeInfo(uuid).group
2079
                     for uuid in node_uuids)
2080

    
2081
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
2082
    """Get the number of current and maximum desired and possible candidates.
2083

2084
    @type exceptions: list
2085
    @param exceptions: if passed, list of nodes that should be ignored
2086
    @rtype: tuple
2087
    @return: tuple of (current, desired and possible, possible)
2088

2089
    """
2090
    mc_now = mc_should = mc_max = 0
2091
    for node in self._config_data.nodes.values():
2092
      if exceptions and node.uuid in exceptions:
2093
        continue
2094
      if not (node.offline or node.drained) and node.master_capable:
2095
        mc_max += 1
2096
      if node.master_candidate:
2097
        mc_now += 1
2098
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
2099
    return (mc_now, mc_should, mc_max)
2100

    
2101
  @locking.ssynchronized(_config_lock, shared=1)
2102
  def GetMasterCandidateStats(self, exceptions=None):
2103
    """Get the number of current and maximum possible candidates.
2104

2105
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
2106

2107
    @type exceptions: list
2108
    @param exceptions: if passed, list of nodes that should be ignored
2109
    @rtype: tuple
2110
    @return: tuple of (current, max)
2111

2112
    """
2113
    return self._UnlockedGetMasterCandidateStats(exceptions)
2114

    
2115
  @locking.ssynchronized(_config_lock)
2116
  def MaintainCandidatePool(self, exception_node_uuids):
2117
    """Try to grow the candidate pool to the desired size.
2118

2119
    @type exception_node_uuids: list
2120
    @param exception_node_uuids: if passed, list of nodes that should be ignored
2121
    @rtype: list
2122
    @return: list with the adjusted nodes (L{objects.Node} instances)
2123

2124
    """
2125
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(
2126
                          exception_node_uuids)
2127
    mod_list = []
2128
    if mc_now < mc_max:
2129
      node_list = self._config_data.nodes.keys()
2130
      random.shuffle(node_list)
2131
      for uuid in node_list:
2132
        if mc_now >= mc_max:
2133
          break
2134
        node = self._config_data.nodes[uuid]
2135
        if (node.master_candidate or node.offline or node.drained or
2136
            node.uuid in exception_node_uuids or not node.master_capable):
2137
          continue
2138
        mod_list.append(node)
2139
        node.master_candidate = True
2140
        node.serial_no += 1
2141
        mc_now += 1
2142
      if mc_now != mc_max:
2143
        # this should not happen
2144
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
2145
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
2146
      if mod_list:
2147
        self._config_data.cluster.serial_no += 1
2148
        self._WriteConfig()
2149

    
2150
    return mod_list
2151

    
2152
  def _UnlockedAddNodeToGroup(self, node_uuid, nodegroup_uuid):
2153
    """Add a given node to the specified group.
2154

2155
    """
2156
    if nodegroup_uuid not in self._config_data.nodegroups:
2157
      # This can happen if a node group gets deleted between its lookup and
2158
      # when we're adding the first node to it, since we don't keep a lock in
2159
      # the meantime. It's ok though, as we'll fail cleanly if the node group
2160
      # is not found anymore.
2161
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
2162
    if node_uuid not in self._config_data.nodegroups[nodegroup_uuid].members:
2163
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_uuid)
2164

    
2165
  def _UnlockedRemoveNodeFromGroup(self, node):
2166
    """Remove a given node from its group.
2167

2168
    """
2169
    nodegroup = node.group
2170
    if nodegroup not in self._config_data.nodegroups:
2171
      logging.warning("Warning: node '%s' has unknown node group '%s'"
2172
                      " (while being removed from it)", node.uuid, nodegroup)
2173
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
2174
    if node.uuid not in nodegroup_obj.members:
2175
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
2176
                      " (while being removed from it)", node.uuid, nodegroup)
2177
    else:
2178
      nodegroup_obj.members.remove(node.uuid)
2179

    
2180
  @locking.ssynchronized(_config_lock)
2181
  def AssignGroupNodes(self, mods):
2182
    """Changes the group of a number of nodes.
2183

2184
    @type mods: list of tuples; (node name, new group UUID)
2185
    @param mods: Node membership modifications
2186

2187
    """
2188
    groups = self._config_data.nodegroups
2189
    nodes = self._config_data.nodes
2190

    
2191
    resmod = []
2192

    
2193
    # Try to resolve UUIDs first
2194
    for (node_uuid, new_group_uuid) in mods:
2195
      try:
2196
        node = nodes[node_uuid]
2197
      except KeyError:
2198
        raise errors.ConfigurationError("Unable to find node '%s'" % node_uuid)
2199

    
2200
      if node.group == new_group_uuid:
2201
        # Node is being assigned to its current group
2202
        logging.debug("Node '%s' was assigned to its current group (%s)",
2203
                      node_uuid, node.group)
2204
        continue
2205

    
2206
      # Try to find current group of node
2207
      try:
2208
        old_group = groups[node.group]
2209
      except KeyError:
2210
        raise errors.ConfigurationError("Unable to find old group '%s'" %
2211
                                        node.group)
2212

    
2213
      # Try to find new group for node
2214
      try:
2215
        new_group = groups[new_group_uuid]
2216
      except KeyError:
2217
        raise errors.ConfigurationError("Unable to find new group '%s'" %
2218
                                        new_group_uuid)
2219

    
2220
      assert node.uuid in old_group.members, \
2221
        ("Inconsistent configuration: node '%s' not listed in members for its"
2222
         " old group '%s'" % (node.uuid, old_group.uuid))
2223
      assert node.uuid not in new_group.members, \
2224
        ("Inconsistent configuration: node '%s' already listed in members for"
2225
         " its new group '%s'" % (node.uuid, new_group.uuid))
2226

    
2227
      resmod.append((node, old_group, new_group))
2228

    
2229
    # Apply changes
2230
    for (node, old_group, new_group) in resmod:
2231
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
2232
        "Assigning to current group is not possible"
2233

    
2234
      node.group = new_group.uuid
2235

    
2236
      # Update members of involved groups
2237
      if node.uuid in old_group.members:
2238
        old_group.members.remove(node.uuid)
2239
      if node.uuid not in new_group.members:
2240
        new_group.members.append(node.uuid)
2241

    
2242
    # Update timestamps and serials (only once per node/group object)
2243
    now = time.time()
2244
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
2245
      obj.serial_no += 1
2246
      obj.mtime = now
2247

    
2248
    # Force ssconf update
2249
    self._config_data.cluster.serial_no += 1
2250

    
2251
    self._WriteConfig()
2252

    
2253
  def _BumpSerialNo(self):
2254
    """Bump up the serial number of the config.
2255

2256
    """
2257
    self._config_data.serial_no += 1
2258
    self._config_data.mtime = time.time()
2259

    
2260
  def _AllUUIDObjects(self):
2261
    """Returns all objects with uuid attributes.
2262

2263
    """
2264
    return (self._config_data.instances.values() +
2265
            self._config_data.nodes.values() +
2266
            self._config_data.nodegroups.values() +
2267
            self._config_data.networks.values() +
2268
            self._AllDisks() +
2269
            self._AllNICs() +
2270
            [self._config_data.cluster])
2271

    
2272
  def _OpenConfig(self, accept_foreign):
2273
    """Read the config data from disk.
2274

2275
    """
2276
    raw_data = utils.ReadFile(self._cfg_file)
2277

    
2278
    try:
2279
      data_dict = serializer.Load(raw_data)
2280
      # Make sure the configuration has the right version
2281
      _ValidateConfig(data_dict)
2282
      data = objects.ConfigData.FromDict(data_dict)
2283
    except errors.ConfigVersionMismatch:
2284
      raise
2285
    except Exception, err:
2286
      raise errors.ConfigurationError(err)
2287

    
2288
    if (not hasattr(data, "cluster") or
2289
        not hasattr(data.cluster, "rsahostkeypub")):
2290
      raise errors.ConfigurationError("Incomplete configuration"
2291
                                      " (missing cluster.rsahostkeypub)")
2292

    
2293
    if not data.cluster.master_node in data.nodes:
2294
      msg = ("The configuration denotes node %s as master, but does not"
2295
             " contain information about this node" %
2296
             data.cluster.master_node)
2297
      raise errors.ConfigurationError(msg)
2298

    
2299
    master_info = data.nodes[data.cluster.master_node]
2300
    if master_info.name != self._my_hostname and not accept_foreign:
2301
      msg = ("The configuration denotes node %s as master, while my"
2302
             " hostname is %s; opening a foreign configuration is only"
2303
             " possible in accept_foreign mode" %
2304
             (master_info.name, self._my_hostname))
2305
      raise errors.ConfigurationError(msg)
2306

    
2307
    self._config_data = data
2308
    # reset the last serial as -1 so that the next write will cause
2309
    # ssconf update
2310
    self._last_cluster_serial = -1
2311

    
2312
    # Upgrade configuration if needed
2313
    self._UpgradeConfig()
2314

    
2315
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2316

    
2317
  def _UpgradeConfig(self):
2318
    """Run any upgrade steps.
2319

2320
    This method performs both in-object upgrades and also update some data
2321
    elements that need uniqueness across the whole configuration or interact
2322
    with other objects.
2323

2324
    @warning: this function will call L{_WriteConfig()}, but also
2325
        L{DropECReservations} so it needs to be called only from a
2326
        "safe" place (the constructor). If one wanted to call it with
2327
        the lock held, a DropECReservationUnlocked would need to be
2328
        created first, to avoid causing deadlock.
2329

2330
    """
2331
    # Keep a copy of the persistent part of _config_data to check for changes
2332
    # Serialization doesn't guarantee order in dictionaries
2333
    oldconf = copy.deepcopy(self._config_data.ToDict())
2334

    
2335
    # In-object upgrades
2336
    self._config_data.UpgradeConfig()
2337

    
2338
    for item in self._AllUUIDObjects():
2339
      if item.uuid is None:
2340
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
2341
    if not self._config_data.nodegroups:
2342
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
2343
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
2344
                                            members=[])
2345
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
2346
    for node in self._config_data.nodes.values():
2347
      if not node.group:
2348
        node.group = self.LookupNodeGroup(None)
2349
      # This is technically *not* an upgrade, but needs to be done both when
2350
      # nodegroups are being added, and upon normally loading the config,
2351
      # because the members list of a node group is discarded upon
2352
      # serializing/deserializing the object.
2353
      self._UnlockedAddNodeToGroup(node.uuid, node.group)
2354

    
2355
    modified = (oldconf != self._config_data.ToDict())
2356
    if modified:
2357
      self._WriteConfig()
2358
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
2359
      # only called at config init time, without the lock held
2360
      self.DropECReservations(_UPGRADE_CONFIG_JID)
2361
    else:
2362
      config_errors = self._UnlockedVerifyConfig()
2363
      if config_errors:
2364
        errmsg = ("Loaded configuration data is not consistent: %s" %
2365
                  (utils.CommaJoin(config_errors)))
2366
        logging.critical(errmsg)
2367

    
2368
  def _DistributeConfig(self, feedback_fn):
2369
    """Distribute the configuration to the other nodes.
2370

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

2374
    """
2375
    if self._offline:
2376
      return True
2377

    
2378
    bad = False
2379

    
2380
    node_list = []
2381
    addr_list = []
2382
    myhostname = self._my_hostname
2383
    # we can skip checking whether _UnlockedGetNodeInfo returns None
2384
    # since the node list comes from _UnlocketGetNodeList, and we are
2385
    # called with the lock held, so no modifications should take place
2386
    # in between
2387
    for node_uuid in self._UnlockedGetNodeList():
2388
      node_info = self._UnlockedGetNodeInfo(node_uuid)
2389
      if node_info.name == myhostname or not node_info.master_candidate:
2390
        continue
2391
      node_list.append(node_info.name)
2392
      addr_list.append(node_info.primary_ip)
2393

    
2394
    # TODO: Use dedicated resolver talking to config writer for name resolution
2395
    result = \
2396
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2397
    for to_node, to_result in result.items():
2398
      msg = to_result.fail_msg
2399
      if msg:
2400
        msg = ("Copy of file %s to node %s failed: %s" %
2401
               (self._cfg_file, to_node, msg))
2402
        logging.error(msg)
2403

    
2404
        if feedback_fn:
2405
          feedback_fn(msg)
2406

    
2407
        bad = True
2408

    
2409
    return not bad
2410

    
2411
  def _WriteConfig(self, destination=None, feedback_fn=None):
2412
    """Write the configuration data to persistent storage.
2413

2414
    """
2415
    assert feedback_fn is None or callable(feedback_fn)
2416

    
2417
    # Warn on config errors, but don't abort the save - the
2418
    # configuration has already been modified, and we can't revert;
2419
    # the best we can do is to warn the user and save as is, leaving
2420
    # recovery to the user
2421
    config_errors = self._UnlockedVerifyConfig()
2422
    if config_errors:
2423
      errmsg = ("Configuration data is not consistent: %s" %
2424
                (utils.CommaJoin(config_errors)))
2425
      logging.critical(errmsg)
2426
      if feedback_fn:
2427
        feedback_fn(errmsg)
2428

    
2429
    if destination is None:
2430
      destination = self._cfg_file
2431
    self._BumpSerialNo()
2432
    txt = serializer.Dump(self._config_data.ToDict())
2433

    
2434
    getents = self._getents()
2435
    try:
2436
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2437
                               close=False, gid=getents.confd_gid, mode=0640)
2438
    except errors.LockError:
2439
      raise errors.ConfigurationError("The configuration file has been"
2440
                                      " modified since the last write, cannot"
2441
                                      " update")
2442
    try:
2443
      self._cfg_id = utils.GetFileID(fd=fd)
2444
    finally:
2445
      os.close(fd)
2446

    
2447
    self.write_count += 1
2448

    
2449
    # and redistribute the config file to master candidates
2450
    self._DistributeConfig(feedback_fn)
2451

    
2452
    # Write ssconf files on all nodes (including locally)
2453
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2454
      if not self._offline:
2455
        result = self._GetRpc(None).call_write_ssconf_files(
2456
          self._UnlockedGetNodeNames(self._UnlockedGetOnlineNodeList()),
2457
          self._UnlockedGetSsconfValues())
2458

    
2459
        for nname, nresu in result.items():
2460
          msg = nresu.fail_msg
2461
          if msg:
2462
            errmsg = ("Error while uploading ssconf files to"
2463
                      " node %s: %s" % (nname, msg))
2464
            logging.warning(errmsg)
2465

    
2466
            if feedback_fn:
2467
              feedback_fn(errmsg)
2468

    
2469
      self._last_cluster_serial = self._config_data.cluster.serial_no
2470

    
2471
  def _GetAllHvparamsStrings(self, hypervisors):
2472
    """Get the hvparams of all given hypervisors from the config.
2473

2474
    @type hypervisors: list of string
2475
    @param hypervisors: list of hypervisor names
2476
    @rtype: dict of strings
2477
    @returns: dictionary mapping the hypervisor name to a string representation
2478
      of the hypervisor's hvparams
2479

2480
    """
2481
    hvparams = {}
2482
    for hv in hypervisors:
2483
      hvparams[hv] = self._UnlockedGetHvparamsString(hv)
2484
    return hvparams
2485

    
2486
  @staticmethod
2487
  def _ExtendByAllHvparamsStrings(ssconf_values, all_hvparams):
2488
    """Extends the ssconf_values dictionary by hvparams.
2489

2490
    @type ssconf_values: dict of strings
2491
    @param ssconf_values: dictionary mapping ssconf_keys to strings
2492
      representing the content of ssconf files
2493
    @type all_hvparams: dict of strings
2494
    @param all_hvparams: dictionary mapping hypervisor names to a string
2495
      representation of their hvparams
2496
    @rtype: same as ssconf_values
2497
    @returns: the ssconf_values dictionary extended by hvparams
2498

2499
    """
2500
    for hv in all_hvparams:
2501
      ssconf_key = constants.SS_HVPARAMS_PREF + hv
2502
      ssconf_values[ssconf_key] = all_hvparams[hv]
2503
    return ssconf_values
2504

    
2505
  def _UnlockedGetSsconfValues(self):
2506
    """Return the values needed by ssconf.
2507

2508
    @rtype: dict
2509
    @return: a dictionary with keys the ssconf names and values their
2510
        associated value
2511

2512
    """
2513
    fn = "\n".join
2514
    instance_names = utils.NiceSort(
2515
                       [inst.name for inst in
2516
                        self._UnlockedGetAllInstancesInfo().values()])
2517
    node_infos = self._UnlockedGetAllNodesInfo().values()
2518
    node_names = [node.name for node in node_infos]
2519
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2520
                    for ninfo in node_infos]
2521
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2522
                    for ninfo in node_infos]
2523

    
2524
    instance_data = fn(instance_names)
2525
    off_data = fn(node.name for node in node_infos if node.offline)
2526
    on_data = fn(node.name for node in node_infos if not node.offline)
2527
    mc_data = fn(node.name for node in node_infos if node.master_candidate)
2528
    mc_ips_data = fn(node.primary_ip for node in node_infos
2529
                     if node.master_candidate)
2530
    node_data = fn(node_names)
2531
    node_pri_ips_data = fn(node_pri_ips)
2532
    node_snd_ips_data = fn(node_snd_ips)
2533

    
2534
    cluster = self._config_data.cluster
2535
    cluster_tags = fn(cluster.GetTags())
2536

    
2537
    hypervisor_list = fn(cluster.enabled_hypervisors)
2538
    all_hvparams = self._GetAllHvparamsStrings(constants.HYPER_TYPES)
2539

    
2540
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2541

    
2542
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2543
                  self._config_data.nodegroups.values()]
2544
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2545
    networks = ["%s %s" % (net.uuid, net.name) for net in
2546
                self._config_data.networks.values()]
2547
    networks_data = fn(utils.NiceSort(networks))
2548

    
2549
    ssconf_values = {
2550
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
2551
      constants.SS_CLUSTER_TAGS: cluster_tags,
2552
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2553
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2554
      constants.SS_MASTER_CANDIDATES: mc_data,
2555
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2556
      constants.SS_MASTER_IP: cluster.master_ip,
2557
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
2558
      constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2559
      constants.SS_MASTER_NODE: self._UnlockedGetNodeName(cluster.master_node),
2560
      constants.SS_NODE_LIST: node_data,
2561
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2562
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2563
      constants.SS_OFFLINE_NODES: off_data,
2564
      constants.SS_ONLINE_NODES: on_data,
2565
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2566
      constants.SS_INSTANCE_LIST: instance_data,
2567
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2568
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
2569
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2570
      constants.SS_UID_POOL: uid_pool,
2571
      constants.SS_NODEGROUPS: nodegroups_data,
2572
      constants.SS_NETWORKS: networks_data,
2573
      }
2574
    ssconf_values = self._ExtendByAllHvparamsStrings(ssconf_values,
2575
                                                     all_hvparams)
2576
    bad_values = [(k, v) for k, v in ssconf_values.items()
2577
                  if not isinstance(v, (str, basestring))]
2578
    if bad_values:
2579
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2580
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2581
                                      " values: %s" % err)
2582
    return ssconf_values
2583

    
2584
  @locking.ssynchronized(_config_lock, shared=1)
2585
  def GetSsconfValues(self):
2586
    """Wrapper using lock around _UnlockedGetSsconf().
2587

2588
    """
2589
    return self._UnlockedGetSsconfValues()
2590

    
2591
  @locking.ssynchronized(_config_lock, shared=1)
2592
  def GetVGName(self):
2593
    """Return the volume group name.
2594

2595
    """
2596
    return self._config_data.cluster.volume_group_name
2597

    
2598
  @locking.ssynchronized(_config_lock)
2599
  def SetVGName(self, vg_name):
2600
    """Set the volume group name.
2601

2602
    """
2603
    self._config_data.cluster.volume_group_name = vg_name
2604
    self._config_data.cluster.serial_no += 1
2605
    self._WriteConfig()
2606

    
2607
  @locking.ssynchronized(_config_lock, shared=1)
2608
  def GetDRBDHelper(self):
2609
    """Return DRBD usermode helper.
2610

2611
    """
2612
    return self._config_data.cluster.drbd_usermode_helper
2613

    
2614
  @locking.ssynchronized(_config_lock)
2615
  def SetDRBDHelper(self, drbd_helper):
2616
    """Set DRBD usermode helper.
2617

2618
    """
2619
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2620
    self._config_data.cluster.serial_no += 1
2621
    self._WriteConfig()
2622

    
2623
  @locking.ssynchronized(_config_lock, shared=1)
2624
  def GetMACPrefix(self):
2625
    """Return the mac prefix.
2626

2627
    """
2628
    return self._config_data.cluster.mac_prefix
2629

    
2630
  @locking.ssynchronized(_config_lock, shared=1)
2631
  def GetClusterInfo(self):
2632
    """Returns information about the cluster
2633

2634
    @rtype: L{objects.Cluster}
2635
    @return: the cluster object
2636

2637
    """
2638
    return self._config_data.cluster
2639

    
2640
  @locking.ssynchronized(_config_lock, shared=1)
2641
  def HasAnyDiskOfType(self, dev_type):
2642
    """Check if in there is at disk of the given type in the configuration.
2643

2644
    """
2645
    return self._config_data.HasAnyDiskOfType(dev_type)
2646

    
2647
  @locking.ssynchronized(_config_lock)
2648
  def Update(self, target, feedback_fn, ec_id=None):
2649
    """Notify function to be called after updates.
2650

2651
    This function must be called when an object (as returned by
2652
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2653
    caller wants the modifications saved to the backing store. Note
2654
    that all modified objects will be saved, but the target argument
2655
    is the one the caller wants to ensure that it's saved.
2656

2657
    @param target: an instance of either L{objects.Cluster},
2658
        L{objects.Node} or L{objects.Instance} which is existing in
2659
        the cluster
2660
    @param feedback_fn: Callable feedback function
2661

2662
    """
2663
    if self._config_data is None:
2664
      raise errors.ProgrammerError("Configuration file not read,"
2665
                                   " cannot save.")
2666
    update_serial = False
2667
    if isinstance(target, objects.Cluster):
2668
      test = target == self._config_data.cluster
2669
    elif isinstance(target, objects.Node):
2670
      test = target in self._config_data.nodes.values()
2671
      update_serial = True
2672
    elif isinstance(target, objects.Instance):
2673
      test = target in self._config_data.instances.values()
2674
    elif isinstance(target, objects.NodeGroup):
2675
      test = target in self._config_data.nodegroups.values()
2676
    elif isinstance(target, objects.Network):
2677
      test = target in self._config_data.networks.values()
2678
    else:
2679
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2680
                                   " ConfigWriter.Update" % type(target))
2681
    if not test:
2682
      raise errors.ConfigurationError("Configuration updated since object"
2683
                                      " has been read or unknown object")
2684
    target.serial_no += 1
2685
    target.mtime = now = time.time()
2686

    
2687
    if update_serial:
2688
      # for node updates, we need to increase the cluster serial too
2689
      self._config_data.cluster.serial_no += 1
2690
      self._config_data.cluster.mtime = now
2691

    
2692
    if isinstance(target, objects.Instance):
2693
      self._UnlockedReleaseDRBDMinors(target.uuid)
2694

    
2695
    if ec_id is not None:
2696
      # Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
2697
      self._UnlockedCommitTemporaryIps(ec_id)
2698

    
2699
    self._WriteConfig(feedback_fn=feedback_fn)
2700

    
2701
  @locking.ssynchronized(_config_lock)
2702
  def DropECReservations(self, ec_id):
2703
    """Drop per-execution-context reservations
2704

2705
    """
2706
    for rm in self._all_rms:
2707
      rm.DropECReservations(ec_id)
2708

    
2709
  @locking.ssynchronized(_config_lock, shared=1)
2710
  def GetAllNetworksInfo(self):
2711
    """Get configuration info of all the networks.
2712

2713
    """
2714
    return dict(self._config_data.networks)
2715

    
2716
  def _UnlockedGetNetworkList(self):
2717
    """Get the list of networks.
2718

2719
    This function is for internal use, when the config lock is already held.
2720

2721
    """
2722
    return self._config_data.networks.keys()
2723

    
2724
  @locking.ssynchronized(_config_lock, shared=1)
2725
  def GetNetworkList(self):
2726
    """Get the list of networks.
2727

2728
    @return: array of networks, ex. ["main", "vlan100", "200]
2729

2730
    """
2731
    return self._UnlockedGetNetworkList()
2732

    
2733
  @locking.ssynchronized(_config_lock, shared=1)
2734
  def GetNetworkNames(self):
2735
    """Get a list of network names
2736

2737
    """
2738
    names = [net.name
2739
             for net in self._config_data.networks.values()]
2740
    return names
2741

    
2742
  def _UnlockedGetNetwork(self, uuid):
2743
    """Returns information about a network.
2744

2745
    This function is for internal use, when the config lock is already held.
2746

2747
    """
2748
    if uuid not in self._config_data.networks:
2749
      return None
2750

    
2751
    return self._config_data.networks[uuid]
2752

    
2753
  @locking.ssynchronized(_config_lock, shared=1)
2754
  def GetNetwork(self, uuid):
2755
    """Returns information about a network.
2756

2757
    It takes the information from the configuration file.
2758

2759
    @param uuid: UUID of the network
2760

2761
    @rtype: L{objects.Network}
2762
    @return: the network object
2763

2764
    """
2765
    return self._UnlockedGetNetwork(uuid)
2766

    
2767
  @locking.ssynchronized(_config_lock)
2768
  def AddNetwork(self, net, ec_id, check_uuid=True):
2769
    """Add a network to the configuration.
2770

2771
    @type net: L{objects.Network}
2772
    @param net: the Network object to add
2773
    @type ec_id: string
2774
    @param ec_id: unique id for the job to use when creating a missing UUID
2775

2776
    """
2777
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2778
    self._WriteConfig()
2779

    
2780
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2781
    """Add a network to the configuration.
2782

2783
    """
2784
    logging.info("Adding network %s to configuration", net.name)
2785

    
2786
    if check_uuid:
2787
      self._EnsureUUID(net, ec_id)
2788

    
2789
    net.serial_no = 1
2790
    net.ctime = net.mtime = time.time()
2791
    self._config_data.networks[net.uuid] = net
2792
    self._config_data.cluster.serial_no += 1
2793

    
2794
  def _UnlockedLookupNetwork(self, target):
2795
    """Lookup a network's UUID.
2796

2797
    @type target: string
2798
    @param target: network name or UUID
2799
    @rtype: string
2800
    @return: network UUID
2801
    @raises errors.OpPrereqError: when the target network cannot be found
2802

2803
    """
2804
    if target is None:
2805
      return None
2806
    if target in self._config_data.networks:
2807
      return target
2808
    for net in self._config_data.networks.values():
2809
      if net.name == target:
2810
        return net.uuid
2811
    raise errors.OpPrereqError("Network '%s' not found" % target,
2812
                               errors.ECODE_NOENT)
2813

    
2814
  @locking.ssynchronized(_config_lock, shared=1)
2815
  def LookupNetwork(self, target):
2816
    """Lookup a network's UUID.
2817

2818
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2819

2820
    @type target: string
2821
    @param target: network name or UUID
2822
    @rtype: string
2823
    @return: network UUID
2824

2825
    """
2826
    return self._UnlockedLookupNetwork(target)
2827

    
2828
  @locking.ssynchronized(_config_lock)
2829
  def RemoveNetwork(self, network_uuid):
2830
    """Remove a network from the configuration.
2831

2832
    @type network_uuid: string
2833
    @param network_uuid: the UUID of the network to remove
2834

2835
    """
2836
    logging.info("Removing network %s from configuration", network_uuid)
2837

    
2838
    if network_uuid not in self._config_data.networks:
2839
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2840

    
2841
    del self._config_data.networks[network_uuid]
2842
    self._config_data.cluster.serial_no += 1
2843
    self._WriteConfig()
2844

    
2845
  def _UnlockedGetGroupNetParams(self, net_uuid, node_uuid):
2846
    """Get the netparams (mode, link) of a network.
2847

2848
    Get a network's netparams for a given node.
2849

2850
    @type net_uuid: string
2851
    @param net_uuid: network uuid
2852
    @type node_uuid: string
2853
    @param node_uuid: node UUID
2854
    @rtype: dict or None
2855
    @return: netparams
2856

2857
    """
2858
    node_info = self._UnlockedGetNodeInfo(node_uuid)
2859
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2860
    netparams = nodegroup_info.networks.get(net_uuid, None)
2861

    
2862
    return netparams
2863

    
2864
  @locking.ssynchronized(_config_lock, shared=1)
2865
  def GetGroupNetParams(self, net_uuid, node_uuid):
2866
    """Locking wrapper of _UnlockedGetGroupNetParams()
2867

2868
    """
2869
    return self._UnlockedGetGroupNetParams(net_uuid, node_uuid)
2870

    
2871
  @locking.ssynchronized(_config_lock, shared=1)
2872
  def CheckIPInNodeGroup(self, ip, node_uuid):
2873
    """Check IP uniqueness in nodegroup.
2874

2875
    Check networks that are connected in the node's node group
2876
    if ip is contained in any of them. Used when creating/adding
2877
    a NIC to ensure uniqueness among nodegroups.
2878

2879
    @type ip: string
2880
    @param ip: ip address
2881
    @type node_uuid: string
2882
    @param node_uuid: node UUID
2883
    @rtype: (string, dict) or (None, None)
2884
    @return: (network name, netparams)
2885

2886
    """
2887
    if ip is None:
2888
      return (None, None)
2889
    node_info = self._UnlockedGetNodeInfo(node_uuid)
2890
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2891
    for net_uuid in nodegroup_info.networks.keys():
2892
      net_info = self._UnlockedGetNetwork(net_uuid)
2893
      pool = network.AddressPool(net_info)
2894
      if pool.Contains(ip):
2895
        return (net_info.name, nodegroup_info.networks[net_uuid])
2896

    
2897
    return (None, None)