Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 4884f187

History | View | Annotate | Download (97.5 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
import ganeti.rpc.node as rpc
49
from ganeti import objects
50
from ganeti import serializer
51
from ganeti import uidpool
52
from ganeti import netutils
53
from ganeti import runtime
54
from ganeti import pathutils
55
from ganeti import network
56

    
57

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

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

    
63

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

67
  This only verifies the version of the configuration.
68

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

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

    
76

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

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

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

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

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

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

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

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

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

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

126
    """
127
    assert callable(generate_one_fn)
128

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

    
142

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

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

    
149

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

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

159
  """
160
  result = []
161

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

    
167
  return result
168

    
169

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

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

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

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

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

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

216
    """
217
    self._context = context
218

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
294
    return prefix
295

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

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

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

    
312
    return GenMac
313

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

318
    This should check the current instances for duplicates.
319

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

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

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

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

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

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

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

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

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

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

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

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

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

374
    This is just a wrapper around _UnlockedReleaseIp.
375

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

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

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

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

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

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

401
    """
402
    nobj = self._UnlockedGetNetwork(net_uuid)
403
    pool = network.AddressPool(nobj)
404
    try:
405
      isreserved = pool.IsReserved(address)
406
      isextreserved = pool.IsReserved(address, external=True)
407
    except errors.AddressPoolError:
408
      raise errors.ReservationError("IP address not in network")
409
    if isreserved:
410
      raise errors.ReservationError("IP address already in use")
411
    if check and isextreserved:
412
      raise errors.ReservationError("IP is externally reserved")
413

    
414
    return self._temporary_ips.Reserve(ec_id,
415
                                       (constants.RESERVE_ACTION,
416
                                        address, net_uuid))
417

    
418
  @locking.ssynchronized(_config_lock, shared=1)
419
  def ReserveIp(self, net_uuid, address, ec_id, check=True):
420
    """Reserve a given IPv4 address for use by an instance.
421

422
    """
423
    if net_uuid:
424
      return self._UnlockedReserveIp(net_uuid, address, ec_id, check)
425

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

430
    @type lv_name: string
431
    @param lv_name: the logical volume name to reserve
432

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

    
440
  @locking.ssynchronized(_config_lock, shared=1)
441
  def GenerateDRBDSecret(self, ec_id):
442
    """Generate a DRBD secret.
443

444
    This checks the current disks for duplicates.
445

446
    """
447
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
448
                                            utils.GenerateSecret,
449
                                            ec_id)
450

    
451
  def _AllLVs(self):
452
    """Compute the list of all LVs.
453

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

    
462
  def _AllDisks(self):
463
    """Compute the list of all Disks (recursively, including children).
464

465
    """
466
    def DiskAndAllChildren(disk):
467
      """Returns a list containing the given disk and all of his children.
468

469
      """
470
      disks = [disk]
471
      if disk.children:
472
        for child_disk in disk.children:
473
          disks.extend(DiskAndAllChildren(child_disk))
474
      return disks
475

    
476
    disks = []
477
    for instance in self._config_data.instances.values():
478
      for disk in instance.disks:
479
        disks.extend(DiskAndAllChildren(disk))
480
    return disks
481

    
482
  def _AllNICs(self):
483
    """Compute the list of all NICs.
484

485
    """
486
    nics = []
487
    for instance in self._config_data.instances.values():
488
      nics.extend(instance.nics)
489
    return nics
490

    
491
  def _AllIDs(self, include_temporary):
492
    """Compute the list of all UUIDs and names we have.
493

494
    @type include_temporary: boolean
495
    @param include_temporary: whether to include the _temporary_ids set
496
    @rtype: set
497
    @return: a set of IDs
498

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

    
509
  def _GenerateUniqueID(self, ec_id):
510
    """Generate an unique UUID.
511

512
    This checks the current node, instances and disk names for
513
    duplicates.
514

515
    @rtype: string
516
    @return: the unique id
517

518
    """
519
    existing = self._AllIDs(include_temporary=False)
520
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
521

    
522
  @locking.ssynchronized(_config_lock, shared=1)
523
  def GenerateUniqueID(self, ec_id):
524
    """Generate an unique ID.
525

526
    This is just a wrapper over the unlocked version.
527

528
    @type ec_id: string
529
    @param ec_id: unique id for the job to reserve the id to
530

531
    """
532
    return self._GenerateUniqueID(ec_id)
533

    
534
  def _AllMACs(self):
535
    """Return all MACs present in the config.
536

537
    @rtype: list
538
    @return: the list of all MACs
539

540
    """
541
    result = []
542
    for instance in self._config_data.instances.values():
543
      for nic in instance.nics:
544
        result.append(nic.mac)
545

    
546
    return result
547

    
548
  def _AllDRBDSecrets(self):
549
    """Return all DRBD secrets present in the config.
550

551
    @rtype: list
552
    @return: the list of all DRBD secrets
553

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

    
563
    result = []
564
    for instance in self._config_data.instances.values():
565
      for disk in instance.disks:
566
        helper(disk, result)
567

    
568
    return result
569

    
570
  def _CheckDiskIDs(self, disk, l_ids):
571
    """Compute duplicate disk IDs
572

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

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

    
588
    if disk.children:
589
      for child in disk.children:
590
        result.extend(self._CheckDiskIDs(child, l_ids))
591
    return result
592

    
593
  def _UnlockedVerifyConfig(self):
594
    """Verify function.
595

596
    @rtype: list
597
    @return: a list of error messages; a non-empty list signifies
598
        configuration errors
599

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

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

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

    
630
    if cluster.master_node not in data.nodes:
631
      result.append("cluster has invalid primary node '%s'" %
632
                    cluster.master_node)
633

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

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

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

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

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

    
684
    for disk_template in cluster.diskparams:
685
      if disk_template not in constants.DTS_HAVE_ACCESS:
686
        continue
687

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

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

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

    
729
      # parameter checks
730
      if instance.beparams:
731
        _helper("instance %s" % instance.name, "beparams",
732
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
733

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

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

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

    
760
        result.append("Instance '%s' has wrongly named disks: %s" %
761
                      (instance.name, tmp))
762

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

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

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

    
784
    if not data.nodes[cluster.master_node].master_candidate:
785
      result.append("Master node is not a master candidate")
786

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

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

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

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

    
843
    # IP checks
844
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
845
    ips = {}
846

    
847
    def _AddIpAddress(ip, name):
848
      ips.setdefault(ip, []).append(name)
849

    
850
    _AddIpAddress(cluster.master_ip, "cluster_ip")
851

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

    
857
    for instance in data.instances.values():
858
      for idx, nic in enumerate(instance.nics):
859
        if nic.ip is None:
860
          continue
861

    
862
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
863
        nic_mode = nicparams[constants.NIC_MODE]
864
        nic_link = nicparams[constants.NIC_LINK]
865

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

    
873
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
874
                      "instance:%s/nic:%d" % (instance.name, idx))
875

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

    
881
    return result
882

    
883
  @locking.ssynchronized(_config_lock, shared=1)
884
  def VerifyConfig(self):
885
    """Verify function.
886

887
    This is just a wrapper over L{_UnlockedVerifyConfig}.
888

889
    @rtype: list
890
    @return: a list of error messages; a non-empty list signifies
891
        configuration errors
892

893
    """
894
    return self._UnlockedVerifyConfig()
895

    
896
  @locking.ssynchronized(_config_lock)
897
  def AddTcpUdpPort(self, port):
898
    """Adds a new port to the available port pool.
899

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

904
    """
905
    if not isinstance(port, int):
906
      raise errors.ProgrammerError("Invalid type passed for port")
907

    
908
    self._config_data.cluster.tcpudp_port_pool.add(port)
909

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

914
    """
915
    return self._config_data.cluster.tcpudp_port_pool.copy()
916

    
917
  @locking.ssynchronized(_config_lock)
918
  def AllocatePort(self):
919
    """Allocate a port.
920

921
    The port will be taken from the available port pool or from the
922
    default port range (and in this case we increase
923
    highest_used_port).
924

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

    
937
    self._WriteConfig()
938
    return port
939

    
940
  def _UnlockedComputeDRBDMap(self):
941
    """Compute the used DRBD minor/nodes.
942

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

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

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

    
984
  @locking.ssynchronized(_config_lock)
985
  def ComputeDRBDMap(self):
986
    """Compute the used DRBD minor/nodes.
987

988
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
989

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

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

    
1001
  @locking.ssynchronized(_config_lock)
1002
  def AllocateDRBDMinor(self, node_uuids, inst_uuid):
1003
    """Allocate a drbd minor.
1004

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

1010
    @type inst_uuid: string
1011
    @param inst_uuid: the instance for which we allocate minors
1012

1013
    """
1014
    assert isinstance(inst_uuid, basestring), \
1015
           "Invalid argument '%s' passed to AllocateDRBDMinor" % inst_uuid
1016

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

    
1057
  def _UnlockedReleaseDRBDMinors(self, inst_uuid):
1058
    """Release temporary drbd minors allocated for a given instance.
1059

1060
    @type inst_uuid: string
1061
    @param inst_uuid: the instance for which temporary minors should be
1062
                      released
1063

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

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

1075
    This should be called on the error paths, on the success paths
1076
    it's automatically called by the ConfigWriter add and update
1077
    functions.
1078

1079
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1080

1081
    @type inst_uuid: string
1082
    @param inst_uuid: the instance for which temporary minors should be
1083
                      released
1084

1085
    """
1086
    self._UnlockedReleaseDRBDMinors(inst_uuid)
1087

    
1088
  @locking.ssynchronized(_config_lock, shared=1)
1089
  def GetConfigVersion(self):
1090
    """Get the configuration version.
1091

1092
    @return: Config version
1093

1094
    """
1095
    return self._config_data.version
1096

    
1097
  @locking.ssynchronized(_config_lock, shared=1)
1098
  def GetClusterName(self):
1099
    """Get cluster name.
1100

1101
    @return: Cluster name
1102

1103
    """
1104
    return self._config_data.cluster.cluster_name
1105

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

1110
    @return: Master node UUID
1111

1112
    """
1113
    return self._config_data.cluster.master_node
1114

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

1119
    @return: Master node hostname
1120

1121
    """
1122
    return self._UnlockedGetNodeName(self._config_data.cluster.master_node)
1123

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

1128
    @rtype: objects.Node
1129
    @return: Master node L{objects.Node} object
1130

1131
    """
1132
    return self._UnlockedGetNodeInfo(self._config_data.cluster.master_node)
1133

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

1138
    @return: Master IP
1139

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

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

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

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

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

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

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

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

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

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

1175
    """
1176
    return self._config_data.cluster.shared_file_storage_dir
1177

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

1182
    """
1183
    return self._config_data.cluster.gluster_storage_dir
1184

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

1189
    """
1190
    return self._config_data.cluster.enabled_hypervisors[0]
1191

    
1192
  @locking.ssynchronized(_config_lock, shared=1)
1193
  def GetRsaHostKey(self):
1194
    """Return the rsa hostkey from the config.
1195

1196
    @rtype: string
1197
    @return: the rsa hostkey
1198

1199
    """
1200
    return self._config_data.cluster.rsahostkeypub
1201

    
1202
  @locking.ssynchronized(_config_lock, shared=1)
1203
  def GetDsaHostKey(self):
1204
    """Return the dsa hostkey from the config.
1205

1206
    @rtype: string
1207
    @return: the dsa hostkey
1208

1209
    """
1210
    return self._config_data.cluster.dsahostkeypub
1211

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

1216
    """
1217
    return self._config_data.cluster.default_iallocator
1218

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

1223
    @rtype: dict
1224
    @return: dict of iallocator parameters
1225

1226
    """
1227
    return self._config_data.cluster.default_iallocator_params
1228

    
1229
  @locking.ssynchronized(_config_lock, shared=1)
1230
  def GetPrimaryIPFamily(self):
1231
    """Get cluster primary ip family.
1232

1233
    @return: primary ip family
1234

1235
    """
1236
    return self._config_data.cluster.primary_ip_family
1237

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

1242
    @rtype: L{object.MasterNetworkParameters}
1243
    @return: network parameters of the master node
1244

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

    
1252
    return result
1253

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

1258
    This method calls group.UpgradeConfig() to fill any missing attributes
1259
    according to their default values.
1260

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

1270
    """
1271
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1272
    self._WriteConfig()
1273

    
1274
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1275
    """Add a node group to the configuration.
1276

1277
    """
1278
    logging.info("Adding node group %s to configuration", group.name)
1279

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

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

    
1296
    group.serial_no = 1
1297
    group.ctime = group.mtime = time.time()
1298
    group.UpgradeConfig()
1299

    
1300
    self._config_data.nodegroups[group.uuid] = group
1301
    self._config_data.cluster.serial_no += 1
1302

    
1303
  @locking.ssynchronized(_config_lock)
1304
  def RemoveNodeGroup(self, group_uuid):
1305
    """Remove a node group from the configuration.
1306

1307
    @type group_uuid: string
1308
    @param group_uuid: the UUID of the node group to remove
1309

1310
    """
1311
    logging.info("Removing node group %s from configuration", group_uuid)
1312

    
1313
    if group_uuid not in self._config_data.nodegroups:
1314
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1315

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

    
1319
    del self._config_data.nodegroups[group_uuid]
1320
    self._config_data.cluster.serial_no += 1
1321
    self._WriteConfig()
1322

    
1323
  def _UnlockedLookupNodeGroup(self, target):
1324
    """Lookup a node group's UUID.
1325

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

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

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

1351
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1352

1353
    @type target: string or None
1354
    @param target: group name or UUID or None to look for the default
1355
    @rtype: string
1356
    @return: nodegroup UUID
1357

1358
    """
1359
    return self._UnlockedLookupNodeGroup(target)
1360

    
1361
  def _UnlockedGetNodeGroup(self, uuid):
1362
    """Lookup a node group.
1363

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

1369
    """
1370
    if uuid not in self._config_data.nodegroups:
1371
      return None
1372

    
1373
    return self._config_data.nodegroups[uuid]
1374

    
1375
  @locking.ssynchronized(_config_lock, shared=1)
1376
  def GetNodeGroup(self, uuid):
1377
    """Lookup a node group.
1378

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

1384
    """
1385
    return self._UnlockedGetNodeGroup(uuid)
1386

    
1387
  def _UnlockedGetAllNodeGroupsInfo(self):
1388
    """Get the configuration of all node groups.
1389

1390
    """
1391
    return dict(self._config_data.nodegroups)
1392

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

1397
    """
1398
    return self._UnlockedGetAllNodeGroupsInfo()
1399

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

1405
    """
1406
    return dict(map(lambda (uuid, ng): (uuid, ng.ToDict()),
1407
                    self._UnlockedGetAllNodeGroupsInfo().items()))
1408

    
1409
  @locking.ssynchronized(_config_lock, shared=1)
1410
  def GetNodeGroupList(self):
1411
    """Get a list of node groups.
1412

1413
    """
1414
    return self._config_data.nodegroups.keys()
1415

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

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

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

1431
    @param group_uuids: List of node group UUIDs
1432
    @rtype: list
1433
    @return: List of tuples of (group_uuid, group_info)
1434

1435
    """
1436
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1437

    
1438
  @locking.ssynchronized(_config_lock)
1439
  def AddInstance(self, instance, ec_id):
1440
    """Add an instance to the config.
1441

1442
    This should be used after creating a new instance.
1443

1444
    @type instance: L{objects.Instance}
1445
    @param instance: the instance object
1446

1447
    """
1448
    if not isinstance(instance, objects.Instance):
1449
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1450

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

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

    
1462
    self._CheckUniqueUUID(instance, include_temporary=False)
1463

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

    
1472
  def _EnsureUUID(self, item, ec_id):
1473
    """Ensures a given object has a valid UUID.
1474

1475
    @param item: the instance or node to be checked
1476
    @param ec_id: the execution context id for the uuid reservation
1477

1478
    """
1479
    if not item.uuid:
1480
      item.uuid = self._GenerateUniqueID(ec_id)
1481
    else:
1482
      self._CheckUniqueUUID(item, include_temporary=True)
1483

    
1484
  def _CheckUniqueUUID(self, item, include_temporary):
1485
    """Checks that the UUID of the given object is unique.
1486

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

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

    
1499
  def _SetInstanceStatus(self, inst_uuid, status, disks_active):
1500
    """Set the instance's status to a given value.
1501

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

    
1508
    if status is None:
1509
      status = instance.admin_state
1510
    if disks_active is None:
1511
      disks_active = instance.disks_active
1512

    
1513
    assert status in constants.ADMINST_ALL, \
1514
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1515

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

    
1524
  @locking.ssynchronized(_config_lock)
1525
  def MarkInstanceUp(self, inst_uuid):
1526
    """Mark the instance status to up in the config.
1527

1528
    This also sets the instance disks active flag.
1529

1530
    """
1531
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_UP, True)
1532

    
1533
  @locking.ssynchronized(_config_lock)
1534
  def MarkInstanceOffline(self, inst_uuid):
1535
    """Mark the instance status to down in the config.
1536

1537
    This also clears the instance disks active flag.
1538

1539
    """
1540
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_OFFLINE, False)
1541

    
1542
  @locking.ssynchronized(_config_lock)
1543
  def RemoveInstance(self, inst_uuid):
1544
    """Remove the instance from the configuration.
1545

1546
    """
1547
    if inst_uuid not in self._config_data.instances:
1548
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1549

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

    
1557
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1558

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

    
1564
    del self._config_data.instances[inst_uuid]
1565
    self._config_data.cluster.serial_no += 1
1566
    self._WriteConfig()
1567

    
1568
  @locking.ssynchronized(_config_lock)
1569
  def RenameInstance(self, inst_uuid, new_name):
1570
    """Rename an instance.
1571

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

1576
    """
1577
    if inst_uuid not in self._config_data.instances:
1578
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1579

    
1580
    inst = self._config_data.instances[inst_uuid]
1581
    inst.name = new_name
1582

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

    
1591
    # Force update of ssconf files
1592
    self._config_data.cluster.serial_no += 1
1593

    
1594
    self._WriteConfig()
1595

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

1600
    This does not touch the instance disks active flag, as shut down instances
1601
    can still have active disks.
1602

1603
    """
1604
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_DOWN, None)
1605

    
1606
  @locking.ssynchronized(_config_lock)
1607
  def MarkInstanceDisksActive(self, inst_uuid):
1608
    """Mark the status of instance disks active.
1609

1610
    """
1611
    self._SetInstanceStatus(inst_uuid, None, True)
1612

    
1613
  @locking.ssynchronized(_config_lock)
1614
  def MarkInstanceDisksInactive(self, inst_uuid):
1615
    """Mark the status of instance disks inactive.
1616

1617
    """
1618
    self._SetInstanceStatus(inst_uuid, None, False)
1619

    
1620
  def _UnlockedGetInstanceList(self):
1621
    """Get the list of instances.
1622

1623
    This function is for internal use, when the config lock is already held.
1624

1625
    """
1626
    return self._config_data.instances.keys()
1627

    
1628
  @locking.ssynchronized(_config_lock, shared=1)
1629
  def GetInstanceList(self):
1630
    """Get the list of instances.
1631

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

1634
    """
1635
    return self._UnlockedGetInstanceList()
1636

    
1637
  def ExpandInstanceName(self, short_name):
1638
    """Attempt to expand an incomplete instance name.
1639

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

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

    
1653
  def _UnlockedGetInstanceInfo(self, inst_uuid):
1654
    """Returns information about an instance.
1655

1656
    This function is for internal use, when the config lock is already held.
1657

1658
    """
1659
    if inst_uuid not in self._config_data.instances:
1660
      return None
1661

    
1662
    return self._config_data.instances[inst_uuid]
1663

    
1664
  @locking.ssynchronized(_config_lock, shared=1)
1665
  def GetInstanceInfo(self, inst_uuid):
1666
    """Returns information about an instance.
1667

1668
    It takes the information from the configuration file. Other information of
1669
    an instance are taken from the live systems.
1670

1671
    @param inst_uuid: UUID of the instance
1672

1673
    @rtype: L{objects.Instance}
1674
    @return: the instance object
1675

1676
    """
1677
    return self._UnlockedGetInstanceInfo(inst_uuid)
1678

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

1683
    @rtype: frozenset
1684

1685
    """
1686
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1687
    if not instance:
1688
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1689

    
1690
    if primary_only:
1691
      nodes = [instance.primary_node]
1692
    else:
1693
      nodes = instance.all_nodes
1694

    
1695
    return frozenset(self._UnlockedGetNodeInfo(node_uuid).group
1696
                     for node_uuid in nodes)
1697

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

1702
    @rtype: frozenset
1703

1704
    """
1705
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1706
    if not instance:
1707
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1708

    
1709
    networks = set()
1710
    for nic in instance.nics:
1711
      if nic.network:
1712
        networks.add(nic.network)
1713

    
1714
    return frozenset(networks)
1715

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

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

1726
    """
1727
    return [(uuid, self._UnlockedGetInstanceInfo(uuid)) for uuid in inst_uuids]
1728

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

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

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

    
1746
  @locking.ssynchronized(_config_lock, shared=1)
1747
  def GetAllInstancesInfo(self):
1748
    """Get the configuration of all instances.
1749

1750
    @rtype: dict
1751
    @return: dict of (instance, instance_info), where instance_info is what
1752
              would GetInstanceInfo return for the node
1753

1754
    """
1755
    return self._UnlockedGetAllInstancesInfo()
1756

    
1757
  def _UnlockedGetAllInstancesInfo(self):
1758
    my_dict = dict([(inst_uuid, self._UnlockedGetInstanceInfo(inst_uuid))
1759
                    for inst_uuid in self._UnlockedGetInstanceList()])
1760
    return my_dict
1761

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

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

1773
    """
1774
    return dict((uuid, inst)
1775
                for (uuid, inst) in self._config_data.instances.items()
1776
                if filter_fn(inst))
1777

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

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

1787
    """
1788
    return self._UnlockedGetInstanceInfoByName(inst_name)
1789

    
1790
  def _UnlockedGetInstanceInfoByName(self, inst_name):
1791
    for inst in self._UnlockedGetAllInstancesInfo().values():
1792
      if inst.name == inst_name:
1793
        return inst
1794
    return None
1795

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

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

1806
    @param inst_uuid: instance UUID to get name for
1807
    @type inst_uuid: string
1808
    @rtype: string
1809
    @return: instance name
1810

1811
    """
1812
    return self._UnlockedGetInstanceName(inst_uuid)
1813

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

1818
    @param inst_uuids: list of instance UUIDs to get names for
1819
    @type inst_uuids: list of strings
1820
    @rtype: list of strings
1821
    @return: list of instance names
1822

1823
    """
1824
    return self._UnlockedGetInstanceNames(inst_uuids)
1825

    
1826
  def _UnlockedGetInstanceNames(self, inst_uuids):
1827
    return [self._UnlockedGetInstanceName(uuid) for uuid in inst_uuids]
1828

    
1829
  @locking.ssynchronized(_config_lock)
1830
  def AddNode(self, node, ec_id):
1831
    """Add a node to the configuration.
1832

1833
    @type node: L{objects.Node}
1834
    @param node: a Node instance
1835

1836
    """
1837
    logging.info("Adding node %s to configuration", node.name)
1838

    
1839
    self._EnsureUUID(node, ec_id)
1840

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

    
1848
  @locking.ssynchronized(_config_lock)
1849
  def RemoveNode(self, node_uuid):
1850
    """Remove a node from the configuration.
1851

1852
    """
1853
    logging.info("Removing node %s from configuration", node_uuid)
1854

    
1855
    if node_uuid not in self._config_data.nodes:
1856
      raise errors.ConfigurationError("Unknown node '%s'" % node_uuid)
1857

    
1858
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_uuid])
1859
    del self._config_data.nodes[node_uuid]
1860
    self._config_data.cluster.serial_no += 1
1861
    self._WriteConfig()
1862

    
1863
  def ExpandNodeName(self, short_name):
1864
    """Attempt to expand an incomplete node name into a node UUID.
1865

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

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

    
1879
  def _UnlockedGetNodeInfo(self, node_uuid):
1880
    """Get the configuration of a node, as stored in the config.
1881

1882
    This function is for internal use, when the config lock is already
1883
    held.
1884

1885
    @param node_uuid: the node UUID
1886

1887
    @rtype: L{objects.Node}
1888
    @return: the node object
1889

1890
    """
1891
    if node_uuid not in self._config_data.nodes:
1892
      return None
1893

    
1894
    return self._config_data.nodes[node_uuid]
1895

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

1900
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1901

1902
    @param node_uuid: the node UUID
1903

1904
    @rtype: L{objects.Node}
1905
    @return: the node object
1906

1907
    """
1908
    return self._UnlockedGetNodeInfo(node_uuid)
1909

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

1914
    @param node_uuid: the node UUID
1915

1916
    @rtype: (list, list)
1917
    @return: a tuple with two lists: the primary and the secondary instances
1918

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

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

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

1938
    """
1939
    if primary_only:
1940
      nodes_fn = lambda inst: [inst.primary_node]
1941
    else:
1942
      nodes_fn = lambda inst: inst.all_nodes
1943

    
1944
    return frozenset(inst.uuid
1945
                     for inst in self._config_data.instances.values()
1946
                     for node_uuid in nodes_fn(inst)
1947
                     if self._UnlockedGetNodeInfo(node_uuid).group == uuid)
1948

    
1949
  def _UnlockedGetHvparamsString(self, hvname):
1950
    """Return the string representation of the list of hyervisor parameters of
1951
    the given hypervisor.
1952

1953
    @see: C{GetHvparams}
1954

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

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

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

1972
    """
1973
    return self._UnlockedGetHvparamsString(hvname)
1974

    
1975
  def _UnlockedGetNodeList(self):
1976
    """Return the list of nodes which are in the configuration.
1977

1978
    This function is for internal use, when the config lock is already
1979
    held.
1980

1981
    @rtype: list
1982

1983
    """
1984
    return self._config_data.nodes.keys()
1985

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

1990
    """
1991
    return self._UnlockedGetNodeList()
1992

    
1993
  def _UnlockedGetOnlineNodeList(self):
1994
    """Return the list of nodes which are online.
1995

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

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

2005
    """
2006
    return self._UnlockedGetOnlineNodeList()
2007

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

2012
    """
2013
    all_nodes = [self._UnlockedGetNodeInfo(node)
2014
                 for node in self._UnlockedGetNodeList()]
2015
    return [node.uuid for node in all_nodes if node.vm_capable]
2016

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

2021
    """
2022
    all_nodes = [self._UnlockedGetNodeInfo(node)
2023
                 for node in self._UnlockedGetNodeList()]
2024
    return [node.uuid for node in all_nodes if not node.vm_capable]
2025

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

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

2036
    """
2037
    return [(uuid, self._UnlockedGetNodeInfo(uuid)) for uuid in node_uuids]
2038

    
2039
  def _UnlockedGetAllNodesInfo(self):
2040
    """Gets configuration of all nodes.
2041

2042
    @note: See L{GetAllNodesInfo}
2043

2044
    """
2045
    return dict([(node_uuid, self._UnlockedGetNodeInfo(node_uuid))
2046
                 for node_uuid in self._UnlockedGetNodeList()])
2047

    
2048
  @locking.ssynchronized(_config_lock, shared=1)
2049
  def GetAllNodesInfo(self):
2050
    """Get the configuration of all nodes.
2051

2052
    @rtype: dict
2053
    @return: dict of (node, node_info), where node_info is what
2054
              would GetNodeInfo return for the node
2055

2056
    """
2057
    return self._UnlockedGetAllNodesInfo()
2058

    
2059
  def _UnlockedGetNodeInfoByName(self, node_name):
2060
    for node in self._UnlockedGetAllNodesInfo().values():
2061
      if node.name == node_name:
2062
        return node
2063
    return None
2064

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

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

2074
    """
2075
    return self._UnlockedGetNodeInfoByName(node_name)
2076

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

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

2086
    """
2087
    for nodegroup in self._UnlockedGetAllNodeGroupsInfo().values():
2088
      if nodegroup.name == nodegroup_name:
2089
        return nodegroup
2090
    return None
2091

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

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

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

2112
    """
2113
    return self._UnlockedGetNodeName(node_spec)
2114

    
2115
  def _UnlockedGetNodeNames(self, node_specs):
2116
    return [self._UnlockedGetNodeName(node_spec) for node_spec in node_specs]
2117

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

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

2127
    """
2128
    return self._UnlockedGetNodeNames(node_specs)
2129

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

2134
    @type node_uuids: list of string
2135
    @param node_uuids: List of node UUIDs
2136
    @rtype: frozenset
2137

2138
    """
2139
    return frozenset(self._UnlockedGetNodeInfo(uuid).group
2140
                     for uuid in node_uuids)
2141

    
2142
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
2143
    """Get the number of current and maximum desired and possible candidates.
2144

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

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

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

2166
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
2167

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

2173
    """
2174
    return self._UnlockedGetMasterCandidateStats(exceptions)
2175

    
2176
  @locking.ssynchronized(_config_lock)
2177
  def MaintainCandidatePool(self, exception_node_uuids):
2178
    """Try to grow the candidate pool to the desired size.
2179

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

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

    
2211
    return mod_list
2212

    
2213
  def _UnlockedAddNodeToGroup(self, node_uuid, nodegroup_uuid):
2214
    """Add a given node to the specified group.
2215

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

    
2226
  def _UnlockedRemoveNodeFromGroup(self, node):
2227
    """Remove a given node from its group.
2228

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

    
2241
  @locking.ssynchronized(_config_lock)
2242
  def AssignGroupNodes(self, mods):
2243
    """Changes the group of a number of nodes.
2244

2245
    @type mods: list of tuples; (node name, new group UUID)
2246
    @param mods: Node membership modifications
2247

2248
    """
2249
    groups = self._config_data.nodegroups
2250
    nodes = self._config_data.nodes
2251

    
2252
    resmod = []
2253

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

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

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

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

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

    
2288
      resmod.append((node, old_group, new_group))
2289

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

    
2295
      node.group = new_group.uuid
2296

    
2297
      # Update members of involved groups
2298
      if node.uuid in old_group.members:
2299
        old_group.members.remove(node.uuid)
2300
      if node.uuid not in new_group.members:
2301
        new_group.members.append(node.uuid)
2302

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

    
2309
    # Force ssconf update
2310
    self._config_data.cluster.serial_no += 1
2311

    
2312
    self._WriteConfig()
2313

    
2314
  def _BumpSerialNo(self):
2315
    """Bump up the serial number of the config.
2316

2317
    """
2318
    self._config_data.serial_no += 1
2319
    self._config_data.mtime = time.time()
2320

    
2321
  def _AllUUIDObjects(self):
2322
    """Returns all objects with uuid attributes.
2323

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

    
2333
  def _OpenConfig(self, accept_foreign):
2334
    """Read the config data from disk.
2335

2336
    """
2337
    raw_data = utils.ReadFile(self._cfg_file)
2338

    
2339
    try:
2340
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
2341
    except Exception, err:
2342
      raise errors.ConfigurationError(err)
2343

    
2344
    # Make sure the configuration has the right version
2345
    _ValidateConfig(data)
2346

    
2347
    if (not hasattr(data, "cluster") or
2348
        not hasattr(data.cluster, "rsahostkeypub")):
2349
      raise errors.ConfigurationError("Incomplete configuration"
2350
                                      " (missing cluster.rsahostkeypub)")
2351

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

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

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

    
2371
    # Upgrade configuration if needed
2372
    self._UpgradeConfig()
2373

    
2374
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2375

    
2376
  def _UpgradeConfig(self):
2377
    """Run any upgrade steps.
2378

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

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

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

    
2394
    # In-object upgrades
2395
    self._config_data.UpgradeConfig()
2396

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

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

    
2427
  def _DistributeConfig(self, feedback_fn):
2428
    """Distribute the configuration to the other nodes.
2429

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

2433
    """
2434
    if self._offline:
2435
      return True
2436

    
2437
    bad = False
2438

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

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

    
2463
        if feedback_fn:
2464
          feedback_fn(msg)
2465

    
2466
        bad = True
2467

    
2468
    return not bad
2469

    
2470
  def _WriteConfig(self, destination=None, feedback_fn=None):
2471
    """Write the configuration data to persistent storage.
2472

2473
    """
2474
    assert feedback_fn is None or callable(feedback_fn)
2475

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

    
2488
    if destination is None:
2489
      destination = self._cfg_file
2490
    self._BumpSerialNo()
2491
    txt = serializer.DumpJson(
2492
      self._config_data.ToDict(_with_private=True),
2493
      private_encoder=serializer.EncodeWithPrivateFields
2494
    )
2495

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

    
2509
    self.write_count += 1
2510

    
2511
    # and redistribute the config file to master candidates
2512
    self._DistributeConfig(feedback_fn)
2513

    
2514
    # Write ssconf files on all nodes (including locally)
2515
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2516
      if not self._offline:
2517
        result = self._GetRpc(None).call_write_ssconf_files(
2518
          self._UnlockedGetNodeNames(self._UnlockedGetOnlineNodeList()),
2519
          self._UnlockedGetSsconfValues())
2520

    
2521
        for nname, nresu in result.items():
2522
          msg = nresu.fail_msg
2523
          if msg:
2524
            errmsg = ("Error while uploading ssconf files to"
2525
                      " node %s: %s" % (nname, msg))
2526
            logging.warning(errmsg)
2527

    
2528
            if feedback_fn:
2529
              feedback_fn(errmsg)
2530

    
2531
      self._last_cluster_serial = self._config_data.cluster.serial_no
2532

    
2533
  def _GetAllHvparamsStrings(self, hypervisors):
2534
    """Get the hvparams of all given hypervisors from the config.
2535

2536
    @type hypervisors: list of string
2537
    @param hypervisors: list of hypervisor names
2538
    @rtype: dict of strings
2539
    @returns: dictionary mapping the hypervisor name to a string representation
2540
      of the hypervisor's hvparams
2541

2542
    """
2543
    hvparams = {}
2544
    for hv in hypervisors:
2545
      hvparams[hv] = self._UnlockedGetHvparamsString(hv)
2546
    return hvparams
2547

    
2548
  @staticmethod
2549
  def _ExtendByAllHvparamsStrings(ssconf_values, all_hvparams):
2550
    """Extends the ssconf_values dictionary by hvparams.
2551

2552
    @type ssconf_values: dict of strings
2553
    @param ssconf_values: dictionary mapping ssconf_keys to strings
2554
      representing the content of ssconf files
2555
    @type all_hvparams: dict of strings
2556
    @param all_hvparams: dictionary mapping hypervisor names to a string
2557
      representation of their hvparams
2558
    @rtype: same as ssconf_values
2559
    @returns: the ssconf_values dictionary extended by hvparams
2560

2561
    """
2562
    for hv in all_hvparams:
2563
      ssconf_key = constants.SS_HVPARAMS_PREF + hv
2564
      ssconf_values[ssconf_key] = all_hvparams[hv]
2565
    return ssconf_values
2566

    
2567
  def _UnlockedGetSsconfValues(self):
2568
    """Return the values needed by ssconf.
2569

2570
    @rtype: dict
2571
    @return: a dictionary with keys the ssconf names and values their
2572
        associated value
2573

2574
    """
2575
    fn = "\n".join
2576
    instance_names = utils.NiceSort(
2577
                       [inst.name for inst in
2578
                        self._UnlockedGetAllInstancesInfo().values()])
2579
    node_infos = self._UnlockedGetAllNodesInfo().values()
2580
    node_names = [node.name for node in node_infos]
2581
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2582
                    for ninfo in node_infos]
2583
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2584
                    for ninfo in node_infos]
2585

    
2586
    instance_data = fn(instance_names)
2587
    off_data = fn(node.name for node in node_infos if node.offline)
2588
    on_data = fn(node.name for node in node_infos if not node.offline)
2589
    mc_data = fn(node.name for node in node_infos if node.master_candidate)
2590
    mc_ips_data = fn(node.primary_ip for node in node_infos
2591
                     if node.master_candidate)
2592
    node_data = fn(node_names)
2593
    node_pri_ips_data = fn(node_pri_ips)
2594
    node_snd_ips_data = fn(node_snd_ips)
2595

    
2596
    cluster = self._config_data.cluster
2597
    cluster_tags = fn(cluster.GetTags())
2598

    
2599
    master_candidates_certs = fn("%s=%s" % (mc_uuid, mc_cert)
2600
                                 for mc_uuid, mc_cert
2601
                                 in cluster.candidate_certs.items())
2602

    
2603
    hypervisor_list = fn(cluster.enabled_hypervisors)
2604
    all_hvparams = self._GetAllHvparamsStrings(constants.HYPER_TYPES)
2605

    
2606
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2607

    
2608
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2609
                  self._config_data.nodegroups.values()]
2610
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2611
    networks = ["%s %s" % (net.uuid, net.name) for net in
2612
                self._config_data.networks.values()]
2613
    networks_data = fn(utils.NiceSort(networks))
2614

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

    
2652
  @locking.ssynchronized(_config_lock, shared=1)
2653
  def GetSsconfValues(self):
2654
    """Wrapper using lock around _UnlockedGetSsconf().
2655

2656
    """
2657
    return self._UnlockedGetSsconfValues()
2658

    
2659
  @locking.ssynchronized(_config_lock, shared=1)
2660
  def GetVGName(self):
2661
    """Return the volume group name.
2662

2663
    """
2664
    return self._config_data.cluster.volume_group_name
2665

    
2666
  @locking.ssynchronized(_config_lock)
2667
  def SetVGName(self, vg_name):
2668
    """Set the volume group name.
2669

2670
    """
2671
    self._config_data.cluster.volume_group_name = vg_name
2672
    self._config_data.cluster.serial_no += 1
2673
    self._WriteConfig()
2674

    
2675
  @locking.ssynchronized(_config_lock, shared=1)
2676
  def GetDRBDHelper(self):
2677
    """Return DRBD usermode helper.
2678

2679
    """
2680
    return self._config_data.cluster.drbd_usermode_helper
2681

    
2682
  @locking.ssynchronized(_config_lock)
2683
  def SetDRBDHelper(self, drbd_helper):
2684
    """Set DRBD usermode helper.
2685

2686
    """
2687
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2688
    self._config_data.cluster.serial_no += 1
2689
    self._WriteConfig()
2690

    
2691
  @locking.ssynchronized(_config_lock, shared=1)
2692
  def GetMACPrefix(self):
2693
    """Return the mac prefix.
2694

2695
    """
2696
    return self._config_data.cluster.mac_prefix
2697

    
2698
  @locking.ssynchronized(_config_lock, shared=1)
2699
  def GetClusterInfo(self):
2700
    """Returns information about the cluster
2701

2702
    @rtype: L{objects.Cluster}
2703
    @return: the cluster object
2704

2705
    """
2706
    return self._config_data.cluster
2707

    
2708
  @locking.ssynchronized(_config_lock, shared=1)
2709
  def HasAnyDiskOfType(self, dev_type):
2710
    """Check if in there is at disk of the given type in the configuration.
2711

2712
    """
2713
    return self._config_data.HasAnyDiskOfType(dev_type)
2714

    
2715
  @locking.ssynchronized(_config_lock)
2716
  def Update(self, target, feedback_fn, ec_id=None):
2717
    """Notify function to be called after updates.
2718

2719
    This function must be called when an object (as returned by
2720
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2721
    caller wants the modifications saved to the backing store. Note
2722
    that all modified objects will be saved, but the target argument
2723
    is the one the caller wants to ensure that it's saved.
2724

2725
    @param target: an instance of either L{objects.Cluster},
2726
        L{objects.Node} or L{objects.Instance} which is existing in
2727
        the cluster
2728
    @param feedback_fn: Callable feedback function
2729

2730
    """
2731
    if self._config_data is None:
2732
      raise errors.ProgrammerError("Configuration file not read,"
2733
                                   " cannot save.")
2734
    update_serial = False
2735
    if isinstance(target, objects.Cluster):
2736
      test = target == self._config_data.cluster
2737
    elif isinstance(target, objects.Node):
2738
      test = target in self._config_data.nodes.values()
2739
      update_serial = True
2740
    elif isinstance(target, objects.Instance):
2741
      test = target in self._config_data.instances.values()
2742
    elif isinstance(target, objects.NodeGroup):
2743
      test = target in self._config_data.nodegroups.values()
2744
    elif isinstance(target, objects.Network):
2745
      test = target in self._config_data.networks.values()
2746
    else:
2747
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2748
                                   " ConfigWriter.Update" % type(target))
2749
    if not test:
2750
      raise errors.ConfigurationError("Configuration updated since object"
2751
                                      " has been read or unknown object")
2752
    target.serial_no += 1
2753
    target.mtime = now = time.time()
2754

    
2755
    if update_serial:
2756
      # for node updates, we need to increase the cluster serial too
2757
      self._config_data.cluster.serial_no += 1
2758
      self._config_data.cluster.mtime = now
2759

    
2760
    if isinstance(target, objects.Instance):
2761
      self._UnlockedReleaseDRBDMinors(target.uuid)
2762

    
2763
    if ec_id is not None:
2764
      # Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
2765
      self._UnlockedCommitTemporaryIps(ec_id)
2766

    
2767
    self._WriteConfig(feedback_fn=feedback_fn)
2768

    
2769
  @locking.ssynchronized(_config_lock)
2770
  def DropECReservations(self, ec_id):
2771
    """Drop per-execution-context reservations
2772

2773
    """
2774
    for rm in self._all_rms:
2775
      rm.DropECReservations(ec_id)
2776

    
2777
  @locking.ssynchronized(_config_lock, shared=1)
2778
  def GetAllNetworksInfo(self):
2779
    """Get configuration info of all the networks.
2780

2781
    """
2782
    return dict(self._config_data.networks)
2783

    
2784
  def _UnlockedGetNetworkList(self):
2785
    """Get the list of networks.
2786

2787
    This function is for internal use, when the config lock is already held.
2788

2789
    """
2790
    return self._config_data.networks.keys()
2791

    
2792
  @locking.ssynchronized(_config_lock, shared=1)
2793
  def GetNetworkList(self):
2794
    """Get the list of networks.
2795

2796
    @return: array of networks, ex. ["main", "vlan100", "200]
2797

2798
    """
2799
    return self._UnlockedGetNetworkList()
2800

    
2801
  @locking.ssynchronized(_config_lock, shared=1)
2802
  def GetNetworkNames(self):
2803
    """Get a list of network names
2804

2805
    """
2806
    names = [net.name
2807
             for net in self._config_data.networks.values()]
2808
    return names
2809

    
2810
  def _UnlockedGetNetwork(self, uuid):
2811
    """Returns information about a network.
2812

2813
    This function is for internal use, when the config lock is already held.
2814

2815
    """
2816
    if uuid not in self._config_data.networks:
2817
      return None
2818

    
2819
    return self._config_data.networks[uuid]
2820

    
2821
  @locking.ssynchronized(_config_lock, shared=1)
2822
  def GetNetwork(self, uuid):
2823
    """Returns information about a network.
2824

2825
    It takes the information from the configuration file.
2826

2827
    @param uuid: UUID of the network
2828

2829
    @rtype: L{objects.Network}
2830
    @return: the network object
2831

2832
    """
2833
    return self._UnlockedGetNetwork(uuid)
2834

    
2835
  @locking.ssynchronized(_config_lock)
2836
  def AddNetwork(self, net, ec_id, check_uuid=True):
2837
    """Add a network to the configuration.
2838

2839
    @type net: L{objects.Network}
2840
    @param net: the Network object to add
2841
    @type ec_id: string
2842
    @param ec_id: unique id for the job to use when creating a missing UUID
2843

2844
    """
2845
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2846
    self._WriteConfig()
2847

    
2848
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2849
    """Add a network to the configuration.
2850

2851
    """
2852
    logging.info("Adding network %s to configuration", net.name)
2853

    
2854
    if check_uuid:
2855
      self._EnsureUUID(net, ec_id)
2856

    
2857
    net.serial_no = 1
2858
    net.ctime = net.mtime = time.time()
2859
    self._config_data.networks[net.uuid] = net
2860
    self._config_data.cluster.serial_no += 1
2861

    
2862
  def _UnlockedLookupNetwork(self, target):
2863
    """Lookup a network's UUID.
2864

2865
    @type target: string
2866
    @param target: network name or UUID
2867
    @rtype: string
2868
    @return: network UUID
2869
    @raises errors.OpPrereqError: when the target network cannot be found
2870

2871
    """
2872
    if target is None:
2873
      return None
2874
    if target in self._config_data.networks:
2875
      return target
2876
    for net in self._config_data.networks.values():
2877
      if net.name == target:
2878
        return net.uuid
2879
    raise errors.OpPrereqError("Network '%s' not found" % target,
2880
                               errors.ECODE_NOENT)
2881

    
2882
  @locking.ssynchronized(_config_lock, shared=1)
2883
  def LookupNetwork(self, target):
2884
    """Lookup a network's UUID.
2885

2886
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2887

2888
    @type target: string
2889
    @param target: network name or UUID
2890
    @rtype: string
2891
    @return: network UUID
2892

2893
    """
2894
    return self._UnlockedLookupNetwork(target)
2895

    
2896
  @locking.ssynchronized(_config_lock)
2897
  def RemoveNetwork(self, network_uuid):
2898
    """Remove a network from the configuration.
2899

2900
    @type network_uuid: string
2901
    @param network_uuid: the UUID of the network to remove
2902

2903
    """
2904
    logging.info("Removing network %s from configuration", network_uuid)
2905

    
2906
    if network_uuid not in self._config_data.networks:
2907
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2908

    
2909
    del self._config_data.networks[network_uuid]
2910
    self._config_data.cluster.serial_no += 1
2911
    self._WriteConfig()
2912

    
2913
  def _UnlockedGetGroupNetParams(self, net_uuid, node_uuid):
2914
    """Get the netparams (mode, link) of a network.
2915

2916
    Get a network's netparams for a given node.
2917

2918
    @type net_uuid: string
2919
    @param net_uuid: network uuid
2920
    @type node_uuid: string
2921
    @param node_uuid: node UUID
2922
    @rtype: dict or None
2923
    @return: netparams
2924

2925
    """
2926
    node_info = self._UnlockedGetNodeInfo(node_uuid)
2927
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2928
    netparams = nodegroup_info.networks.get(net_uuid, None)
2929

    
2930
    return netparams
2931

    
2932
  @locking.ssynchronized(_config_lock, shared=1)
2933
  def GetGroupNetParams(self, net_uuid, node_uuid):
2934
    """Locking wrapper of _UnlockedGetGroupNetParams()
2935

2936
    """
2937
    return self._UnlockedGetGroupNetParams(net_uuid, node_uuid)
2938

    
2939
  @locking.ssynchronized(_config_lock, shared=1)
2940
  def CheckIPInNodeGroup(self, ip, node_uuid):
2941
    """Check IP uniqueness in nodegroup.
2942

2943
    Check networks that are connected in the node's node group
2944
    if ip is contained in any of them. Used when creating/adding
2945
    a NIC to ensure uniqueness among nodegroups.
2946

2947
    @type ip: string
2948
    @param ip: ip address
2949
    @type node_uuid: string
2950
    @param node_uuid: node UUID
2951
    @rtype: (string, dict) or (None, None)
2952
    @return: (network name, netparams)
2953

2954
    """
2955
    if ip is None:
2956
      return (None, None)
2957
    node_info = self._UnlockedGetNodeInfo(node_uuid)
2958
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2959
    for net_uuid in nodegroup_info.networks.keys():
2960
      net_info = self._UnlockedGetNetwork(net_uuid)
2961
      pool = network.AddressPool(net_info)
2962
      if pool.Contains(ip):
2963
        return (net_info.name, nodegroup_info.networks[net_uuid])
2964

    
2965
    return (None, None)