Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 93f1e606

History | View | Annotate | Download (97.9 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 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, shared=1)
1255
  def GetInstanceCommunicationNetwork(self):
1256
    """Get cluster instance communication network
1257

1258
    @rtype: string
1259
    @return: instance communication network, which is the name of the
1260
             network used for instance communication
1261

1262
    """
1263
    return self._config_data.cluster.instance_communication_network
1264

    
1265
  @locking.ssynchronized(_config_lock)
1266
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1267
    """Add a node group to the configuration.
1268

1269
    This method calls group.UpgradeConfig() to fill any missing attributes
1270
    according to their default values.
1271

1272
    @type group: L{objects.NodeGroup}
1273
    @param group: the NodeGroup object to add
1274
    @type ec_id: string
1275
    @param ec_id: unique id for the job to use when creating a missing UUID
1276
    @type check_uuid: bool
1277
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1278
                       it does, ensure that it does not exist in the
1279
                       configuration already
1280

1281
    """
1282
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1283
    self._WriteConfig()
1284

    
1285
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1286
    """Add a node group to the configuration.
1287

1288
    """
1289
    logging.info("Adding node group %s to configuration", group.name)
1290

    
1291
    # Some code might need to add a node group with a pre-populated UUID
1292
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1293
    # the "does this UUID" exist already check.
1294
    if check_uuid:
1295
      self._EnsureUUID(group, ec_id)
1296

    
1297
    try:
1298
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1299
    except errors.OpPrereqError:
1300
      pass
1301
    else:
1302
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1303
                                 " node group (UUID: %s)" %
1304
                                 (group.name, existing_uuid),
1305
                                 errors.ECODE_EXISTS)
1306

    
1307
    group.serial_no = 1
1308
    group.ctime = group.mtime = time.time()
1309
    group.UpgradeConfig()
1310

    
1311
    self._config_data.nodegroups[group.uuid] = group
1312
    self._config_data.cluster.serial_no += 1
1313

    
1314
  @locking.ssynchronized(_config_lock)
1315
  def RemoveNodeGroup(self, group_uuid):
1316
    """Remove a node group from the configuration.
1317

1318
    @type group_uuid: string
1319
    @param group_uuid: the UUID of the node group to remove
1320

1321
    """
1322
    logging.info("Removing node group %s from configuration", group_uuid)
1323

    
1324
    if group_uuid not in self._config_data.nodegroups:
1325
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1326

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

    
1330
    del self._config_data.nodegroups[group_uuid]
1331
    self._config_data.cluster.serial_no += 1
1332
    self._WriteConfig()
1333

    
1334
  def _UnlockedLookupNodeGroup(self, target):
1335
    """Lookup a node group's UUID.
1336

1337
    @type target: string or None
1338
    @param target: group name or UUID or None to look for the default
1339
    @rtype: string
1340
    @return: nodegroup UUID
1341
    @raises errors.OpPrereqError: when the target group cannot be found
1342

1343
    """
1344
    if target is None:
1345
      if len(self._config_data.nodegroups) != 1:
1346
        raise errors.OpPrereqError("More than one node group exists. Target"
1347
                                   " group must be specified explicitly.")
1348
      else:
1349
        return self._config_data.nodegroups.keys()[0]
1350
    if target in self._config_data.nodegroups:
1351
      return target
1352
    for nodegroup in self._config_data.nodegroups.values():
1353
      if nodegroup.name == target:
1354
        return nodegroup.uuid
1355
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1356
                               errors.ECODE_NOENT)
1357

    
1358
  @locking.ssynchronized(_config_lock, shared=1)
1359
  def LookupNodeGroup(self, target):
1360
    """Lookup a node group's UUID.
1361

1362
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1363

1364
    @type target: string or None
1365
    @param target: group name or UUID or None to look for the default
1366
    @rtype: string
1367
    @return: nodegroup UUID
1368

1369
    """
1370
    return self._UnlockedLookupNodeGroup(target)
1371

    
1372
  def _UnlockedGetNodeGroup(self, uuid):
1373
    """Lookup a node group.
1374

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

1380
    """
1381
    if uuid not in self._config_data.nodegroups:
1382
      return None
1383

    
1384
    return self._config_data.nodegroups[uuid]
1385

    
1386
  @locking.ssynchronized(_config_lock, shared=1)
1387
  def GetNodeGroup(self, uuid):
1388
    """Lookup a node group.
1389

1390
    @type uuid: string
1391
    @param uuid: group UUID
1392
    @rtype: L{objects.NodeGroup} or None
1393
    @return: nodegroup object, or None if not found
1394

1395
    """
1396
    return self._UnlockedGetNodeGroup(uuid)
1397

    
1398
  def _UnlockedGetAllNodeGroupsInfo(self):
1399
    """Get the configuration of all node groups.
1400

1401
    """
1402
    return dict(self._config_data.nodegroups)
1403

    
1404
  @locking.ssynchronized(_config_lock, shared=1)
1405
  def GetAllNodeGroupsInfo(self):
1406
    """Get the configuration of all node groups.
1407

1408
    """
1409
    return self._UnlockedGetAllNodeGroupsInfo()
1410

    
1411
  @locking.ssynchronized(_config_lock, shared=1)
1412
  def GetAllNodeGroupsInfoDict(self):
1413
    """Get the configuration of all node groups expressed as a dictionary of
1414
    dictionaries.
1415

1416
    """
1417
    return dict(map(lambda (uuid, ng): (uuid, ng.ToDict()),
1418
                    self._UnlockedGetAllNodeGroupsInfo().items()))
1419

    
1420
  @locking.ssynchronized(_config_lock, shared=1)
1421
  def GetNodeGroupList(self):
1422
    """Get a list of node groups.
1423

1424
    """
1425
    return self._config_data.nodegroups.keys()
1426

    
1427
  @locking.ssynchronized(_config_lock, shared=1)
1428
  def GetNodeGroupMembersByNodes(self, nodes):
1429
    """Get nodes which are member in the same nodegroups as the given nodes.
1430

1431
    """
1432
    ngfn = lambda node_uuid: self._UnlockedGetNodeInfo(node_uuid).group
1433
    return frozenset(member_uuid
1434
                     for node_uuid in nodes
1435
                     for member_uuid in
1436
                       self._UnlockedGetNodeGroup(ngfn(node_uuid)).members)
1437

    
1438
  @locking.ssynchronized(_config_lock, shared=1)
1439
  def GetMultiNodeGroupInfo(self, group_uuids):
1440
    """Get the configuration of multiple node groups.
1441

1442
    @param group_uuids: List of node group UUIDs
1443
    @rtype: list
1444
    @return: List of tuples of (group_uuid, group_info)
1445

1446
    """
1447
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1448

    
1449
  @locking.ssynchronized(_config_lock)
1450
  def AddInstance(self, instance, ec_id):
1451
    """Add an instance to the config.
1452

1453
    This should be used after creating a new instance.
1454

1455
    @type instance: L{objects.Instance}
1456
    @param instance: the instance object
1457

1458
    """
1459
    if not isinstance(instance, objects.Instance):
1460
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1461

    
1462
    if instance.disk_template != constants.DT_DISKLESS:
1463
      all_lvs = instance.MapLVsByNode()
1464
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1465

    
1466
    all_macs = self._AllMACs()
1467
    for nic in instance.nics:
1468
      if nic.mac in all_macs:
1469
        raise errors.ConfigurationError("Cannot add instance %s:"
1470
                                        " MAC address '%s' already in use." %
1471
                                        (instance.name, nic.mac))
1472

    
1473
    self._CheckUniqueUUID(instance, include_temporary=False)
1474

    
1475
    instance.serial_no = 1
1476
    instance.ctime = instance.mtime = time.time()
1477
    self._config_data.instances[instance.uuid] = instance
1478
    self._config_data.cluster.serial_no += 1
1479
    self._UnlockedReleaseDRBDMinors(instance.uuid)
1480
    self._UnlockedCommitTemporaryIps(ec_id)
1481
    self._WriteConfig()
1482

    
1483
  def _EnsureUUID(self, item, ec_id):
1484
    """Ensures a given object has a valid UUID.
1485

1486
    @param item: the instance or node to be checked
1487
    @param ec_id: the execution context id for the uuid reservation
1488

1489
    """
1490
    if not item.uuid:
1491
      item.uuid = self._GenerateUniqueID(ec_id)
1492
    else:
1493
      self._CheckUniqueUUID(item, include_temporary=True)
1494

    
1495
  def _CheckUniqueUUID(self, item, include_temporary):
1496
    """Checks that the UUID of the given object is unique.
1497

1498
    @param item: the instance or node to be checked
1499
    @param include_temporary: whether temporarily generated UUID's should be
1500
              included in the check. If the UUID of the item to be checked is
1501
              a temporarily generated one, this has to be C{False}.
1502

1503
    """
1504
    if not item.uuid:
1505
      raise errors.ConfigurationError("'%s' must have an UUID" % (item.name,))
1506
    if item.uuid in self._AllIDs(include_temporary=include_temporary):
1507
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1508
                                      " in use" % (item.name, item.uuid))
1509

    
1510
  def _SetInstanceStatus(self, inst_uuid, status, disks_active):
1511
    """Set the instance's status to a given value.
1512

1513
    """
1514
    if inst_uuid not in self._config_data.instances:
1515
      raise errors.ConfigurationError("Unknown instance '%s'" %
1516
                                      inst_uuid)
1517
    instance = self._config_data.instances[inst_uuid]
1518

    
1519
    if status is None:
1520
      status = instance.admin_state
1521
    if disks_active is None:
1522
      disks_active = instance.disks_active
1523

    
1524
    assert status in constants.ADMINST_ALL, \
1525
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1526

    
1527
    if instance.admin_state != status or \
1528
       instance.disks_active != disks_active:
1529
      instance.admin_state = status
1530
      instance.disks_active = disks_active
1531
      instance.serial_no += 1
1532
      instance.mtime = time.time()
1533
      self._WriteConfig()
1534

    
1535
  @locking.ssynchronized(_config_lock)
1536
  def MarkInstanceUp(self, inst_uuid):
1537
    """Mark the instance status to up in the config.
1538

1539
    This also sets the instance disks active flag.
1540

1541
    """
1542
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_UP, True)
1543

    
1544
  @locking.ssynchronized(_config_lock)
1545
  def MarkInstanceOffline(self, inst_uuid):
1546
    """Mark the instance status to down in the config.
1547

1548
    This also clears the instance disks active flag.
1549

1550
    """
1551
    self._SetInstanceStatus(inst_uuid, constants.ADMINST_OFFLINE, False)
1552

    
1553
  @locking.ssynchronized(_config_lock)
1554
  def RemoveInstance(self, inst_uuid):
1555
    """Remove the instance from the configuration.
1556

1557
    """
1558
    if inst_uuid not in self._config_data.instances:
1559
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1560

    
1561
    # If a network port has been allocated to the instance,
1562
    # return it to the pool of free ports.
1563
    inst = self._config_data.instances[inst_uuid]
1564
    network_port = getattr(inst, "network_port", None)
1565
    if network_port is not None:
1566
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1567

    
1568
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1569

    
1570
    for nic in instance.nics:
1571
      if nic.network and nic.ip:
1572
        # Return all IP addresses to the respective address pools
1573
        self._UnlockedCommitIp(constants.RELEASE_ACTION, nic.network, nic.ip)
1574

    
1575
    del self._config_data.instances[inst_uuid]
1576
    self._config_data.cluster.serial_no += 1
1577
    self._WriteConfig()
1578

    
1579
  @locking.ssynchronized(_config_lock)
1580
  def RenameInstance(self, inst_uuid, new_name):
1581
    """Rename an instance.
1582

1583
    This needs to be done in ConfigWriter and not by RemoveInstance
1584
    combined with AddInstance as only we can guarantee an atomic
1585
    rename.
1586

1587
    """
1588
    if inst_uuid not in self._config_data.instances:
1589
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1590

    
1591
    inst = self._config_data.instances[inst_uuid]
1592
    inst.name = new_name
1593

    
1594
    for (_, disk) in enumerate(inst.disks):
1595
      if disk.dev_type in [constants.DT_FILE, constants.DT_SHARED_FILE]:
1596
        # rename the file paths in logical and physical id
1597
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1598
        disk.logical_id = (disk.logical_id[0],
1599
                           utils.PathJoin(file_storage_dir, inst.name,
1600
                                          os.path.basename(disk.logical_id[1])))
1601

    
1602
    # Force update of ssconf files
1603
    self._config_data.cluster.serial_no += 1
1604

    
1605
    self._WriteConfig()
1606

    
1607
  @locking.ssynchronized(_config_lock)
1608
  def MarkInstanceDown(self, inst_uuid):
1609
    """Mark the status of an instance to down in the configuration.
1610

1611
    This does not touch the instance disks active flag, as shut down instances
1612
    can still have active disks.
1613

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

    
1617
  @locking.ssynchronized(_config_lock)
1618
  def MarkInstanceDisksActive(self, inst_uuid):
1619
    """Mark the status of instance disks active.
1620

1621
    """
1622
    self._SetInstanceStatus(inst_uuid, None, True)
1623

    
1624
  @locking.ssynchronized(_config_lock)
1625
  def MarkInstanceDisksInactive(self, inst_uuid):
1626
    """Mark the status of instance disks inactive.
1627

1628
    """
1629
    self._SetInstanceStatus(inst_uuid, None, False)
1630

    
1631
  def _UnlockedGetInstanceList(self):
1632
    """Get the list of instances.
1633

1634
    This function is for internal use, when the config lock is already held.
1635

1636
    """
1637
    return self._config_data.instances.keys()
1638

    
1639
  @locking.ssynchronized(_config_lock, shared=1)
1640
  def GetInstanceList(self):
1641
    """Get the list of instances.
1642

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

1645
    """
1646
    return self._UnlockedGetInstanceList()
1647

    
1648
  def ExpandInstanceName(self, short_name):
1649
    """Attempt to expand an incomplete instance name.
1650

1651
    """
1652
    # Locking is done in L{ConfigWriter.GetAllInstancesInfo}
1653
    all_insts = self.GetAllInstancesInfo().values()
1654
    expanded_name = _MatchNameComponentIgnoreCase(
1655
                      short_name, [inst.name for inst in all_insts])
1656

    
1657
    if expanded_name is not None:
1658
      # there has to be exactly one instance with that name
1659
      inst = (filter(lambda n: n.name == expanded_name, all_insts)[0])
1660
      return (inst.uuid, inst.name)
1661
    else:
1662
      return (None, None)
1663

    
1664
  def _UnlockedGetInstanceInfo(self, inst_uuid):
1665
    """Returns information about an instance.
1666

1667
    This function is for internal use, when the config lock is already held.
1668

1669
    """
1670
    if inst_uuid not in self._config_data.instances:
1671
      return None
1672

    
1673
    return self._config_data.instances[inst_uuid]
1674

    
1675
  @locking.ssynchronized(_config_lock, shared=1)
1676
  def GetInstanceInfo(self, inst_uuid):
1677
    """Returns information about an instance.
1678

1679
    It takes the information from the configuration file. Other information of
1680
    an instance are taken from the live systems.
1681

1682
    @param inst_uuid: UUID of the instance
1683

1684
    @rtype: L{objects.Instance}
1685
    @return: the instance object
1686

1687
    """
1688
    return self._UnlockedGetInstanceInfo(inst_uuid)
1689

    
1690
  @locking.ssynchronized(_config_lock, shared=1)
1691
  def GetInstanceNodeGroups(self, inst_uuid, primary_only=False):
1692
    """Returns set of node group UUIDs for instance's nodes.
1693

1694
    @rtype: frozenset
1695

1696
    """
1697
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1698
    if not instance:
1699
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1700

    
1701
    if primary_only:
1702
      nodes = [instance.primary_node]
1703
    else:
1704
      nodes = instance.all_nodes
1705

    
1706
    return frozenset(self._UnlockedGetNodeInfo(node_uuid).group
1707
                     for node_uuid in nodes)
1708

    
1709
  @locking.ssynchronized(_config_lock, shared=1)
1710
  def GetInstanceNetworks(self, inst_uuid):
1711
    """Returns set of network UUIDs for instance's nics.
1712

1713
    @rtype: frozenset
1714

1715
    """
1716
    instance = self._UnlockedGetInstanceInfo(inst_uuid)
1717
    if not instance:
1718
      raise errors.ConfigurationError("Unknown instance '%s'" % inst_uuid)
1719

    
1720
    networks = set()
1721
    for nic in instance.nics:
1722
      if nic.network:
1723
        networks.add(nic.network)
1724

    
1725
    return frozenset(networks)
1726

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

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

1737
    """
1738
    return [(uuid, self._UnlockedGetInstanceInfo(uuid)) for uuid in inst_uuids]
1739

    
1740
  @locking.ssynchronized(_config_lock, shared=1)
1741
  def GetMultiInstanceInfoByName(self, inst_names):
1742
    """Get the configuration of multiple instances.
1743

1744
    @param inst_names: list of instance names
1745
    @rtype: list
1746
    @return: list of tuples (instance, instance_info), where
1747
        instance_info is what would GetInstanceInfo return for the
1748
        node, while keeping the original order
1749

1750
    """
1751
    result = []
1752
    for name in inst_names:
1753
      instance = self._UnlockedGetInstanceInfoByName(name)
1754
      result.append((instance.uuid, instance))
1755
    return result
1756

    
1757
  @locking.ssynchronized(_config_lock, shared=1)
1758
  def GetAllInstancesInfo(self):
1759
    """Get the configuration of all instances.
1760

1761
    @rtype: dict
1762
    @return: dict of (instance, instance_info), where instance_info is what
1763
              would GetInstanceInfo return for the node
1764

1765
    """
1766
    return self._UnlockedGetAllInstancesInfo()
1767

    
1768
  def _UnlockedGetAllInstancesInfo(self):
1769
    my_dict = dict([(inst_uuid, self._UnlockedGetInstanceInfo(inst_uuid))
1770
                    for inst_uuid in self._UnlockedGetInstanceList()])
1771
    return my_dict
1772

    
1773
  @locking.ssynchronized(_config_lock, shared=1)
1774
  def GetInstancesInfoByFilter(self, filter_fn):
1775
    """Get instance configuration with a filter.
1776

1777
    @type filter_fn: callable
1778
    @param filter_fn: Filter function receiving instance object as parameter,
1779
      returning boolean. Important: this function is called while the
1780
      configuration locks is held. It must not do any complex work or call
1781
      functions potentially leading to a deadlock. Ideally it doesn't call any
1782
      other functions and just compares instance attributes.
1783

1784
    """
1785
    return dict((uuid, inst)
1786
                for (uuid, inst) in self._config_data.instances.items()
1787
                if filter_fn(inst))
1788

    
1789
  @locking.ssynchronized(_config_lock, shared=1)
1790
  def GetInstanceInfoByName(self, inst_name):
1791
    """Get the L{objects.Instance} object for a named instance.
1792

1793
    @param inst_name: name of the instance to get information for
1794
    @type inst_name: string
1795
    @return: the corresponding L{objects.Instance} instance or None if no
1796
          information is available
1797

1798
    """
1799
    return self._UnlockedGetInstanceInfoByName(inst_name)
1800

    
1801
  def _UnlockedGetInstanceInfoByName(self, inst_name):
1802
    for inst in self._UnlockedGetAllInstancesInfo().values():
1803
      if inst.name == inst_name:
1804
        return inst
1805
    return None
1806

    
1807
  def _UnlockedGetInstanceName(self, inst_uuid):
1808
    inst_info = self._UnlockedGetInstanceInfo(inst_uuid)
1809
    if inst_info is None:
1810
      raise errors.OpExecError("Unknown instance: %s" % inst_uuid)
1811
    return inst_info.name
1812

    
1813
  @locking.ssynchronized(_config_lock, shared=1)
1814
  def GetInstanceName(self, inst_uuid):
1815
    """Gets the instance name for the passed instance.
1816

1817
    @param inst_uuid: instance UUID to get name for
1818
    @type inst_uuid: string
1819
    @rtype: string
1820
    @return: instance name
1821

1822
    """
1823
    return self._UnlockedGetInstanceName(inst_uuid)
1824

    
1825
  @locking.ssynchronized(_config_lock, shared=1)
1826
  def GetInstanceNames(self, inst_uuids):
1827
    """Gets the instance names for the passed list of nodes.
1828

1829
    @param inst_uuids: list of instance UUIDs to get names for
1830
    @type inst_uuids: list of strings
1831
    @rtype: list of strings
1832
    @return: list of instance names
1833

1834
    """
1835
    return self._UnlockedGetInstanceNames(inst_uuids)
1836

    
1837
  def _UnlockedGetInstanceNames(self, inst_uuids):
1838
    return [self._UnlockedGetInstanceName(uuid) for uuid in inst_uuids]
1839

    
1840
  @locking.ssynchronized(_config_lock)
1841
  def AddNode(self, node, ec_id):
1842
    """Add a node to the configuration.
1843

1844
    @type node: L{objects.Node}
1845
    @param node: a Node instance
1846

1847
    """
1848
    logging.info("Adding node %s to configuration", node.name)
1849

    
1850
    self._EnsureUUID(node, ec_id)
1851

    
1852
    node.serial_no = 1
1853
    node.ctime = node.mtime = time.time()
1854
    self._UnlockedAddNodeToGroup(node.uuid, node.group)
1855
    self._config_data.nodes[node.uuid] = node
1856
    self._config_data.cluster.serial_no += 1
1857
    self._WriteConfig()
1858

    
1859
  @locking.ssynchronized(_config_lock)
1860
  def RemoveNode(self, node_uuid):
1861
    """Remove a node from the configuration.
1862

1863
    """
1864
    logging.info("Removing node %s from configuration", node_uuid)
1865

    
1866
    if node_uuid not in self._config_data.nodes:
1867
      raise errors.ConfigurationError("Unknown node '%s'" % node_uuid)
1868

    
1869
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_uuid])
1870
    del self._config_data.nodes[node_uuid]
1871
    self._config_data.cluster.serial_no += 1
1872
    self._WriteConfig()
1873

    
1874
  def ExpandNodeName(self, short_name):
1875
    """Attempt to expand an incomplete node name into a node UUID.
1876

1877
    """
1878
    # Locking is done in L{ConfigWriter.GetAllNodesInfo}
1879
    all_nodes = self.GetAllNodesInfo().values()
1880
    expanded_name = _MatchNameComponentIgnoreCase(
1881
                      short_name, [node.name for node in all_nodes])
1882

    
1883
    if expanded_name is not None:
1884
      # there has to be exactly one node with that name
1885
      node = (filter(lambda n: n.name == expanded_name, all_nodes)[0])
1886
      return (node.uuid, node.name)
1887
    else:
1888
      return (None, None)
1889

    
1890
  def _UnlockedGetNodeInfo(self, node_uuid):
1891
    """Get the configuration of a node, as stored in the config.
1892

1893
    This function is for internal use, when the config lock is already
1894
    held.
1895

1896
    @param node_uuid: the node UUID
1897

1898
    @rtype: L{objects.Node}
1899
    @return: the node object
1900

1901
    """
1902
    if node_uuid not in self._config_data.nodes:
1903
      return None
1904

    
1905
    return self._config_data.nodes[node_uuid]
1906

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

1911
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1912

1913
    @param node_uuid: the node UUID
1914

1915
    @rtype: L{objects.Node}
1916
    @return: the node object
1917

1918
    """
1919
    return self._UnlockedGetNodeInfo(node_uuid)
1920

    
1921
  @locking.ssynchronized(_config_lock, shared=1)
1922
  def GetNodeInstances(self, node_uuid):
1923
    """Get the instances of a node, as stored in the config.
1924

1925
    @param node_uuid: the node UUID
1926

1927
    @rtype: (list, list)
1928
    @return: a tuple with two lists: the primary and the secondary instances
1929

1930
    """
1931
    pri = []
1932
    sec = []
1933
    for inst in self._config_data.instances.values():
1934
      if inst.primary_node == node_uuid:
1935
        pri.append(inst.uuid)
1936
      if node_uuid in inst.secondary_nodes:
1937
        sec.append(inst.uuid)
1938
    return (pri, sec)
1939

    
1940
  @locking.ssynchronized(_config_lock, shared=1)
1941
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1942
    """Get the instances of a node group.
1943

1944
    @param uuid: Node group UUID
1945
    @param primary_only: Whether to only consider primary nodes
1946
    @rtype: frozenset
1947
    @return: List of instance UUIDs in node group
1948

1949
    """
1950
    if primary_only:
1951
      nodes_fn = lambda inst: [inst.primary_node]
1952
    else:
1953
      nodes_fn = lambda inst: inst.all_nodes
1954

    
1955
    return frozenset(inst.uuid
1956
                     for inst in self._config_data.instances.values()
1957
                     for node_uuid in nodes_fn(inst)
1958
                     if self._UnlockedGetNodeInfo(node_uuid).group == uuid)
1959

    
1960
  def _UnlockedGetHvparamsString(self, hvname):
1961
    """Return the string representation of the list of hyervisor parameters of
1962
    the given hypervisor.
1963

1964
    @see: C{GetHvparams}
1965

1966
    """
1967
    result = ""
1968
    hvparams = self._config_data.cluster.hvparams[hvname]
1969
    for key in hvparams:
1970
      result += "%s=%s\n" % (key, hvparams[key])
1971
    return result
1972

    
1973
  @locking.ssynchronized(_config_lock, shared=1)
1974
  def GetHvparamsString(self, hvname):
1975
    """Return the hypervisor parameters of the given hypervisor.
1976

1977
    @type hvname: string
1978
    @param hvname: name of a hypervisor
1979
    @rtype: string
1980
    @return: string containing key-value-pairs, one pair on each line;
1981
      format: KEY=VALUE
1982

1983
    """
1984
    return self._UnlockedGetHvparamsString(hvname)
1985

    
1986
  def _UnlockedGetNodeList(self):
1987
    """Return the list of nodes which are in the configuration.
1988

1989
    This function is for internal use, when the config lock is already
1990
    held.
1991

1992
    @rtype: list
1993

1994
    """
1995
    return self._config_data.nodes.keys()
1996

    
1997
  @locking.ssynchronized(_config_lock, shared=1)
1998
  def GetNodeList(self):
1999
    """Return the list of nodes which are in the configuration.
2000

2001
    """
2002
    return self._UnlockedGetNodeList()
2003

    
2004
  def _UnlockedGetOnlineNodeList(self):
2005
    """Return the list of nodes which are online.
2006

2007
    """
2008
    all_nodes = [self._UnlockedGetNodeInfo(node)
2009
                 for node in self._UnlockedGetNodeList()]
2010
    return [node.uuid for node in all_nodes if not node.offline]
2011

    
2012
  @locking.ssynchronized(_config_lock, shared=1)
2013
  def GetOnlineNodeList(self):
2014
    """Return the list of nodes which are online.
2015

2016
    """
2017
    return self._UnlockedGetOnlineNodeList()
2018

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

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

    
2028
  @locking.ssynchronized(_config_lock, shared=1)
2029
  def GetNonVmCapableNodeList(self):
2030
    """Return the list of nodes which are not vm capable.
2031

2032
    """
2033
    all_nodes = [self._UnlockedGetNodeInfo(node)
2034
                 for node in self._UnlockedGetNodeList()]
2035
    return [node.uuid for node in all_nodes if not node.vm_capable]
2036

    
2037
  @locking.ssynchronized(_config_lock, shared=1)
2038
  def GetMultiNodeInfo(self, node_uuids):
2039
    """Get the configuration of multiple nodes.
2040

2041
    @param node_uuids: list of node UUIDs
2042
    @rtype: list
2043
    @return: list of tuples of (node, node_info), where node_info is
2044
        what would GetNodeInfo return for the node, in the original
2045
        order
2046

2047
    """
2048
    return [(uuid, self._UnlockedGetNodeInfo(uuid)) for uuid in node_uuids]
2049

    
2050
  def _UnlockedGetAllNodesInfo(self):
2051
    """Gets configuration of all nodes.
2052

2053
    @note: See L{GetAllNodesInfo}
2054

2055
    """
2056
    return dict([(node_uuid, self._UnlockedGetNodeInfo(node_uuid))
2057
                 for node_uuid in self._UnlockedGetNodeList()])
2058

    
2059
  @locking.ssynchronized(_config_lock, shared=1)
2060
  def GetAllNodesInfo(self):
2061
    """Get the configuration of all nodes.
2062

2063
    @rtype: dict
2064
    @return: dict of (node, node_info), where node_info is what
2065
              would GetNodeInfo return for the node
2066

2067
    """
2068
    return self._UnlockedGetAllNodesInfo()
2069

    
2070
  def _UnlockedGetNodeInfoByName(self, node_name):
2071
    for node in self._UnlockedGetAllNodesInfo().values():
2072
      if node.name == node_name:
2073
        return node
2074
    return None
2075

    
2076
  @locking.ssynchronized(_config_lock, shared=1)
2077
  def GetNodeInfoByName(self, node_name):
2078
    """Get the L{objects.Node} object for a named node.
2079

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

2085
    """
2086
    return self._UnlockedGetNodeInfoByName(node_name)
2087

    
2088
  @locking.ssynchronized(_config_lock, shared=1)
2089
  def GetNodeGroupInfoByName(self, nodegroup_name):
2090
    """Get the L{objects.NodeGroup} object for a named node group.
2091

2092
    @param nodegroup_name: name of the node group to get information for
2093
    @type nodegroup_name: string
2094
    @return: the corresponding L{objects.NodeGroup} instance or None if no
2095
          information is available
2096

2097
    """
2098
    for nodegroup in self._UnlockedGetAllNodeGroupsInfo().values():
2099
      if nodegroup.name == nodegroup_name:
2100
        return nodegroup
2101
    return None
2102

    
2103
  def _UnlockedGetNodeName(self, node_spec):
2104
    if isinstance(node_spec, objects.Node):
2105
      return node_spec.name
2106
    elif isinstance(node_spec, basestring):
2107
      node_info = self._UnlockedGetNodeInfo(node_spec)
2108
      if node_info is None:
2109
        raise errors.OpExecError("Unknown node: %s" % node_spec)
2110
      return node_info.name
2111
    else:
2112
      raise errors.ProgrammerError("Can't handle node spec '%s'" % node_spec)
2113

    
2114
  @locking.ssynchronized(_config_lock, shared=1)
2115
  def GetNodeName(self, node_spec):
2116
    """Gets the node name for the passed node.
2117

2118
    @param node_spec: node to get names for
2119
    @type node_spec: either node UUID or a L{objects.Node} object
2120
    @rtype: string
2121
    @return: node name
2122

2123
    """
2124
    return self._UnlockedGetNodeName(node_spec)
2125

    
2126
  def _UnlockedGetNodeNames(self, node_specs):
2127
    return [self._UnlockedGetNodeName(node_spec) for node_spec in node_specs]
2128

    
2129
  @locking.ssynchronized(_config_lock, shared=1)
2130
  def GetNodeNames(self, node_specs):
2131
    """Gets the node names for the passed list of nodes.
2132

2133
    @param node_specs: list of nodes to get names for
2134
    @type node_specs: list of either node UUIDs or L{objects.Node} objects
2135
    @rtype: list of strings
2136
    @return: list of node names
2137

2138
    """
2139
    return self._UnlockedGetNodeNames(node_specs)
2140

    
2141
  @locking.ssynchronized(_config_lock, shared=1)
2142
  def GetNodeGroupsFromNodes(self, node_uuids):
2143
    """Returns groups for a list of nodes.
2144

2145
    @type node_uuids: list of string
2146
    @param node_uuids: List of node UUIDs
2147
    @rtype: frozenset
2148

2149
    """
2150
    return frozenset(self._UnlockedGetNodeInfo(uuid).group
2151
                     for uuid in node_uuids)
2152

    
2153
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
2154
    """Get the number of current and maximum desired and possible candidates.
2155

2156
    @type exceptions: list
2157
    @param exceptions: if passed, list of nodes that should be ignored
2158
    @rtype: tuple
2159
    @return: tuple of (current, desired and possible, possible)
2160

2161
    """
2162
    mc_now = mc_should = mc_max = 0
2163
    for node in self._config_data.nodes.values():
2164
      if exceptions and node.uuid in exceptions:
2165
        continue
2166
      if not (node.offline or node.drained) and node.master_capable:
2167
        mc_max += 1
2168
      if node.master_candidate:
2169
        mc_now += 1
2170
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
2171
    return (mc_now, mc_should, mc_max)
2172

    
2173
  @locking.ssynchronized(_config_lock, shared=1)
2174
  def GetMasterCandidateStats(self, exceptions=None):
2175
    """Get the number of current and maximum possible candidates.
2176

2177
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
2178

2179
    @type exceptions: list
2180
    @param exceptions: if passed, list of nodes that should be ignored
2181
    @rtype: tuple
2182
    @return: tuple of (current, max)
2183

2184
    """
2185
    return self._UnlockedGetMasterCandidateStats(exceptions)
2186

    
2187
  @locking.ssynchronized(_config_lock)
2188
  def MaintainCandidatePool(self, exception_node_uuids):
2189
    """Try to grow the candidate pool to the desired size.
2190

2191
    @type exception_node_uuids: list
2192
    @param exception_node_uuids: if passed, list of nodes that should be ignored
2193
    @rtype: list
2194
    @return: list with the adjusted nodes (L{objects.Node} instances)
2195

2196
    """
2197
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(
2198
                          exception_node_uuids)
2199
    mod_list = []
2200
    if mc_now < mc_max:
2201
      node_list = self._config_data.nodes.keys()
2202
      random.shuffle(node_list)
2203
      for uuid in node_list:
2204
        if mc_now >= mc_max:
2205
          break
2206
        node = self._config_data.nodes[uuid]
2207
        if (node.master_candidate or node.offline or node.drained or
2208
            node.uuid in exception_node_uuids or not node.master_capable):
2209
          continue
2210
        mod_list.append(node)
2211
        node.master_candidate = True
2212
        node.serial_no += 1
2213
        mc_now += 1
2214
      if mc_now != mc_max:
2215
        # this should not happen
2216
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
2217
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
2218
      if mod_list:
2219
        self._config_data.cluster.serial_no += 1
2220
        self._WriteConfig()
2221

    
2222
    return mod_list
2223

    
2224
  def _UnlockedAddNodeToGroup(self, node_uuid, nodegroup_uuid):
2225
    """Add a given node to the specified group.
2226

2227
    """
2228
    if nodegroup_uuid not in self._config_data.nodegroups:
2229
      # This can happen if a node group gets deleted between its lookup and
2230
      # when we're adding the first node to it, since we don't keep a lock in
2231
      # the meantime. It's ok though, as we'll fail cleanly if the node group
2232
      # is not found anymore.
2233
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
2234
    if node_uuid not in self._config_data.nodegroups[nodegroup_uuid].members:
2235
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_uuid)
2236

    
2237
  def _UnlockedRemoveNodeFromGroup(self, node):
2238
    """Remove a given node from its group.
2239

2240
    """
2241
    nodegroup = node.group
2242
    if nodegroup not in self._config_data.nodegroups:
2243
      logging.warning("Warning: node '%s' has unknown node group '%s'"
2244
                      " (while being removed from it)", node.uuid, nodegroup)
2245
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
2246
    if node.uuid not in nodegroup_obj.members:
2247
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
2248
                      " (while being removed from it)", node.uuid, nodegroup)
2249
    else:
2250
      nodegroup_obj.members.remove(node.uuid)
2251

    
2252
  @locking.ssynchronized(_config_lock)
2253
  def AssignGroupNodes(self, mods):
2254
    """Changes the group of a number of nodes.
2255

2256
    @type mods: list of tuples; (node name, new group UUID)
2257
    @param mods: Node membership modifications
2258

2259
    """
2260
    groups = self._config_data.nodegroups
2261
    nodes = self._config_data.nodes
2262

    
2263
    resmod = []
2264

    
2265
    # Try to resolve UUIDs first
2266
    for (node_uuid, new_group_uuid) in mods:
2267
      try:
2268
        node = nodes[node_uuid]
2269
      except KeyError:
2270
        raise errors.ConfigurationError("Unable to find node '%s'" % node_uuid)
2271

    
2272
      if node.group == new_group_uuid:
2273
        # Node is being assigned to its current group
2274
        logging.debug("Node '%s' was assigned to its current group (%s)",
2275
                      node_uuid, node.group)
2276
        continue
2277

    
2278
      # Try to find current group of node
2279
      try:
2280
        old_group = groups[node.group]
2281
      except KeyError:
2282
        raise errors.ConfigurationError("Unable to find old group '%s'" %
2283
                                        node.group)
2284

    
2285
      # Try to find new group for node
2286
      try:
2287
        new_group = groups[new_group_uuid]
2288
      except KeyError:
2289
        raise errors.ConfigurationError("Unable to find new group '%s'" %
2290
                                        new_group_uuid)
2291

    
2292
      assert node.uuid in old_group.members, \
2293
        ("Inconsistent configuration: node '%s' not listed in members for its"
2294
         " old group '%s'" % (node.uuid, old_group.uuid))
2295
      assert node.uuid not in new_group.members, \
2296
        ("Inconsistent configuration: node '%s' already listed in members for"
2297
         " its new group '%s'" % (node.uuid, new_group.uuid))
2298

    
2299
      resmod.append((node, old_group, new_group))
2300

    
2301
    # Apply changes
2302
    for (node, old_group, new_group) in resmod:
2303
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
2304
        "Assigning to current group is not possible"
2305

    
2306
      node.group = new_group.uuid
2307

    
2308
      # Update members of involved groups
2309
      if node.uuid in old_group.members:
2310
        old_group.members.remove(node.uuid)
2311
      if node.uuid not in new_group.members:
2312
        new_group.members.append(node.uuid)
2313

    
2314
    # Update timestamps and serials (only once per node/group object)
2315
    now = time.time()
2316
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
2317
      obj.serial_no += 1
2318
      obj.mtime = now
2319

    
2320
    # Force ssconf update
2321
    self._config_data.cluster.serial_no += 1
2322

    
2323
    self._WriteConfig()
2324

    
2325
  def _BumpSerialNo(self):
2326
    """Bump up the serial number of the config.
2327

2328
    """
2329
    self._config_data.serial_no += 1
2330
    self._config_data.mtime = time.time()
2331

    
2332
  def _AllUUIDObjects(self):
2333
    """Returns all objects with uuid attributes.
2334

2335
    """
2336
    return (self._config_data.instances.values() +
2337
            self._config_data.nodes.values() +
2338
            self._config_data.nodegroups.values() +
2339
            self._config_data.networks.values() +
2340
            self._AllDisks() +
2341
            self._AllNICs() +
2342
            [self._config_data.cluster])
2343

    
2344
  def _OpenConfig(self, accept_foreign):
2345
    """Read the config data from disk.
2346

2347
    """
2348
    raw_data = utils.ReadFile(self._cfg_file)
2349

    
2350
    try:
2351
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
2352
    except Exception, err:
2353
      raise errors.ConfigurationError(err)
2354

    
2355
    # Make sure the configuration has the right version
2356
    _ValidateConfig(data)
2357

    
2358
    if (not hasattr(data, "cluster") or
2359
        not hasattr(data.cluster, "rsahostkeypub")):
2360
      raise errors.ConfigurationError("Incomplete configuration"
2361
                                      " (missing cluster.rsahostkeypub)")
2362

    
2363
    if not data.cluster.master_node in data.nodes:
2364
      msg = ("The configuration denotes node %s as master, but does not"
2365
             " contain information about this node" %
2366
             data.cluster.master_node)
2367
      raise errors.ConfigurationError(msg)
2368

    
2369
    master_info = data.nodes[data.cluster.master_node]
2370
    if master_info.name != self._my_hostname and not accept_foreign:
2371
      msg = ("The configuration denotes node %s as master, while my"
2372
             " hostname is %s; opening a foreign configuration is only"
2373
             " possible in accept_foreign mode" %
2374
             (master_info.name, self._my_hostname))
2375
      raise errors.ConfigurationError(msg)
2376

    
2377
    self._config_data = data
2378
    # reset the last serial as -1 so that the next write will cause
2379
    # ssconf update
2380
    self._last_cluster_serial = -1
2381

    
2382
    # Upgrade configuration if needed
2383
    self._UpgradeConfig()
2384

    
2385
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2386

    
2387
  def _UpgradeConfig(self):
2388
    """Run any upgrade steps.
2389

2390
    This method performs both in-object upgrades and also update some data
2391
    elements that need uniqueness across the whole configuration or interact
2392
    with other objects.
2393

2394
    @warning: this function will call L{_WriteConfig()}, but also
2395
        L{DropECReservations} so it needs to be called only from a
2396
        "safe" place (the constructor). If one wanted to call it with
2397
        the lock held, a DropECReservationUnlocked would need to be
2398
        created first, to avoid causing deadlock.
2399

2400
    """
2401
    # Keep a copy of the persistent part of _config_data to check for changes
2402
    # Serialization doesn't guarantee order in dictionaries
2403
    oldconf = copy.deepcopy(self._config_data.ToDict())
2404

    
2405
    # In-object upgrades
2406
    self._config_data.UpgradeConfig()
2407

    
2408
    for item in self._AllUUIDObjects():
2409
      if item.uuid is None:
2410
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
2411
    if not self._config_data.nodegroups:
2412
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
2413
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
2414
                                            members=[])
2415
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
2416
    for node in self._config_data.nodes.values():
2417
      if not node.group:
2418
        node.group = self.LookupNodeGroup(None)
2419
      # This is technically *not* an upgrade, but needs to be done both when
2420
      # nodegroups are being added, and upon normally loading the config,
2421
      # because the members list of a node group is discarded upon
2422
      # serializing/deserializing the object.
2423
      self._UnlockedAddNodeToGroup(node.uuid, node.group)
2424

    
2425
    modified = (oldconf != self._config_data.ToDict())
2426
    if modified:
2427
      self._WriteConfig()
2428
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
2429
      # only called at config init time, without the lock held
2430
      self.DropECReservations(_UPGRADE_CONFIG_JID)
2431
    else:
2432
      config_errors = self._UnlockedVerifyConfig()
2433
      if config_errors:
2434
        errmsg = ("Loaded configuration data is not consistent: %s" %
2435
                  (utils.CommaJoin(config_errors)))
2436
        logging.critical(errmsg)
2437

    
2438
  def _DistributeConfig(self, feedback_fn):
2439
    """Distribute the configuration to the other nodes.
2440

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

2444
    """
2445
    if self._offline:
2446
      return True
2447

    
2448
    bad = False
2449

    
2450
    node_list = []
2451
    addr_list = []
2452
    myhostname = self._my_hostname
2453
    # we can skip checking whether _UnlockedGetNodeInfo returns None
2454
    # since the node list comes from _UnlocketGetNodeList, and we are
2455
    # called with the lock held, so no modifications should take place
2456
    # in between
2457
    for node_uuid in self._UnlockedGetNodeList():
2458
      node_info = self._UnlockedGetNodeInfo(node_uuid)
2459
      if node_info.name == myhostname or not node_info.master_candidate:
2460
        continue
2461
      node_list.append(node_info.name)
2462
      addr_list.append(node_info.primary_ip)
2463

    
2464
    # TODO: Use dedicated resolver talking to config writer for name resolution
2465
    result = \
2466
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2467
    for to_node, to_result in result.items():
2468
      msg = to_result.fail_msg
2469
      if msg:
2470
        msg = ("Copy of file %s to node %s failed: %s" %
2471
               (self._cfg_file, to_node, msg))
2472
        logging.error(msg)
2473

    
2474
        if feedback_fn:
2475
          feedback_fn(msg)
2476

    
2477
        bad = True
2478

    
2479
    return not bad
2480

    
2481
  def _WriteConfig(self, destination=None, feedback_fn=None):
2482
    """Write the configuration data to persistent storage.
2483

2484
    """
2485
    assert feedback_fn is None or callable(feedback_fn)
2486

    
2487
    # Warn on config errors, but don't abort the save - the
2488
    # configuration has already been modified, and we can't revert;
2489
    # the best we can do is to warn the user and save as is, leaving
2490
    # recovery to the user
2491
    config_errors = self._UnlockedVerifyConfig()
2492
    if config_errors:
2493
      errmsg = ("Configuration data is not consistent: %s" %
2494
                (utils.CommaJoin(config_errors)))
2495
      logging.critical(errmsg)
2496
      if feedback_fn:
2497
        feedback_fn(errmsg)
2498

    
2499
    if destination is None:
2500
      destination = self._cfg_file
2501
    self._BumpSerialNo()
2502
    txt = serializer.DumpJson(
2503
      self._config_data.ToDict(_with_private=True),
2504
      private_encoder=serializer.EncodeWithPrivateFields
2505
    )
2506

    
2507
    getents = self._getents()
2508
    try:
2509
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2510
                               close=False, gid=getents.confd_gid, mode=0640)
2511
    except errors.LockError:
2512
      raise errors.ConfigurationError("The configuration file has been"
2513
                                      " modified since the last write, cannot"
2514
                                      " update")
2515
    try:
2516
      self._cfg_id = utils.GetFileID(fd=fd)
2517
    finally:
2518
      os.close(fd)
2519

    
2520
    self.write_count += 1
2521

    
2522
    # and redistribute the config file to master candidates
2523
    self._DistributeConfig(feedback_fn)
2524

    
2525
    # Write ssconf files on all nodes (including locally)
2526
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2527
      if not self._offline:
2528
        result = self._GetRpc(None).call_write_ssconf_files(
2529
          self._UnlockedGetNodeNames(self._UnlockedGetOnlineNodeList()),
2530
          self._UnlockedGetSsconfValues())
2531

    
2532
        for nname, nresu in result.items():
2533
          msg = nresu.fail_msg
2534
          if msg:
2535
            errmsg = ("Error while uploading ssconf files to"
2536
                      " node %s: %s" % (nname, msg))
2537
            logging.warning(errmsg)
2538

    
2539
            if feedback_fn:
2540
              feedback_fn(errmsg)
2541

    
2542
      self._last_cluster_serial = self._config_data.cluster.serial_no
2543

    
2544
  def _GetAllHvparamsStrings(self, hypervisors):
2545
    """Get the hvparams of all given hypervisors from the config.
2546

2547
    @type hypervisors: list of string
2548
    @param hypervisors: list of hypervisor names
2549
    @rtype: dict of strings
2550
    @returns: dictionary mapping the hypervisor name to a string representation
2551
      of the hypervisor's hvparams
2552

2553
    """
2554
    hvparams = {}
2555
    for hv in hypervisors:
2556
      hvparams[hv] = self._UnlockedGetHvparamsString(hv)
2557
    return hvparams
2558

    
2559
  @staticmethod
2560
  def _ExtendByAllHvparamsStrings(ssconf_values, all_hvparams):
2561
    """Extends the ssconf_values dictionary by hvparams.
2562

2563
    @type ssconf_values: dict of strings
2564
    @param ssconf_values: dictionary mapping ssconf_keys to strings
2565
      representing the content of ssconf files
2566
    @type all_hvparams: dict of strings
2567
    @param all_hvparams: dictionary mapping hypervisor names to a string
2568
      representation of their hvparams
2569
    @rtype: same as ssconf_values
2570
    @returns: the ssconf_values dictionary extended by hvparams
2571

2572
    """
2573
    for hv in all_hvparams:
2574
      ssconf_key = constants.SS_HVPARAMS_PREF + hv
2575
      ssconf_values[ssconf_key] = all_hvparams[hv]
2576
    return ssconf_values
2577

    
2578
  def _UnlockedGetSsconfValues(self):
2579
    """Return the values needed by ssconf.
2580

2581
    @rtype: dict
2582
    @return: a dictionary with keys the ssconf names and values their
2583
        associated value
2584

2585
    """
2586
    fn = "\n".join
2587
    instance_names = utils.NiceSort(
2588
                       [inst.name for inst in
2589
                        self._UnlockedGetAllInstancesInfo().values()])
2590
    node_infos = self._UnlockedGetAllNodesInfo().values()
2591
    node_names = [node.name for node in node_infos]
2592
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2593
                    for ninfo in node_infos]
2594
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2595
                    for ninfo in node_infos]
2596

    
2597
    instance_data = fn(instance_names)
2598
    off_data = fn(node.name for node in node_infos if node.offline)
2599
    on_data = fn(node.name for node in node_infos if not node.offline)
2600
    mc_data = fn(node.name for node in node_infos if node.master_candidate)
2601
    mc_ips_data = fn(node.primary_ip for node in node_infos
2602
                     if node.master_candidate)
2603
    node_data = fn(node_names)
2604
    node_pri_ips_data = fn(node_pri_ips)
2605
    node_snd_ips_data = fn(node_snd_ips)
2606

    
2607
    cluster = self._config_data.cluster
2608
    cluster_tags = fn(cluster.GetTags())
2609

    
2610
    master_candidates_certs = fn("%s=%s" % (mc_uuid, mc_cert)
2611
                                 for mc_uuid, mc_cert
2612
                                 in cluster.candidate_certs.items())
2613

    
2614
    hypervisor_list = fn(cluster.enabled_hypervisors)
2615
    all_hvparams = self._GetAllHvparamsStrings(constants.HYPER_TYPES)
2616

    
2617
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2618

    
2619
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2620
                  self._config_data.nodegroups.values()]
2621
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2622
    networks = ["%s %s" % (net.uuid, net.name) for net in
2623
                self._config_data.networks.values()]
2624
    networks_data = fn(utils.NiceSort(networks))
2625

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

    
2663
  @locking.ssynchronized(_config_lock, shared=1)
2664
  def GetSsconfValues(self):
2665
    """Wrapper using lock around _UnlockedGetSsconf().
2666

2667
    """
2668
    return self._UnlockedGetSsconfValues()
2669

    
2670
  @locking.ssynchronized(_config_lock, shared=1)
2671
  def GetVGName(self):
2672
    """Return the volume group name.
2673

2674
    """
2675
    return self._config_data.cluster.volume_group_name
2676

    
2677
  @locking.ssynchronized(_config_lock)
2678
  def SetVGName(self, vg_name):
2679
    """Set the volume group name.
2680

2681
    """
2682
    self._config_data.cluster.volume_group_name = vg_name
2683
    self._config_data.cluster.serial_no += 1
2684
    self._WriteConfig()
2685

    
2686
  @locking.ssynchronized(_config_lock, shared=1)
2687
  def GetDRBDHelper(self):
2688
    """Return DRBD usermode helper.
2689

2690
    """
2691
    return self._config_data.cluster.drbd_usermode_helper
2692

    
2693
  @locking.ssynchronized(_config_lock)
2694
  def SetDRBDHelper(self, drbd_helper):
2695
    """Set DRBD usermode helper.
2696

2697
    """
2698
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2699
    self._config_data.cluster.serial_no += 1
2700
    self._WriteConfig()
2701

    
2702
  @locking.ssynchronized(_config_lock, shared=1)
2703
  def GetMACPrefix(self):
2704
    """Return the mac prefix.
2705

2706
    """
2707
    return self._config_data.cluster.mac_prefix
2708

    
2709
  @locking.ssynchronized(_config_lock, shared=1)
2710
  def GetClusterInfo(self):
2711
    """Returns information about the cluster
2712

2713
    @rtype: L{objects.Cluster}
2714
    @return: the cluster object
2715

2716
    """
2717
    return self._config_data.cluster
2718

    
2719
  @locking.ssynchronized(_config_lock, shared=1)
2720
  def HasAnyDiskOfType(self, dev_type):
2721
    """Check if in there is at disk of the given type in the configuration.
2722

2723
    """
2724
    return self._config_data.HasAnyDiskOfType(dev_type)
2725

    
2726
  @locking.ssynchronized(_config_lock)
2727
  def Update(self, target, feedback_fn, ec_id=None):
2728
    """Notify function to be called after updates.
2729

2730
    This function must be called when an object (as returned by
2731
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2732
    caller wants the modifications saved to the backing store. Note
2733
    that all modified objects will be saved, but the target argument
2734
    is the one the caller wants to ensure that it's saved.
2735

2736
    @param target: an instance of either L{objects.Cluster},
2737
        L{objects.Node} or L{objects.Instance} which is existing in
2738
        the cluster
2739
    @param feedback_fn: Callable feedback function
2740

2741
    """
2742
    if self._config_data is None:
2743
      raise errors.ProgrammerError("Configuration file not read,"
2744
                                   " cannot save.")
2745
    update_serial = False
2746
    if isinstance(target, objects.Cluster):
2747
      test = target == self._config_data.cluster
2748
    elif isinstance(target, objects.Node):
2749
      test = target in self._config_data.nodes.values()
2750
      update_serial = True
2751
    elif isinstance(target, objects.Instance):
2752
      test = target in self._config_data.instances.values()
2753
    elif isinstance(target, objects.NodeGroup):
2754
      test = target in self._config_data.nodegroups.values()
2755
    elif isinstance(target, objects.Network):
2756
      test = target in self._config_data.networks.values()
2757
    else:
2758
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2759
                                   " ConfigWriter.Update" % type(target))
2760
    if not test:
2761
      raise errors.ConfigurationError("Configuration updated since object"
2762
                                      " has been read or unknown object")
2763
    target.serial_no += 1
2764
    target.mtime = now = time.time()
2765

    
2766
    if update_serial:
2767
      # for node updates, we need to increase the cluster serial too
2768
      self._config_data.cluster.serial_no += 1
2769
      self._config_data.cluster.mtime = now
2770

    
2771
    if isinstance(target, objects.Instance):
2772
      self._UnlockedReleaseDRBDMinors(target.uuid)
2773

    
2774
    if ec_id is not None:
2775
      # Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
2776
      self._UnlockedCommitTemporaryIps(ec_id)
2777

    
2778
    self._WriteConfig(feedback_fn=feedback_fn)
2779

    
2780
  @locking.ssynchronized(_config_lock)
2781
  def DropECReservations(self, ec_id):
2782
    """Drop per-execution-context reservations
2783

2784
    """
2785
    for rm in self._all_rms:
2786
      rm.DropECReservations(ec_id)
2787

    
2788
  @locking.ssynchronized(_config_lock, shared=1)
2789
  def GetAllNetworksInfo(self):
2790
    """Get configuration info of all the networks.
2791

2792
    """
2793
    return dict(self._config_data.networks)
2794

    
2795
  def _UnlockedGetNetworkList(self):
2796
    """Get the list of networks.
2797

2798
    This function is for internal use, when the config lock is already held.
2799

2800
    """
2801
    return self._config_data.networks.keys()
2802

    
2803
  @locking.ssynchronized(_config_lock, shared=1)
2804
  def GetNetworkList(self):
2805
    """Get the list of networks.
2806

2807
    @return: array of networks, ex. ["main", "vlan100", "200]
2808

2809
    """
2810
    return self._UnlockedGetNetworkList()
2811

    
2812
  @locking.ssynchronized(_config_lock, shared=1)
2813
  def GetNetworkNames(self):
2814
    """Get a list of network names
2815

2816
    """
2817
    names = [net.name
2818
             for net in self._config_data.networks.values()]
2819
    return names
2820

    
2821
  def _UnlockedGetNetwork(self, uuid):
2822
    """Returns information about a network.
2823

2824
    This function is for internal use, when the config lock is already held.
2825

2826
    """
2827
    if uuid not in self._config_data.networks:
2828
      return None
2829

    
2830
    return self._config_data.networks[uuid]
2831

    
2832
  @locking.ssynchronized(_config_lock, shared=1)
2833
  def GetNetwork(self, uuid):
2834
    """Returns information about a network.
2835

2836
    It takes the information from the configuration file.
2837

2838
    @param uuid: UUID of the network
2839

2840
    @rtype: L{objects.Network}
2841
    @return: the network object
2842

2843
    """
2844
    return self._UnlockedGetNetwork(uuid)
2845

    
2846
  @locking.ssynchronized(_config_lock)
2847
  def AddNetwork(self, net, ec_id, check_uuid=True):
2848
    """Add a network to the configuration.
2849

2850
    @type net: L{objects.Network}
2851
    @param net: the Network object to add
2852
    @type ec_id: string
2853
    @param ec_id: unique id for the job to use when creating a missing UUID
2854

2855
    """
2856
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2857
    self._WriteConfig()
2858

    
2859
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2860
    """Add a network to the configuration.
2861

2862
    """
2863
    logging.info("Adding network %s to configuration", net.name)
2864

    
2865
    if check_uuid:
2866
      self._EnsureUUID(net, ec_id)
2867

    
2868
    net.serial_no = 1
2869
    net.ctime = net.mtime = time.time()
2870
    self._config_data.networks[net.uuid] = net
2871
    self._config_data.cluster.serial_no += 1
2872

    
2873
  def _UnlockedLookupNetwork(self, target):
2874
    """Lookup a network's UUID.
2875

2876
    @type target: string
2877
    @param target: network name or UUID
2878
    @rtype: string
2879
    @return: network UUID
2880
    @raises errors.OpPrereqError: when the target network cannot be found
2881

2882
    """
2883
    if target is None:
2884
      return None
2885
    if target in self._config_data.networks:
2886
      return target
2887
    for net in self._config_data.networks.values():
2888
      if net.name == target:
2889
        return net.uuid
2890
    raise errors.OpPrereqError("Network '%s' not found" % target,
2891
                               errors.ECODE_NOENT)
2892

    
2893
  @locking.ssynchronized(_config_lock, shared=1)
2894
  def LookupNetwork(self, target):
2895
    """Lookup a network's UUID.
2896

2897
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2898

2899
    @type target: string
2900
    @param target: network name or UUID
2901
    @rtype: string
2902
    @return: network UUID
2903

2904
    """
2905
    return self._UnlockedLookupNetwork(target)
2906

    
2907
  @locking.ssynchronized(_config_lock)
2908
  def RemoveNetwork(self, network_uuid):
2909
    """Remove a network from the configuration.
2910

2911
    @type network_uuid: string
2912
    @param network_uuid: the UUID of the network to remove
2913

2914
    """
2915
    logging.info("Removing network %s from configuration", network_uuid)
2916

    
2917
    if network_uuid not in self._config_data.networks:
2918
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2919

    
2920
    del self._config_data.networks[network_uuid]
2921
    self._config_data.cluster.serial_no += 1
2922
    self._WriteConfig()
2923

    
2924
  def _UnlockedGetGroupNetParams(self, net_uuid, node_uuid):
2925
    """Get the netparams (mode, link) of a network.
2926

2927
    Get a network's netparams for a given node.
2928

2929
    @type net_uuid: string
2930
    @param net_uuid: network uuid
2931
    @type node_uuid: string
2932
    @param node_uuid: node UUID
2933
    @rtype: dict or None
2934
    @return: netparams
2935

2936
    """
2937
    node_info = self._UnlockedGetNodeInfo(node_uuid)
2938
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2939
    netparams = nodegroup_info.networks.get(net_uuid, None)
2940

    
2941
    return netparams
2942

    
2943
  @locking.ssynchronized(_config_lock, shared=1)
2944
  def GetGroupNetParams(self, net_uuid, node_uuid):
2945
    """Locking wrapper of _UnlockedGetGroupNetParams()
2946

2947
    """
2948
    return self._UnlockedGetGroupNetParams(net_uuid, node_uuid)
2949

    
2950
  @locking.ssynchronized(_config_lock, shared=1)
2951
  def CheckIPInNodeGroup(self, ip, node_uuid):
2952
    """Check IP uniqueness in nodegroup.
2953

2954
    Check networks that are connected in the node's node group
2955
    if ip is contained in any of them. Used when creating/adding
2956
    a NIC to ensure uniqueness among nodegroups.
2957

2958
    @type ip: string
2959
    @param ip: ip address
2960
    @type node_uuid: string
2961
    @param node_uuid: node UUID
2962
    @rtype: (string, dict) or (None, None)
2963
    @return: (network name, netparams)
2964

2965
    """
2966
    if ip is None:
2967
      return (None, None)
2968
    node_info = self._UnlockedGetNodeInfo(node_uuid)
2969
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2970
    for net_uuid in nodegroup_info.networks.keys():
2971
      net_info = self._UnlockedGetNetwork(net_uuid)
2972
      pool = network.AddressPool(net_info)
2973
      if pool.Contains(ip):
2974
        return (net_info.name, nodegroup_info.networks[net_uuid])
2975

    
2976
    return (None, None)