Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ e8e079f3

History | View | Annotate | Download (83.3 kB)

1
#
2
#
3

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

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

    
56

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

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

    
62

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

66
  This only verifies the version of the configuration.
67

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

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

    
75

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

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

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

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

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

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

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

    
111
  def GetECReserved(self, ec_id):
112
    ec_reserved = set()
113
    if ec_id in self._ec_reserved:
114
      ec_reserved.update(self._ec_reserved[ec_id])
115
    return ec_reserved
116

    
117

    
118
  def Generate(self, existing, generate_one_fn, ec_id):
119
    """Generate a new resource of this type
120

121
    """
122
    assert callable(generate_one_fn)
123

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

    
137

    
138
def _MatchNameComponentIgnoreCase(short_name, names):
139
  """Wrapper around L{utils.text.MatchNameComponent}.
140

141
  """
142
  return utils.MatchNameComponent(short_name, names, case_sensitive=False)
143

    
144

    
145
def _CheckInstanceDiskIvNames(disks):
146
  """Checks if instance's disks' C{iv_name} attributes are in order.
147

148
  @type disks: list of L{objects.Disk}
149
  @param disks: List of disks
150
  @rtype: list of tuples; (int, string, string)
151
  @return: List of wrongly named disks, each tuple contains disk index,
152
    expected and actual name
153

154
  """
155
  result = []
156

    
157
  for (idx, disk) in enumerate(disks):
158
    exp_iv_name = "disk/%s" % idx
159
    if disk.iv_name != exp_iv_name:
160
      result.append((idx, exp_iv_name, disk.iv_name))
161

    
162
  return result
163

    
164

    
165
class ConfigWriter:
166
  """The interface to the cluster configuration.
167

168
  @ivar _temporary_lvs: reservation manager for temporary LVs
169
  @ivar _all_rms: a list of all temporary reservation managers
170

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

    
202
  def _GetRpc(self, address_list):
203
    """Returns RPC runner for configuration.
204

205
    """
206
    return rpc.ConfigRunner(self._context, address_list)
207

    
208
  def SetContext(self, context):
209
    """Sets Ganeti context.
210

211
    """
212
    self._context = context
213

    
214
  # this method needs to be static, so that we can call it on the class
215
  @staticmethod
216
  def IsCluster():
217
    """Check if the cluster is configured.
218

219
    """
220
    return os.path.exists(pathutils.CLUSTER_CONF_FILE)
221

    
222
  def _GenerateOneMAC(self):
223
    """Generate one mac address
224

225
    """
226
    prefix = self._config_data.cluster.mac_prefix
227
    byte1 = random.randrange(0, 256)
228
    byte2 = random.randrange(0, 256)
229
    byte3 = random.randrange(0, 256)
230
    mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
231
    return mac
232

    
233
  @locking.ssynchronized(_config_lock, shared=1)
234
  def GetNdParams(self, node):
235
    """Get the node params populated with cluster defaults.
236

237
    @type node: L{objects.Node}
238
    @param node: The node we want to know the params for
239
    @return: A dict with the filled in node params
240

241
    """
242
    nodegroup = self._UnlockedGetNodeGroup(node.group)
243
    return self._config_data.cluster.FillND(node, nodegroup)
244

    
245
  @locking.ssynchronized(_config_lock, shared=1)
246
  def GetInstanceDiskParams(self, instance):
247
    """Get the disk params populated with inherit chain.
248

249
    @type instance: L{objects.Instance}
250
    @param instance: The instance we want to know the params for
251
    @return: A dict with the filled in disk params
252

253
    """
254
    node = self._UnlockedGetNodeInfo(instance.primary_node)
255
    nodegroup = self._UnlockedGetNodeGroup(node.group)
256
    return self._UnlockedGetGroupDiskParams(nodegroup)
257

    
258
  @locking.ssynchronized(_config_lock, shared=1)
259
  def GetGroupDiskParams(self, group):
260
    """Get the disk params populated with inherit chain.
261

262
    @type group: L{objects.NodeGroup}
263
    @param group: The group we want to know the params for
264
    @return: A dict with the filled in disk params
265

266
    """
267
    return self._UnlockedGetGroupDiskParams(group)
268

    
269
  def _UnlockedGetGroupDiskParams(self, group):
270
    """Get the disk params populated with inherit chain down to node-group.
271

272
    @type group: L{objects.NodeGroup}
273
    @param group: The group we want to know the params for
274
    @return: A dict with the filled in disk params
275

276
    """
277
    return self._config_data.cluster.SimpleFillDP(group.diskparams)
278

    
279
  @locking.ssynchronized(_config_lock, shared=1)
280
  def GenerateMAC(self, ec_id):
281
    """Generate a MAC for an instance.
282

283
    This should check the current instances for duplicates.
284

285
    """
286
    existing = self._AllMACs()
287
    return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
288

    
289
  @locking.ssynchronized(_config_lock, shared=1)
290
  def ReserveMAC(self, mac, ec_id):
291
    """Reserve a MAC for an instance.
292

293
    This only checks instances managed by this cluster, it does not
294
    check for potential collisions elsewhere.
295

296
    """
297
    all_macs = self._AllMACs()
298
    if mac in all_macs:
299
      raise errors.ReservationError("mac already in use")
300
    else:
301
      self._temporary_macs.Reserve(ec_id, mac)
302

    
303
  def _UnlockedCommitTemporaryIps(self, ec_id):
304
    """Commit all reserved IP address to their respective pools
305

306
    """
307
    for action, address, net_uuid in self._temporary_ips.GetECReserved(ec_id):
308
      self._UnlockedCommitIp(action, net_uuid, address)
309

    
310
  def _UnlockedCommitIp(self, action, net_uuid, address):
311
    """Commit a reserved IP address to an IP pool.
312

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

315
    """
316
    nobj = self._UnlockedGetNetwork(net_uuid)
317
    pool = network.AddressPool(nobj)
318
    if action == 'reserve':
319
      pool.Reserve(address)
320
    elif action == 'release':
321
      pool.Release(address)
322

    
323
  def _UnlockedReleaseIp(self, net_uuid, address, ec_id):
324
    """Give a specific IP address back to an IP pool.
325

326
    The IP address is returned to the IP pool designated by pool_id and marked
327
    as reserved.
328

329
    """
330
    nobj = self._UnlockedGetNetwork(net_uuid)
331
    pool = network.AddressPool(nobj)
332
    self._temporary_ips.Reserve(ec_id, ('release', address, net_uuid))
333

    
334
  @locking.ssynchronized(_config_lock, shared=1)
335
  def ReleaseIp(self, network, address, ec_id):
336
    """Give a specified IP address back to an IP pool.
337

338
    This is just a wrapper around _UnlockedReleaseIp.
339

340
    """
341
    net_uuid = self._UnlockedLookupNetwork(network)
342
    if net_uuid:
343
      self._UnlockedReleaseIp(net_uuid, address, ec_id)
344

    
345
  @locking.ssynchronized(_config_lock, shared=1)
346
  def GenerateIp(self, net, ec_id):
347
    """Find a free IPv4 address for an instance.
348

349
    """
350
    net_uuid = self._UnlockedLookupNetwork(net)
351
    nobj = self._UnlockedGetNetwork(net_uuid)
352
    pool = network.AddressPool(nobj)
353
    gen_free = pool.GenerateFree()
354

    
355
    def gen_one():
356
      try:
357
        ip = gen_free()
358
      except StopIteration:
359
        raise errors.ReservationError("Cannot generate IP. Network is full")
360
      return ("reserve", ip, net_uuid)
361

    
362
    _ ,address, _ = self._temporary_ips.Generate([], gen_one, ec_id)
363
    return address
364

    
365
  def _UnlockedReserveIp(self, net_uuid, address, ec_id):
366
    """Reserve a given IPv4 address for use by an instance.
367

368
    """
369
    nobj = self._UnlockedGetNetwork(net_uuid)
370
    pool = network.AddressPool(nobj)
371
    try:
372
      isreserved = pool.IsReserved(address)
373
    except errors.AddressPoolError:
374
      raise errors.ReservationError("IP address not in network")
375
    if isreserved:
376
      raise errors.ReservationError("IP address already in use")
377

    
378
    return self._temporary_ips.Reserve(ec_id, ('reserve', address, net_uuid))
379

    
380

    
381
  @locking.ssynchronized(_config_lock, shared=1)
382
  def ReserveIp(self, net, address, ec_id):
383
    """Reserve a given IPv4 address for use by an instance.
384

385
    """
386
    net_uuid = self._UnlockedLookupNetwork(net)
387
    if net_uuid:
388
      return self._UnlockedReserveIp(net_uuid, address, ec_id)
389

    
390
  @locking.ssynchronized(_config_lock, shared=1)
391
  def ReserveLV(self, lv_name, ec_id):
392
    """Reserve an VG/LV pair for an instance.
393

394
    @type lv_name: string
395
    @param lv_name: the logical volume name to reserve
396

397
    """
398
    all_lvs = self._AllLVs()
399
    if lv_name in all_lvs:
400
      raise errors.ReservationError("LV already in use")
401
    else:
402
      self._temporary_lvs.Reserve(ec_id, lv_name)
403

    
404
  @locking.ssynchronized(_config_lock, shared=1)
405
  def GenerateDRBDSecret(self, ec_id):
406
    """Generate a DRBD secret.
407

408
    This checks the current disks for duplicates.
409

410
    """
411
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
412
                                            utils.GenerateSecret,
413
                                            ec_id)
414

    
415
  def _AllLVs(self):
416
    """Compute the list of all LVs.
417

418
    """
419
    lvnames = set()
420
    for instance in self._config_data.instances.values():
421
      node_data = instance.MapLVsByNode()
422
      for lv_list in node_data.values():
423
        lvnames.update(lv_list)
424
    return lvnames
425

    
426
  def _AllIDs(self, include_temporary):
427
    """Compute the list of all UUIDs and names we have.
428

429
    @type include_temporary: boolean
430
    @param include_temporary: whether to include the _temporary_ids set
431
    @rtype: set
432
    @return: a set of IDs
433

434
    """
435
    existing = set()
436
    if include_temporary:
437
      existing.update(self._temporary_ids.GetReserved())
438
    existing.update(self._AllLVs())
439
    existing.update(self._config_data.instances.keys())
440
    existing.update(self._config_data.nodes.keys())
441
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
442
    return existing
443

    
444
  def _GenerateUniqueID(self, ec_id):
445
    """Generate an unique UUID.
446

447
    This checks the current node, instances and disk names for
448
    duplicates.
449

450
    @rtype: string
451
    @return: the unique id
452

453
    """
454
    existing = self._AllIDs(include_temporary=False)
455
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
456

    
457
  @locking.ssynchronized(_config_lock, shared=1)
458
  def GenerateUniqueID(self, ec_id):
459
    """Generate an unique ID.
460

461
    This is just a wrapper over the unlocked version.
462

463
    @type ec_id: string
464
    @param ec_id: unique id for the job to reserve the id to
465

466
    """
467
    return self._GenerateUniqueID(ec_id)
468

    
469
  def _AllMACs(self):
470
    """Return all MACs present in the config.
471

472
    @rtype: list
473
    @return: the list of all MACs
474

475
    """
476
    result = []
477
    for instance in self._config_data.instances.values():
478
      for nic in instance.nics:
479
        result.append(nic.mac)
480

    
481
    return result
482

    
483
  def _AllDRBDSecrets(self):
484
    """Return all DRBD secrets present in the config.
485

486
    @rtype: list
487
    @return: the list of all DRBD secrets
488

489
    """
490
    def helper(disk, result):
491
      """Recursively gather secrets from this disk."""
492
      if disk.dev_type == constants.DT_DRBD8:
493
        result.append(disk.logical_id[5])
494
      if disk.children:
495
        for child in disk.children:
496
          helper(child, result)
497

    
498
    result = []
499
    for instance in self._config_data.instances.values():
500
      for disk in instance.disks:
501
        helper(disk, result)
502

    
503
    return result
504

    
505
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
506
    """Compute duplicate disk IDs
507

508
    @type disk: L{objects.Disk}
509
    @param disk: the disk at which to start searching
510
    @type l_ids: list
511
    @param l_ids: list of current logical ids
512
    @type p_ids: list
513
    @param p_ids: list of current physical ids
514
    @rtype: list
515
    @return: a list of error messages
516

517
    """
518
    result = []
519
    if disk.logical_id is not None:
520
      if disk.logical_id in l_ids:
521
        result.append("duplicate logical id %s" % str(disk.logical_id))
522
      else:
523
        l_ids.append(disk.logical_id)
524
    if disk.physical_id is not None:
525
      if disk.physical_id in p_ids:
526
        result.append("duplicate physical id %s" % str(disk.physical_id))
527
      else:
528
        p_ids.append(disk.physical_id)
529

    
530
    if disk.children:
531
      for child in disk.children:
532
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
533
    return result
534

    
535
  def _UnlockedVerifyConfig(self):
536
    """Verify function.
537

538
    @rtype: list
539
    @return: a list of error messages; a non-empty list signifies
540
        configuration errors
541

542
    """
543
    # pylint: disable=R0914
544
    result = []
545
    seen_macs = []
546
    ports = {}
547
    data = self._config_data
548
    cluster = data.cluster
549
    seen_lids = []
550
    seen_pids = []
551

    
552
    # global cluster checks
553
    if not cluster.enabled_hypervisors:
554
      result.append("enabled hypervisors list doesn't have any entries")
555
    invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
556
    if invalid_hvs:
557
      result.append("enabled hypervisors contains invalid entries: %s" %
558
                    invalid_hvs)
559
    missing_hvp = (set(cluster.enabled_hypervisors) -
560
                   set(cluster.hvparams.keys()))
561
    if missing_hvp:
562
      result.append("hypervisor parameters missing for the enabled"
563
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
564

    
565
    if cluster.master_node not in data.nodes:
566
      result.append("cluster has invalid primary node '%s'" %
567
                    cluster.master_node)
568

    
569
    def _helper(owner, attr, value, template):
570
      try:
571
        utils.ForceDictType(value, template)
572
      except errors.GenericError, err:
573
        result.append("%s has invalid %s: %s" % (owner, attr, err))
574

    
575
    def _helper_nic(owner, params):
576
      try:
577
        objects.NIC.CheckParameterSyntax(params)
578
      except errors.ConfigurationError, err:
579
        result.append("%s has invalid nicparams: %s" % (owner, err))
580

    
581
    def _helper_ipolicy(owner, params, check_std):
582
      try:
583
        objects.InstancePolicy.CheckParameterSyntax(params, check_std)
584
      except errors.ConfigurationError, err:
585
        result.append("%s has invalid instance policy: %s" % (owner, err))
586

    
587
    def _helper_ispecs(owner, params):
588
      for key, value in params.items():
589
        if key in constants.IPOLICY_ISPECS:
590
          fullkey = "ipolicy/" + key
591
          _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
592
        else:
593
          # FIXME: assuming list type
594
          if key in constants.IPOLICY_PARAMETERS:
595
            exp_type = float
596
          else:
597
            exp_type = list
598
          if not isinstance(value, exp_type):
599
            result.append("%s has invalid instance policy: for %s,"
600
                          " expecting %s, got %s" %
601
                          (owner, key, exp_type.__name__, type(value)))
602

    
603
    # check cluster parameters
604
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
605
            constants.BES_PARAMETER_TYPES)
606
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
607
            constants.NICS_PARAMETER_TYPES)
608
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
609
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
610
            constants.NDS_PARAMETER_TYPES)
611
    _helper_ipolicy("cluster", cluster.SimpleFillIPolicy({}), True)
612
    _helper_ispecs("cluster", cluster.SimpleFillIPolicy({}))
613

    
614
    # per-instance checks
615
    for instance_name in data.instances:
616
      instance = data.instances[instance_name]
617
      if instance.name != instance_name:
618
        result.append("instance '%s' is indexed by wrong name '%s'" %
619
                      (instance.name, instance_name))
620
      if instance.primary_node not in data.nodes:
621
        result.append("instance '%s' has invalid primary node '%s'" %
622
                      (instance_name, instance.primary_node))
623
      for snode in instance.secondary_nodes:
624
        if snode not in data.nodes:
625
          result.append("instance '%s' has invalid secondary node '%s'" %
626
                        (instance_name, snode))
627
      for idx, nic in enumerate(instance.nics):
628
        if nic.mac in seen_macs:
629
          result.append("instance '%s' has NIC %d mac %s duplicate" %
630
                        (instance_name, idx, nic.mac))
631
        else:
632
          seen_macs.append(nic.mac)
633
        if nic.nicparams:
634
          filled = cluster.SimpleFillNIC(nic.nicparams)
635
          owner = "instance %s nic %d" % (instance.name, idx)
636
          _helper(owner, "nicparams",
637
                  filled, constants.NICS_PARAMETER_TYPES)
638
          _helper_nic(owner, filled)
639

    
640
      # parameter checks
641
      if instance.beparams:
642
        _helper("instance %s" % instance.name, "beparams",
643
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
644

    
645
      # gather the drbd ports for duplicate checks
646
      for (idx, dsk) in enumerate(instance.disks):
647
        if dsk.dev_type in constants.LDS_DRBD:
648
          tcp_port = dsk.logical_id[2]
649
          if tcp_port not in ports:
650
            ports[tcp_port] = []
651
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
652
      # gather network port reservation
653
      net_port = getattr(instance, "network_port", None)
654
      if net_port is not None:
655
        if net_port not in ports:
656
          ports[net_port] = []
657
        ports[net_port].append((instance.name, "network port"))
658

    
659
      # instance disk verify
660
      for idx, disk in enumerate(instance.disks):
661
        result.extend(["instance '%s' disk %d error: %s" %
662
                       (instance.name, idx, msg) for msg in disk.Verify()])
663
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
664

    
665
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
666
      if wrong_names:
667
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
668
                         (idx, exp_name, actual_name))
669
                        for (idx, exp_name, actual_name) in wrong_names)
670

    
671
        result.append("Instance '%s' has wrongly named disks: %s" %
672
                      (instance.name, tmp))
673

    
674
    # cluster-wide pool of free ports
675
    for free_port in cluster.tcpudp_port_pool:
676
      if free_port not in ports:
677
        ports[free_port] = []
678
      ports[free_port].append(("cluster", "port marked as free"))
679

    
680
    # compute tcp/udp duplicate ports
681
    keys = ports.keys()
682
    keys.sort()
683
    for pnum in keys:
684
      pdata = ports[pnum]
685
      if len(pdata) > 1:
686
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
687
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
688

    
689
    # highest used tcp port check
690
    if keys:
691
      if keys[-1] > cluster.highest_used_port:
692
        result.append("Highest used port mismatch, saved %s, computed %s" %
693
                      (cluster.highest_used_port, keys[-1]))
694

    
695
    if not data.nodes[cluster.master_node].master_candidate:
696
      result.append("Master node is not a master candidate")
697

    
698
    # master candidate checks
699
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
700
    if mc_now < mc_max:
701
      result.append("Not enough master candidates: actual %d, target %d" %
702
                    (mc_now, mc_max))
703

    
704
    # node checks
705
    for node_name, node in data.nodes.items():
706
      if node.name != node_name:
707
        result.append("Node '%s' is indexed by wrong name '%s'" %
708
                      (node.name, node_name))
709
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
710
        result.append("Node %s state is invalid: master_candidate=%s,"
711
                      " drain=%s, offline=%s" %
712
                      (node.name, node.master_candidate, node.drained,
713
                       node.offline))
714
      if node.group not in data.nodegroups:
715
        result.append("Node '%s' has invalid group '%s'" %
716
                      (node.name, node.group))
717
      else:
718
        _helper("node %s" % node.name, "ndparams",
719
                cluster.FillND(node, data.nodegroups[node.group]),
720
                constants.NDS_PARAMETER_TYPES)
721

    
722
    # nodegroups checks
723
    nodegroups_names = set()
724
    for nodegroup_uuid in data.nodegroups:
725
      nodegroup = data.nodegroups[nodegroup_uuid]
726
      if nodegroup.uuid != nodegroup_uuid:
727
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
728
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
729
      if utils.UUID_RE.match(nodegroup.name.lower()):
730
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
731
                      (nodegroup.name, nodegroup.uuid))
732
      if nodegroup.name in nodegroups_names:
733
        result.append("duplicate node group name '%s'" % nodegroup.name)
734
      else:
735
        nodegroups_names.add(nodegroup.name)
736
      group_name = "group %s" % nodegroup.name
737
      _helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy),
738
                      False)
739
      _helper_ispecs(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy))
740
      if nodegroup.ndparams:
741
        _helper(group_name, "ndparams",
742
                cluster.SimpleFillND(nodegroup.ndparams),
743
                constants.NDS_PARAMETER_TYPES)
744

    
745
    # drbd minors check
746
    _, duplicates = self._UnlockedComputeDRBDMap()
747
    for node, minor, instance_a, instance_b in duplicates:
748
      result.append("DRBD minor %d on node %s is assigned twice to instances"
749
                    " %s and %s" % (minor, node, instance_a, instance_b))
750

    
751
    # IP checks
752
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
753
    ips = {}
754

    
755
    def _AddIpAddress(ip, name):
756
      ips.setdefault(ip, []).append(name)
757

    
758
    _AddIpAddress(cluster.master_ip, "cluster_ip")
759

    
760
    for node in data.nodes.values():
761
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
762
      if node.secondary_ip != node.primary_ip:
763
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
764

    
765
    for instance in data.instances.values():
766
      for idx, nic in enumerate(instance.nics):
767
        if nic.ip is None:
768
          continue
769

    
770
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
771
        nic_mode = nicparams[constants.NIC_MODE]
772
        nic_link = nicparams[constants.NIC_LINK]
773

    
774
        if nic_mode == constants.NIC_MODE_BRIDGED:
775
          link = "bridge:%s" % nic_link
776
        elif nic_mode == constants.NIC_MODE_ROUTED:
777
          link = "route:%s" % nic_link
778
        else:
779
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
780

    
781
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
782
                      "instance:%s/nic:%d" % (instance.name, idx))
783

    
784
    for ip, owners in ips.items():
785
      if len(owners) > 1:
786
        result.append("IP address %s is used by multiple owners: %s" %
787
                      (ip, utils.CommaJoin(owners)))
788

    
789
    return result
790

    
791
  @locking.ssynchronized(_config_lock, shared=1)
792
  def VerifyConfig(self):
793
    """Verify function.
794

795
    This is just a wrapper over L{_UnlockedVerifyConfig}.
796

797
    @rtype: list
798
    @return: a list of error messages; a non-empty list signifies
799
        configuration errors
800

801
    """
802
    return self._UnlockedVerifyConfig()
803

    
804
  def _UnlockedSetDiskID(self, disk, node_name):
805
    """Convert the unique ID to the ID needed on the target nodes.
806

807
    This is used only for drbd, which needs ip/port configuration.
808

809
    The routine descends down and updates its children also, because
810
    this helps when the only the top device is passed to the remote
811
    node.
812

813
    This function is for internal use, when the config lock is already held.
814

815
    """
816
    if disk.children:
817
      for child in disk.children:
818
        self._UnlockedSetDiskID(child, node_name)
819

    
820
    if disk.logical_id is None and disk.physical_id is not None:
821
      return
822
    if disk.dev_type == constants.LD_DRBD8:
823
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
824
      if node_name not in (pnode, snode):
825
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
826
                                        node_name)
827
      pnode_info = self._UnlockedGetNodeInfo(pnode)
828
      snode_info = self._UnlockedGetNodeInfo(snode)
829
      if pnode_info is None or snode_info is None:
830
        raise errors.ConfigurationError("Can't find primary or secondary node"
831
                                        " for %s" % str(disk))
832
      p_data = (pnode_info.secondary_ip, port)
833
      s_data = (snode_info.secondary_ip, port)
834
      if pnode == node_name:
835
        disk.physical_id = p_data + s_data + (pminor, secret)
836
      else: # it must be secondary, we tested above
837
        disk.physical_id = s_data + p_data + (sminor, secret)
838
    else:
839
      disk.physical_id = disk.logical_id
840
    return
841

    
842
  @locking.ssynchronized(_config_lock)
843
  def SetDiskID(self, disk, node_name):
844
    """Convert the unique ID to the ID needed on the target nodes.
845

846
    This is used only for drbd, which needs ip/port configuration.
847

848
    The routine descends down and updates its children also, because
849
    this helps when the only the top device is passed to the remote
850
    node.
851

852
    """
853
    return self._UnlockedSetDiskID(disk, node_name)
854

    
855
  @locking.ssynchronized(_config_lock)
856
  def AddTcpUdpPort(self, port):
857
    """Adds a new port to the available port pool.
858

859
    @warning: this method does not "flush" the configuration (via
860
        L{_WriteConfig}); callers should do that themselves once the
861
        configuration is stable
862

863
    """
864
    if not isinstance(port, int):
865
      raise errors.ProgrammerError("Invalid type passed for port")
866

    
867
    self._config_data.cluster.tcpudp_port_pool.add(port)
868

    
869
  @locking.ssynchronized(_config_lock, shared=1)
870
  def GetPortList(self):
871
    """Returns a copy of the current port list.
872

873
    """
874
    return self._config_data.cluster.tcpudp_port_pool.copy()
875

    
876
  @locking.ssynchronized(_config_lock)
877
  def AllocatePort(self):
878
    """Allocate a port.
879

880
    The port will be taken from the available port pool or from the
881
    default port range (and in this case we increase
882
    highest_used_port).
883

884
    """
885
    # If there are TCP/IP ports configured, we use them first.
886
    if self._config_data.cluster.tcpudp_port_pool:
887
      port = self._config_data.cluster.tcpudp_port_pool.pop()
888
    else:
889
      port = self._config_data.cluster.highest_used_port + 1
890
      if port >= constants.LAST_DRBD_PORT:
891
        raise errors.ConfigurationError("The highest used port is greater"
892
                                        " than %s. Aborting." %
893
                                        constants.LAST_DRBD_PORT)
894
      self._config_data.cluster.highest_used_port = port
895

    
896
    self._WriteConfig()
897
    return port
898

    
899
  def _UnlockedComputeDRBDMap(self):
900
    """Compute the used DRBD minor/nodes.
901

902
    @rtype: (dict, list)
903
    @return: dictionary of node_name: dict of minor: instance_name;
904
        the returned dict will have all the nodes in it (even if with
905
        an empty list), and a list of duplicates; if the duplicates
906
        list is not empty, the configuration is corrupted and its caller
907
        should raise an exception
908

909
    """
910
    def _AppendUsedPorts(instance_name, disk, used):
911
      duplicates = []
912
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
913
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
914
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
915
          assert node in used, ("Node '%s' of instance '%s' not found"
916
                                " in node list" % (node, instance_name))
917
          if port in used[node]:
918
            duplicates.append((node, port, instance_name, used[node][port]))
919
          else:
920
            used[node][port] = instance_name
921
      if disk.children:
922
        for child in disk.children:
923
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
924
      return duplicates
925

    
926
    duplicates = []
927
    my_dict = dict((node, {}) for node in self._config_data.nodes)
928
    for instance in self._config_data.instances.itervalues():
929
      for disk in instance.disks:
930
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
931
    for (node, minor), instance in self._temporary_drbds.iteritems():
932
      if minor in my_dict[node] and my_dict[node][minor] != instance:
933
        duplicates.append((node, minor, instance, my_dict[node][minor]))
934
      else:
935
        my_dict[node][minor] = instance
936
    return my_dict, duplicates
937

    
938
  @locking.ssynchronized(_config_lock)
939
  def ComputeDRBDMap(self):
940
    """Compute the used DRBD minor/nodes.
941

942
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
943

944
    @return: dictionary of node_name: dict of minor: instance_name;
945
        the returned dict will have all the nodes in it (even if with
946
        an empty list).
947

948
    """
949
    d_map, duplicates = self._UnlockedComputeDRBDMap()
950
    if duplicates:
951
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
952
                                      str(duplicates))
953
    return d_map
954

    
955
  @locking.ssynchronized(_config_lock)
956
  def AllocateDRBDMinor(self, nodes, instance):
957
    """Allocate a drbd minor.
958

959
    The free minor will be automatically computed from the existing
960
    devices. A node can be given multiple times in order to allocate
961
    multiple minors. The result is the list of minors, in the same
962
    order as the passed nodes.
963

964
    @type instance: string
965
    @param instance: the instance for which we allocate minors
966

967
    """
968
    assert isinstance(instance, basestring), \
969
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
970

    
971
    d_map, duplicates = self._UnlockedComputeDRBDMap()
972
    if duplicates:
973
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
974
                                      str(duplicates))
975
    result = []
976
    for nname in nodes:
977
      ndata = d_map[nname]
978
      if not ndata:
979
        # no minors used, we can start at 0
980
        result.append(0)
981
        ndata[0] = instance
982
        self._temporary_drbds[(nname, 0)] = instance
983
        continue
984
      keys = ndata.keys()
985
      keys.sort()
986
      ffree = utils.FirstFree(keys)
987
      if ffree is None:
988
        # return the next minor
989
        # TODO: implement high-limit check
990
        minor = keys[-1] + 1
991
      else:
992
        minor = ffree
993
      # double-check minor against current instances
994
      assert minor not in d_map[nname], \
995
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
996
              " already allocated to instance %s" %
997
              (minor, nname, d_map[nname][minor]))
998
      ndata[minor] = instance
999
      # double-check minor against reservation
1000
      r_key = (nname, minor)
1001
      assert r_key not in self._temporary_drbds, \
1002
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
1003
              " reserved for instance %s" %
1004
              (minor, nname, self._temporary_drbds[r_key]))
1005
      self._temporary_drbds[r_key] = instance
1006
      result.append(minor)
1007
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
1008
                  nodes, result)
1009
    return result
1010

    
1011
  def _UnlockedReleaseDRBDMinors(self, instance):
1012
    """Release temporary drbd minors allocated for a given instance.
1013

1014
    @type instance: string
1015
    @param instance: the instance for which temporary minors should be
1016
                     released
1017

1018
    """
1019
    assert isinstance(instance, basestring), \
1020
           "Invalid argument passed to ReleaseDRBDMinors"
1021
    for key, name in self._temporary_drbds.items():
1022
      if name == instance:
1023
        del self._temporary_drbds[key]
1024

    
1025
  @locking.ssynchronized(_config_lock)
1026
  def ReleaseDRBDMinors(self, instance):
1027
    """Release temporary drbd minors allocated for a given instance.
1028

1029
    This should be called on the error paths, on the success paths
1030
    it's automatically called by the ConfigWriter add and update
1031
    functions.
1032

1033
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1034

1035
    @type instance: string
1036
    @param instance: the instance for which temporary minors should be
1037
                     released
1038

1039
    """
1040
    self._UnlockedReleaseDRBDMinors(instance)
1041

    
1042
  @locking.ssynchronized(_config_lock, shared=1)
1043
  def GetConfigVersion(self):
1044
    """Get the configuration version.
1045

1046
    @return: Config version
1047

1048
    """
1049
    return self._config_data.version
1050

    
1051
  @locking.ssynchronized(_config_lock, shared=1)
1052
  def GetClusterName(self):
1053
    """Get cluster name.
1054

1055
    @return: Cluster name
1056

1057
    """
1058
    return self._config_data.cluster.cluster_name
1059

    
1060
  @locking.ssynchronized(_config_lock, shared=1)
1061
  def GetMasterNode(self):
1062
    """Get the hostname of the master node for this cluster.
1063

1064
    @return: Master hostname
1065

1066
    """
1067
    return self._config_data.cluster.master_node
1068

    
1069
  @locking.ssynchronized(_config_lock, shared=1)
1070
  def GetMasterIP(self):
1071
    """Get the IP of the master node for this cluster.
1072

1073
    @return: Master IP
1074

1075
    """
1076
    return self._config_data.cluster.master_ip
1077

    
1078
  @locking.ssynchronized(_config_lock, shared=1)
1079
  def GetMasterNetdev(self):
1080
    """Get the master network device for this cluster.
1081

1082
    """
1083
    return self._config_data.cluster.master_netdev
1084

    
1085
  @locking.ssynchronized(_config_lock, shared=1)
1086
  def GetMasterNetmask(self):
1087
    """Get the netmask of the master node for this cluster.
1088

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

    
1092
  @locking.ssynchronized(_config_lock, shared=1)
1093
  def GetUseExternalMipScript(self):
1094
    """Get flag representing whether to use the external master IP setup script.
1095

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

    
1099
  @locking.ssynchronized(_config_lock, shared=1)
1100
  def GetFileStorageDir(self):
1101
    """Get the file storage dir for this cluster.
1102

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

    
1106
  @locking.ssynchronized(_config_lock, shared=1)
1107
  def GetSharedFileStorageDir(self):
1108
    """Get the shared file storage dir for this cluster.
1109

1110
    """
1111
    return self._config_data.cluster.shared_file_storage_dir
1112

    
1113
  @locking.ssynchronized(_config_lock, shared=1)
1114
  def GetHypervisorType(self):
1115
    """Get the hypervisor type for this cluster.
1116

1117
    """
1118
    return self._config_data.cluster.enabled_hypervisors[0]
1119

    
1120
  @locking.ssynchronized(_config_lock, shared=1)
1121
  def GetHostKey(self):
1122
    """Return the rsa hostkey from the config.
1123

1124
    @rtype: string
1125
    @return: the rsa hostkey
1126

1127
    """
1128
    return self._config_data.cluster.rsahostkeypub
1129

    
1130
  @locking.ssynchronized(_config_lock, shared=1)
1131
  def GetDefaultIAllocator(self):
1132
    """Get the default instance allocator for this cluster.
1133

1134
    """
1135
    return self._config_data.cluster.default_iallocator
1136

    
1137
  @locking.ssynchronized(_config_lock, shared=1)
1138
  def GetPrimaryIPFamily(self):
1139
    """Get cluster primary ip family.
1140

1141
    @return: primary ip family
1142

1143
    """
1144
    return self._config_data.cluster.primary_ip_family
1145

    
1146
  @locking.ssynchronized(_config_lock, shared=1)
1147
  def GetMasterNetworkParameters(self):
1148
    """Get network parameters of the master node.
1149

1150
    @rtype: L{object.MasterNetworkParameters}
1151
    @return: network parameters of the master node
1152

1153
    """
1154
    cluster = self._config_data.cluster
1155
    result = objects.MasterNetworkParameters(
1156
      name=cluster.master_node, ip=cluster.master_ip,
1157
      netmask=cluster.master_netmask, netdev=cluster.master_netdev,
1158
      ip_family=cluster.primary_ip_family)
1159

    
1160
    return result
1161

    
1162
  @locking.ssynchronized(_config_lock)
1163
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1164
    """Add a node group to the configuration.
1165

1166
    This method calls group.UpgradeConfig() to fill any missing attributes
1167
    according to their default values.
1168

1169
    @type group: L{objects.NodeGroup}
1170
    @param group: the NodeGroup object to add
1171
    @type ec_id: string
1172
    @param ec_id: unique id for the job to use when creating a missing UUID
1173
    @type check_uuid: bool
1174
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1175
                       it does, ensure that it does not exist in the
1176
                       configuration already
1177

1178
    """
1179
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1180
    self._WriteConfig()
1181

    
1182
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1183
    """Add a node group to the configuration.
1184

1185
    """
1186
    logging.info("Adding node group %s to configuration", group.name)
1187

    
1188
    # Some code might need to add a node group with a pre-populated UUID
1189
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1190
    # the "does this UUID" exist already check.
1191
    if check_uuid:
1192
      self._EnsureUUID(group, ec_id)
1193

    
1194
    try:
1195
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1196
    except errors.OpPrereqError:
1197
      pass
1198
    else:
1199
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1200
                                 " node group (UUID: %s)" %
1201
                                 (group.name, existing_uuid),
1202
                                 errors.ECODE_EXISTS)
1203

    
1204
    group.serial_no = 1
1205
    group.ctime = group.mtime = time.time()
1206
    group.UpgradeConfig()
1207

    
1208
    self._config_data.nodegroups[group.uuid] = group
1209
    self._config_data.cluster.serial_no += 1
1210

    
1211
  @locking.ssynchronized(_config_lock)
1212
  def RemoveNodeGroup(self, group_uuid):
1213
    """Remove a node group from the configuration.
1214

1215
    @type group_uuid: string
1216
    @param group_uuid: the UUID of the node group to remove
1217

1218
    """
1219
    logging.info("Removing node group %s from configuration", group_uuid)
1220

    
1221
    if group_uuid not in self._config_data.nodegroups:
1222
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1223

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

    
1227
    del self._config_data.nodegroups[group_uuid]
1228
    self._config_data.cluster.serial_no += 1
1229
    self._WriteConfig()
1230

    
1231
  def _UnlockedLookupNodeGroup(self, target):
1232
    """Lookup a node group's UUID.
1233

1234
    @type target: string or None
1235
    @param target: group name or UUID or None to look for the default
1236
    @rtype: string
1237
    @return: nodegroup UUID
1238
    @raises errors.OpPrereqError: when the target group cannot be found
1239

1240
    """
1241
    if target is None:
1242
      if len(self._config_data.nodegroups) != 1:
1243
        raise errors.OpPrereqError("More than one node group exists. Target"
1244
                                   " group must be specified explicitly.")
1245
      else:
1246
        return self._config_data.nodegroups.keys()[0]
1247
    if target in self._config_data.nodegroups:
1248
      return target
1249
    for nodegroup in self._config_data.nodegroups.values():
1250
      if nodegroup.name == target:
1251
        return nodegroup.uuid
1252
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1253
                               errors.ECODE_NOENT)
1254

    
1255
  @locking.ssynchronized(_config_lock, shared=1)
1256
  def LookupNodeGroup(self, target):
1257
    """Lookup a node group's UUID.
1258

1259
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1260

1261
    @type target: string or None
1262
    @param target: group name or UUID or None to look for the default
1263
    @rtype: string
1264
    @return: nodegroup UUID
1265

1266
    """
1267
    return self._UnlockedLookupNodeGroup(target)
1268

    
1269
  def _UnlockedGetNodeGroup(self, uuid):
1270
    """Lookup a node group.
1271

1272
    @type uuid: string
1273
    @param uuid: group UUID
1274
    @rtype: L{objects.NodeGroup} or None
1275
    @return: nodegroup object, or None if not found
1276

1277
    """
1278
    if uuid not in self._config_data.nodegroups:
1279
      return None
1280

    
1281
    return self._config_data.nodegroups[uuid]
1282

    
1283
  @locking.ssynchronized(_config_lock, shared=1)
1284
  def GetNodeGroup(self, uuid):
1285
    """Lookup a node group.
1286

1287
    @type uuid: string
1288
    @param uuid: group UUID
1289
    @rtype: L{objects.NodeGroup} or None
1290
    @return: nodegroup object, or None if not found
1291

1292
    """
1293
    return self._UnlockedGetNodeGroup(uuid)
1294

    
1295
  @locking.ssynchronized(_config_lock, shared=1)
1296
  def GetAllNodeGroupsInfo(self):
1297
    """Get the configuration of all node groups.
1298

1299
    """
1300
    return dict(self._config_data.nodegroups)
1301

    
1302
  @locking.ssynchronized(_config_lock, shared=1)
1303
  def GetNodeGroupList(self):
1304
    """Get a list of node groups.
1305

1306
    """
1307
    return self._config_data.nodegroups.keys()
1308

    
1309
  @locking.ssynchronized(_config_lock, shared=1)
1310
  def GetNodeGroupMembersByNodes(self, nodes):
1311
    """Get nodes which are member in the same nodegroups as the given nodes.
1312

1313
    """
1314
    ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1315
    return frozenset(member_name
1316
                     for node_name in nodes
1317
                     for member_name in
1318
                       self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1319

    
1320
  @locking.ssynchronized(_config_lock, shared=1)
1321
  def GetMultiNodeGroupInfo(self, group_uuids):
1322
    """Get the configuration of multiple node groups.
1323

1324
    @param group_uuids: List of node group UUIDs
1325
    @rtype: list
1326
    @return: List of tuples of (group_uuid, group_info)
1327

1328
    """
1329
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1330

    
1331
  @locking.ssynchronized(_config_lock)
1332
  def AddInstance(self, instance, ec_id):
1333
    """Add an instance to the config.
1334

1335
    This should be used after creating a new instance.
1336

1337
    @type instance: L{objects.Instance}
1338
    @param instance: the instance object
1339

1340
    """
1341
    if not isinstance(instance, objects.Instance):
1342
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1343

    
1344
    if instance.disk_template != constants.DT_DISKLESS:
1345
      all_lvs = instance.MapLVsByNode()
1346
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1347

    
1348
    all_macs = self._AllMACs()
1349
    for nic in instance.nics:
1350
      if nic.mac in all_macs:
1351
        raise errors.ConfigurationError("Cannot add instance %s:"
1352
                                        " MAC address '%s' already in use." %
1353
                                        (instance.name, nic.mac))
1354

    
1355
    self._EnsureUUID(instance, ec_id)
1356

    
1357
    instance.serial_no = 1
1358
    instance.ctime = instance.mtime = time.time()
1359
    self._config_data.instances[instance.name] = instance
1360
    self._config_data.cluster.serial_no += 1
1361
    self._UnlockedReleaseDRBDMinors(instance.name)
1362
    self._UnlockedCommitTemporaryIps(ec_id)
1363
    self._WriteConfig()
1364

    
1365
  def _EnsureUUID(self, item, ec_id):
1366
    """Ensures a given object has a valid UUID.
1367

1368
    @param item: the instance or node to be checked
1369
    @param ec_id: the execution context id for the uuid reservation
1370

1371
    """
1372
    if not item.uuid:
1373
      item.uuid = self._GenerateUniqueID(ec_id)
1374
    elif item.uuid in self._AllIDs(include_temporary=True):
1375
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1376
                                      " in use" % (item.name, item.uuid))
1377

    
1378
  def _SetInstanceStatus(self, instance_name, status):
1379
    """Set the instance's status to a given value.
1380

1381
    """
1382
    assert status in constants.ADMINST_ALL, \
1383
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1384

    
1385
    if instance_name not in self._config_data.instances:
1386
      raise errors.ConfigurationError("Unknown instance '%s'" %
1387
                                      instance_name)
1388
    instance = self._config_data.instances[instance_name]
1389
    if instance.admin_state != status:
1390
      instance.admin_state = status
1391
      instance.serial_no += 1
1392
      instance.mtime = time.time()
1393
      self._WriteConfig()
1394

    
1395
  @locking.ssynchronized(_config_lock)
1396
  def MarkInstanceUp(self, instance_name):
1397
    """Mark the instance status to up in the config.
1398

1399
    """
1400
    self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1401

    
1402
  @locking.ssynchronized(_config_lock)
1403
  def MarkInstanceOffline(self, instance_name):
1404
    """Mark the instance status to down in the config.
1405

1406
    """
1407
    self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1408

    
1409
  @locking.ssynchronized(_config_lock)
1410
  def RemoveInstance(self, instance_name):
1411
    """Remove the instance from the configuration.
1412

1413
    """
1414
    if instance_name not in self._config_data.instances:
1415
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1416

    
1417
    # If a network port has been allocated to the instance,
1418
    # return it to the pool of free ports.
1419
    inst = self._config_data.instances[instance_name]
1420
    network_port = getattr(inst, "network_port", None)
1421
    if network_port is not None:
1422
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1423

    
1424
    del self._config_data.instances[instance_name]
1425
    self._config_data.cluster.serial_no += 1
1426
    self._WriteConfig()
1427

    
1428
  @locking.ssynchronized(_config_lock)
1429
  def RenameInstance(self, old_name, new_name):
1430
    """Rename an instance.
1431

1432
    This needs to be done in ConfigWriter and not by RemoveInstance
1433
    combined with AddInstance as only we can guarantee an atomic
1434
    rename.
1435

1436
    """
1437
    if old_name not in self._config_data.instances:
1438
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1439

    
1440
    # Operate on a copy to not loose instance object in case of a failure
1441
    inst = self._config_data.instances[old_name].Copy()
1442
    inst.name = new_name
1443

    
1444
    for (idx, disk) in enumerate(inst.disks):
1445
      if disk.dev_type == constants.LD_FILE:
1446
        # rename the file paths in logical and physical id
1447
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1448
        disk.logical_id = (disk.logical_id[0],
1449
                           utils.PathJoin(file_storage_dir, inst.name,
1450
                                          "disk%s" % idx))
1451
        disk.physical_id = disk.logical_id
1452

    
1453
    # Actually replace instance object
1454
    del self._config_data.instances[old_name]
1455
    self._config_data.instances[inst.name] = inst
1456

    
1457
    # Force update of ssconf files
1458
    self._config_data.cluster.serial_no += 1
1459

    
1460
    self._WriteConfig()
1461

    
1462
  @locking.ssynchronized(_config_lock)
1463
  def MarkInstanceDown(self, instance_name):
1464
    """Mark the status of an instance to down in the configuration.
1465

1466
    """
1467
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1468

    
1469
  def _UnlockedGetInstanceList(self):
1470
    """Get the list of instances.
1471

1472
    This function is for internal use, when the config lock is already held.
1473

1474
    """
1475
    return self._config_data.instances.keys()
1476

    
1477
  @locking.ssynchronized(_config_lock, shared=1)
1478
  def GetInstanceList(self):
1479
    """Get the list of instances.
1480

1481
    @return: array of instances, ex. ['instance2.example.com',
1482
        'instance1.example.com']
1483

1484
    """
1485
    return self._UnlockedGetInstanceList()
1486

    
1487
  def ExpandInstanceName(self, short_name):
1488
    """Attempt to expand an incomplete instance name.
1489

1490
    """
1491
    # Locking is done in L{ConfigWriter.GetInstanceList}
1492
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1493

    
1494
  def _UnlockedGetInstanceInfo(self, instance_name):
1495
    """Returns information about an instance.
1496

1497
    This function is for internal use, when the config lock is already held.
1498

1499
    """
1500
    if instance_name not in self._config_data.instances:
1501
      return None
1502

    
1503
    return self._config_data.instances[instance_name]
1504

    
1505
  @locking.ssynchronized(_config_lock, shared=1)
1506
  def GetInstanceInfo(self, instance_name):
1507
    """Returns information about an instance.
1508

1509
    It takes the information from the configuration file. Other information of
1510
    an instance are taken from the live systems.
1511

1512
    @param instance_name: name of the instance, e.g.
1513
        I{instance1.example.com}
1514

1515
    @rtype: L{objects.Instance}
1516
    @return: the instance object
1517

1518
    """
1519
    return self._UnlockedGetInstanceInfo(instance_name)
1520

    
1521
  @locking.ssynchronized(_config_lock, shared=1)
1522
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1523
    """Returns set of node group UUIDs for instance's nodes.
1524

1525
    @rtype: frozenset
1526

1527
    """
1528
    instance = self._UnlockedGetInstanceInfo(instance_name)
1529
    if not instance:
1530
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1531

    
1532
    if primary_only:
1533
      nodes = [instance.primary_node]
1534
    else:
1535
      nodes = instance.all_nodes
1536

    
1537
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1538
                     for node_name in nodes)
1539

    
1540
  @locking.ssynchronized(_config_lock, shared=1)
1541
  def GetMultiInstanceInfo(self, instances):
1542
    """Get the configuration of multiple instances.
1543

1544
    @param instances: list of instance names
1545
    @rtype: list
1546
    @return: list of tuples (instance, instance_info), where
1547
        instance_info is what would GetInstanceInfo return for the
1548
        node, while keeping the original order
1549

1550
    """
1551
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1552

    
1553
  @locking.ssynchronized(_config_lock, shared=1)
1554
  def GetAllInstancesInfo(self):
1555
    """Get the configuration of all instances.
1556

1557
    @rtype: dict
1558
    @return: dict of (instance, instance_info), where instance_info is what
1559
              would GetInstanceInfo return for the node
1560

1561
    """
1562
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1563
                    for instance in self._UnlockedGetInstanceList()])
1564
    return my_dict
1565

    
1566
  @locking.ssynchronized(_config_lock, shared=1)
1567
  def GetInstancesInfoByFilter(self, filter_fn):
1568
    """Get instance configuration with a filter.
1569

1570
    @type filter_fn: callable
1571
    @param filter_fn: Filter function receiving instance object as parameter,
1572
      returning boolean. Important: this function is called while the
1573
      configuration locks is held. It must not do any complex work or call
1574
      functions potentially leading to a deadlock. Ideally it doesn't call any
1575
      other functions and just compares instance attributes.
1576

1577
    """
1578
    return dict((name, inst)
1579
                for (name, inst) in self._config_data.instances.items()
1580
                if filter_fn(inst))
1581

    
1582
  @locking.ssynchronized(_config_lock)
1583
  def AddNode(self, node, ec_id):
1584
    """Add a node to the configuration.
1585

1586
    @type node: L{objects.Node}
1587
    @param node: a Node instance
1588

1589
    """
1590
    logging.info("Adding node %s to configuration", node.name)
1591

    
1592
    self._EnsureUUID(node, ec_id)
1593

    
1594
    node.serial_no = 1
1595
    node.ctime = node.mtime = time.time()
1596
    self._UnlockedAddNodeToGroup(node.name, node.group)
1597
    self._config_data.nodes[node.name] = node
1598
    self._config_data.cluster.serial_no += 1
1599
    self._WriteConfig()
1600

    
1601
  @locking.ssynchronized(_config_lock)
1602
  def RemoveNode(self, node_name):
1603
    """Remove a node from the configuration.
1604

1605
    """
1606
    logging.info("Removing node %s from configuration", node_name)
1607

    
1608
    if node_name not in self._config_data.nodes:
1609
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1610

    
1611
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1612
    del self._config_data.nodes[node_name]
1613
    self._config_data.cluster.serial_no += 1
1614
    self._WriteConfig()
1615

    
1616
  def ExpandNodeName(self, short_name):
1617
    """Attempt to expand an incomplete node name.
1618

1619
    """
1620
    # Locking is done in L{ConfigWriter.GetNodeList}
1621
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1622

    
1623
  def _UnlockedGetNodeInfo(self, node_name):
1624
    """Get the configuration of a node, as stored in the config.
1625

1626
    This function is for internal use, when the config lock is already
1627
    held.
1628

1629
    @param node_name: the node name, e.g. I{node1.example.com}
1630

1631
    @rtype: L{objects.Node}
1632
    @return: the node object
1633

1634
    """
1635
    if node_name not in self._config_data.nodes:
1636
      return None
1637

    
1638
    return self._config_data.nodes[node_name]
1639

    
1640
  @locking.ssynchronized(_config_lock, shared=1)
1641
  def GetNodeInfo(self, node_name):
1642
    """Get the configuration of a node, as stored in the config.
1643

1644
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1645

1646
    @param node_name: the node name, e.g. I{node1.example.com}
1647

1648
    @rtype: L{objects.Node}
1649
    @return: the node object
1650

1651
    """
1652
    return self._UnlockedGetNodeInfo(node_name)
1653

    
1654
  @locking.ssynchronized(_config_lock, shared=1)
1655
  def GetNodeInstances(self, node_name):
1656
    """Get the instances of a node, as stored in the config.
1657

1658
    @param node_name: the node name, e.g. I{node1.example.com}
1659

1660
    @rtype: (list, list)
1661
    @return: a tuple with two lists: the primary and the secondary instances
1662

1663
    """
1664
    pri = []
1665
    sec = []
1666
    for inst in self._config_data.instances.values():
1667
      if inst.primary_node == node_name:
1668
        pri.append(inst.name)
1669
      if node_name in inst.secondary_nodes:
1670
        sec.append(inst.name)
1671
    return (pri, sec)
1672

    
1673
  @locking.ssynchronized(_config_lock, shared=1)
1674
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1675
    """Get the instances of a node group.
1676

1677
    @param uuid: Node group UUID
1678
    @param primary_only: Whether to only consider primary nodes
1679
    @rtype: frozenset
1680
    @return: List of instance names in node group
1681

1682
    """
1683
    if primary_only:
1684
      nodes_fn = lambda inst: [inst.primary_node]
1685
    else:
1686
      nodes_fn = lambda inst: inst.all_nodes
1687

    
1688
    return frozenset(inst.name
1689
                     for inst in self._config_data.instances.values()
1690
                     for node_name in nodes_fn(inst)
1691
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1692

    
1693
  def _UnlockedGetNodeList(self):
1694
    """Return the list of nodes which are in the configuration.
1695

1696
    This function is for internal use, when the config lock is already
1697
    held.
1698

1699
    @rtype: list
1700

1701
    """
1702
    return self._config_data.nodes.keys()
1703

    
1704
  @locking.ssynchronized(_config_lock, shared=1)
1705
  def GetNodeList(self):
1706
    """Return the list of nodes which are in the configuration.
1707

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

    
1711
  def _UnlockedGetOnlineNodeList(self):
1712
    """Return the list of nodes which are online.
1713

1714
    """
1715
    all_nodes = [self._UnlockedGetNodeInfo(node)
1716
                 for node in self._UnlockedGetNodeList()]
1717
    return [node.name for node in all_nodes if not node.offline]
1718

    
1719
  @locking.ssynchronized(_config_lock, shared=1)
1720
  def GetOnlineNodeList(self):
1721
    """Return the list of nodes which are online.
1722

1723
    """
1724
    return self._UnlockedGetOnlineNodeList()
1725

    
1726
  @locking.ssynchronized(_config_lock, shared=1)
1727
  def GetVmCapableNodeList(self):
1728
    """Return the list of nodes which are not vm capable.
1729

1730
    """
1731
    all_nodes = [self._UnlockedGetNodeInfo(node)
1732
                 for node in self._UnlockedGetNodeList()]
1733
    return [node.name for node in all_nodes if node.vm_capable]
1734

    
1735
  @locking.ssynchronized(_config_lock, shared=1)
1736
  def GetNonVmCapableNodeList(self):
1737
    """Return the list of nodes which are not vm capable.
1738

1739
    """
1740
    all_nodes = [self._UnlockedGetNodeInfo(node)
1741
                 for node in self._UnlockedGetNodeList()]
1742
    return [node.name for node in all_nodes if not node.vm_capable]
1743

    
1744
  @locking.ssynchronized(_config_lock, shared=1)
1745
  def GetMultiNodeInfo(self, nodes):
1746
    """Get the configuration of multiple nodes.
1747

1748
    @param nodes: list of node names
1749
    @rtype: list
1750
    @return: list of tuples of (node, node_info), where node_info is
1751
        what would GetNodeInfo return for the node, in the original
1752
        order
1753

1754
    """
1755
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1756

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

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

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

    
1768
  def _UnlockedGetAllNodesInfo(self):
1769
    """Gets configuration of all nodes.
1770

1771
    @note: See L{GetAllNodesInfo}
1772

1773
    """
1774
    return dict([(node, self._UnlockedGetNodeInfo(node))
1775
                 for node in self._UnlockedGetNodeList()])
1776

    
1777
  @locking.ssynchronized(_config_lock, shared=1)
1778
  def GetNodeGroupsFromNodes(self, nodes):
1779
    """Returns groups for a list of nodes.
1780

1781
    @type nodes: list of string
1782
    @param nodes: List of node names
1783
    @rtype: frozenset
1784

1785
    """
1786
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1787

    
1788
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1789
    """Get the number of current and maximum desired and possible candidates.
1790

1791
    @type exceptions: list
1792
    @param exceptions: if passed, list of nodes that should be ignored
1793
    @rtype: tuple
1794
    @return: tuple of (current, desired and possible, possible)
1795

1796
    """
1797
    mc_now = mc_should = mc_max = 0
1798
    for node in self._config_data.nodes.values():
1799
      if exceptions and node.name in exceptions:
1800
        continue
1801
      if not (node.offline or node.drained) and node.master_capable:
1802
        mc_max += 1
1803
      if node.master_candidate:
1804
        mc_now += 1
1805
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1806
    return (mc_now, mc_should, mc_max)
1807

    
1808
  @locking.ssynchronized(_config_lock, shared=1)
1809
  def GetMasterCandidateStats(self, exceptions=None):
1810
    """Get the number of current and maximum possible candidates.
1811

1812
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1813

1814
    @type exceptions: list
1815
    @param exceptions: if passed, list of nodes that should be ignored
1816
    @rtype: tuple
1817
    @return: tuple of (current, max)
1818

1819
    """
1820
    return self._UnlockedGetMasterCandidateStats(exceptions)
1821

    
1822
  @locking.ssynchronized(_config_lock)
1823
  def MaintainCandidatePool(self, exceptions):
1824
    """Try to grow the candidate pool to the desired size.
1825

1826
    @type exceptions: list
1827
    @param exceptions: if passed, list of nodes that should be ignored
1828
    @rtype: list
1829
    @return: list with the adjusted nodes (L{objects.Node} instances)
1830

1831
    """
1832
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1833
    mod_list = []
1834
    if mc_now < mc_max:
1835
      node_list = self._config_data.nodes.keys()
1836
      random.shuffle(node_list)
1837
      for name in node_list:
1838
        if mc_now >= mc_max:
1839
          break
1840
        node = self._config_data.nodes[name]
1841
        if (node.master_candidate or node.offline or node.drained or
1842
            node.name in exceptions or not node.master_capable):
1843
          continue
1844
        mod_list.append(node)
1845
        node.master_candidate = True
1846
        node.serial_no += 1
1847
        mc_now += 1
1848
      if mc_now != mc_max:
1849
        # this should not happen
1850
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1851
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1852
      if mod_list:
1853
        self._config_data.cluster.serial_no += 1
1854
        self._WriteConfig()
1855

    
1856
    return mod_list
1857

    
1858
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1859
    """Add a given node to the specified group.
1860

1861
    """
1862
    if nodegroup_uuid not in self._config_data.nodegroups:
1863
      # This can happen if a node group gets deleted between its lookup and
1864
      # when we're adding the first node to it, since we don't keep a lock in
1865
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1866
      # is not found anymore.
1867
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1868
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1869
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1870

    
1871
  def _UnlockedRemoveNodeFromGroup(self, node):
1872
    """Remove a given node from its group.
1873

1874
    """
1875
    nodegroup = node.group
1876
    if nodegroup not in self._config_data.nodegroups:
1877
      logging.warning("Warning: node '%s' has unknown node group '%s'"
1878
                      " (while being removed from it)", node.name, nodegroup)
1879
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1880
    if node.name not in nodegroup_obj.members:
1881
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
1882
                      " (while being removed from it)", node.name, nodegroup)
1883
    else:
1884
      nodegroup_obj.members.remove(node.name)
1885

    
1886
  @locking.ssynchronized(_config_lock)
1887
  def AssignGroupNodes(self, mods):
1888
    """Changes the group of a number of nodes.
1889

1890
    @type mods: list of tuples; (node name, new group UUID)
1891
    @param mods: Node membership modifications
1892

1893
    """
1894
    groups = self._config_data.nodegroups
1895
    nodes = self._config_data.nodes
1896

    
1897
    resmod = []
1898

    
1899
    # Try to resolve names/UUIDs first
1900
    for (node_name, new_group_uuid) in mods:
1901
      try:
1902
        node = nodes[node_name]
1903
      except KeyError:
1904
        raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1905

    
1906
      if node.group == new_group_uuid:
1907
        # Node is being assigned to its current group
1908
        logging.debug("Node '%s' was assigned to its current group (%s)",
1909
                      node_name, node.group)
1910
        continue
1911

    
1912
      # Try to find current group of node
1913
      try:
1914
        old_group = groups[node.group]
1915
      except KeyError:
1916
        raise errors.ConfigurationError("Unable to find old group '%s'" %
1917
                                        node.group)
1918

    
1919
      # Try to find new group for node
1920
      try:
1921
        new_group = groups[new_group_uuid]
1922
      except KeyError:
1923
        raise errors.ConfigurationError("Unable to find new group '%s'" %
1924
                                        new_group_uuid)
1925

    
1926
      assert node.name in old_group.members, \
1927
        ("Inconsistent configuration: node '%s' not listed in members for its"
1928
         " old group '%s'" % (node.name, old_group.uuid))
1929
      assert node.name not in new_group.members, \
1930
        ("Inconsistent configuration: node '%s' already listed in members for"
1931
         " its new group '%s'" % (node.name, new_group.uuid))
1932

    
1933
      resmod.append((node, old_group, new_group))
1934

    
1935
    # Apply changes
1936
    for (node, old_group, new_group) in resmod:
1937
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
1938
        "Assigning to current group is not possible"
1939

    
1940
      node.group = new_group.uuid
1941

    
1942
      # Update members of involved groups
1943
      if node.name in old_group.members:
1944
        old_group.members.remove(node.name)
1945
      if node.name not in new_group.members:
1946
        new_group.members.append(node.name)
1947

    
1948
    # Update timestamps and serials (only once per node/group object)
1949
    now = time.time()
1950
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
1951
      obj.serial_no += 1
1952
      obj.mtime = now
1953

    
1954
    # Force ssconf update
1955
    self._config_data.cluster.serial_no += 1
1956

    
1957
    self._WriteConfig()
1958

    
1959
  def _BumpSerialNo(self):
1960
    """Bump up the serial number of the config.
1961

1962
    """
1963
    self._config_data.serial_no += 1
1964
    self._config_data.mtime = time.time()
1965

    
1966
  def _AllUUIDObjects(self):
1967
    """Returns all objects with uuid attributes.
1968

1969
    """
1970
    return (self._config_data.instances.values() +
1971
            self._config_data.nodes.values() +
1972
            self._config_data.nodegroups.values() +
1973
            [self._config_data.cluster])
1974

    
1975
  def _OpenConfig(self, accept_foreign):
1976
    """Read the config data from disk.
1977

1978
    """
1979
    raw_data = utils.ReadFile(self._cfg_file)
1980

    
1981
    try:
1982
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1983
    except Exception, err:
1984
      raise errors.ConfigurationError(err)
1985

    
1986
    # Make sure the configuration has the right version
1987
    _ValidateConfig(data)
1988

    
1989
    if (not hasattr(data, "cluster") or
1990
        not hasattr(data.cluster, "rsahostkeypub")):
1991
      raise errors.ConfigurationError("Incomplete configuration"
1992
                                      " (missing cluster.rsahostkeypub)")
1993

    
1994
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
1995
      msg = ("The configuration denotes node %s as master, while my"
1996
             " hostname is %s; opening a foreign configuration is only"
1997
             " possible in accept_foreign mode" %
1998
             (data.cluster.master_node, self._my_hostname))
1999
      raise errors.ConfigurationError(msg)
2000

    
2001
    # Upgrade configuration if needed
2002
    data.UpgradeConfig()
2003

    
2004
    self._config_data = data
2005
    # reset the last serial as -1 so that the next write will cause
2006
    # ssconf update
2007
    self._last_cluster_serial = -1
2008

    
2009
    # And finally run our (custom) config upgrade sequence
2010
    self._UpgradeConfig()
2011

    
2012
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2013

    
2014
  def _UpgradeConfig(self):
2015
    """Run upgrade steps that cannot be done purely in the objects.
2016

2017
    This is because some data elements need uniqueness across the
2018
    whole configuration, etc.
2019

2020
    @warning: this function will call L{_WriteConfig()}, but also
2021
        L{DropECReservations} so it needs to be called only from a
2022
        "safe" place (the constructor). If one wanted to call it with
2023
        the lock held, a DropECReservationUnlocked would need to be
2024
        created first, to avoid causing deadlock.
2025

2026
    """
2027
    modified = False
2028
    for item in self._AllUUIDObjects():
2029
      if item.uuid is None:
2030
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
2031
        modified = True
2032
    if not self._config_data.nodegroups:
2033
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
2034
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
2035
                                            members=[])
2036
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
2037
      modified = True
2038
    for node in self._config_data.nodes.values():
2039
      if not node.group:
2040
        node.group = self.LookupNodeGroup(None)
2041
        modified = True
2042
      # This is technically *not* an upgrade, but needs to be done both when
2043
      # nodegroups are being added, and upon normally loading the config,
2044
      # because the members list of a node group is discarded upon
2045
      # serializing/deserializing the object.
2046
      self._UnlockedAddNodeToGroup(node.name, node.group)
2047
    if modified:
2048
      self._WriteConfig()
2049
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
2050
      # only called at config init time, without the lock held
2051
      self.DropECReservations(_UPGRADE_CONFIG_JID)
2052

    
2053
  def _DistributeConfig(self, feedback_fn):
2054
    """Distribute the configuration to the other nodes.
2055

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

2059
    """
2060
    if self._offline:
2061
      return True
2062

    
2063
    bad = False
2064

    
2065
    node_list = []
2066
    addr_list = []
2067
    myhostname = self._my_hostname
2068
    # we can skip checking whether _UnlockedGetNodeInfo returns None
2069
    # since the node list comes from _UnlocketGetNodeList, and we are
2070
    # called with the lock held, so no modifications should take place
2071
    # in between
2072
    for node_name in self._UnlockedGetNodeList():
2073
      if node_name == myhostname:
2074
        continue
2075
      node_info = self._UnlockedGetNodeInfo(node_name)
2076
      if not node_info.master_candidate:
2077
        continue
2078
      node_list.append(node_info.name)
2079
      addr_list.append(node_info.primary_ip)
2080

    
2081
    # TODO: Use dedicated resolver talking to config writer for name resolution
2082
    result = \
2083
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2084
    for to_node, to_result in result.items():
2085
      msg = to_result.fail_msg
2086
      if msg:
2087
        msg = ("Copy of file %s to node %s failed: %s" %
2088
               (self._cfg_file, to_node, msg))
2089
        logging.error(msg)
2090

    
2091
        if feedback_fn:
2092
          feedback_fn(msg)
2093

    
2094
        bad = True
2095

    
2096
    return not bad
2097

    
2098
  def _WriteConfig(self, destination=None, feedback_fn=None):
2099
    """Write the configuration data to persistent storage.
2100

2101
    """
2102
    assert feedback_fn is None or callable(feedback_fn)
2103

    
2104
    # Warn on config errors, but don't abort the save - the
2105
    # configuration has already been modified, and we can't revert;
2106
    # the best we can do is to warn the user and save as is, leaving
2107
    # recovery to the user
2108
    config_errors = self._UnlockedVerifyConfig()
2109
    if config_errors:
2110
      errmsg = ("Configuration data is not consistent: %s" %
2111
                (utils.CommaJoin(config_errors)))
2112
      logging.critical(errmsg)
2113
      if feedback_fn:
2114
        feedback_fn(errmsg)
2115

    
2116
    if destination is None:
2117
      destination = self._cfg_file
2118
    self._BumpSerialNo()
2119
    txt = serializer.Dump(self._config_data.ToDict())
2120

    
2121
    getents = self._getents()
2122
    try:
2123
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2124
                               close=False, gid=getents.confd_gid, mode=0640)
2125
    except errors.LockError:
2126
      raise errors.ConfigurationError("The configuration file has been"
2127
                                      " modified since the last write, cannot"
2128
                                      " update")
2129
    try:
2130
      self._cfg_id = utils.GetFileID(fd=fd)
2131
    finally:
2132
      os.close(fd)
2133

    
2134
    self.write_count += 1
2135

    
2136
    # and redistribute the config file to master candidates
2137
    self._DistributeConfig(feedback_fn)
2138

    
2139
    # Write ssconf files on all nodes (including locally)
2140
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2141
      if not self._offline:
2142
        result = self._GetRpc(None).call_write_ssconf_files(
2143
          self._UnlockedGetOnlineNodeList(),
2144
          self._UnlockedGetSsconfValues())
2145

    
2146
        for nname, nresu in result.items():
2147
          msg = nresu.fail_msg
2148
          if msg:
2149
            errmsg = ("Error while uploading ssconf files to"
2150
                      " node %s: %s" % (nname, msg))
2151
            logging.warning(errmsg)
2152

    
2153
            if feedback_fn:
2154
              feedback_fn(errmsg)
2155

    
2156
      self._last_cluster_serial = self._config_data.cluster.serial_no
2157

    
2158
  def _UnlockedGetSsconfValues(self):
2159
    """Return the values needed by ssconf.
2160

2161
    @rtype: dict
2162
    @return: a dictionary with keys the ssconf names and values their
2163
        associated value
2164

2165
    """
2166
    fn = "\n".join
2167
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
2168
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
2169
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
2170
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2171
                    for ninfo in node_info]
2172
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2173
                    for ninfo in node_info]
2174

    
2175
    instance_data = fn(instance_names)
2176
    off_data = fn(node.name for node in node_info if node.offline)
2177
    on_data = fn(node.name for node in node_info if not node.offline)
2178
    mc_data = fn(node.name for node in node_info if node.master_candidate)
2179
    mc_ips_data = fn(node.primary_ip for node in node_info
2180
                     if node.master_candidate)
2181
    node_data = fn(node_names)
2182
    node_pri_ips_data = fn(node_pri_ips)
2183
    node_snd_ips_data = fn(node_snd_ips)
2184

    
2185
    cluster = self._config_data.cluster
2186
    cluster_tags = fn(cluster.GetTags())
2187

    
2188
    hypervisor_list = fn(cluster.enabled_hypervisors)
2189

    
2190
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2191

    
2192
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2193
                  self._config_data.nodegroups.values()]
2194
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2195
    networks = ["%s %s" % (net.uuid, net.name) for net in
2196
                self._config_data.networks.values()]
2197
    networks_data = fn(utils.NiceSort(networks))
2198

    
2199
    ssconf_values = {
2200
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
2201
      constants.SS_CLUSTER_TAGS: cluster_tags,
2202
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2203
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2204
      constants.SS_MASTER_CANDIDATES: mc_data,
2205
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2206
      constants.SS_MASTER_IP: cluster.master_ip,
2207
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
2208
      constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2209
      constants.SS_MASTER_NODE: cluster.master_node,
2210
      constants.SS_NODE_LIST: node_data,
2211
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2212
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2213
      constants.SS_OFFLINE_NODES: off_data,
2214
      constants.SS_ONLINE_NODES: on_data,
2215
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2216
      constants.SS_INSTANCE_LIST: instance_data,
2217
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2218
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
2219
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2220
      constants.SS_UID_POOL: uid_pool,
2221
      constants.SS_NODEGROUPS: nodegroups_data,
2222
      constants.SS_NETWORKS: networks_data,
2223
      }
2224
    bad_values = [(k, v) for k, v in ssconf_values.items()
2225
                  if not isinstance(v, (str, basestring))]
2226
    if bad_values:
2227
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2228
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2229
                                      " values: %s" % err)
2230
    return ssconf_values
2231

    
2232
  @locking.ssynchronized(_config_lock, shared=1)
2233
  def GetSsconfValues(self):
2234
    """Wrapper using lock around _UnlockedGetSsconf().
2235

2236
    """
2237
    return self._UnlockedGetSsconfValues()
2238

    
2239
  @locking.ssynchronized(_config_lock, shared=1)
2240
  def GetVGName(self):
2241
    """Return the volume group name.
2242

2243
    """
2244
    return self._config_data.cluster.volume_group_name
2245

    
2246
  @locking.ssynchronized(_config_lock)
2247
  def SetVGName(self, vg_name):
2248
    """Set the volume group name.
2249

2250
    """
2251
    self._config_data.cluster.volume_group_name = vg_name
2252
    self._config_data.cluster.serial_no += 1
2253
    self._WriteConfig()
2254

    
2255
  @locking.ssynchronized(_config_lock, shared=1)
2256
  def GetDRBDHelper(self):
2257
    """Return DRBD usermode helper.
2258

2259
    """
2260
    return self._config_data.cluster.drbd_usermode_helper
2261

    
2262
  @locking.ssynchronized(_config_lock)
2263
  def SetDRBDHelper(self, drbd_helper):
2264
    """Set DRBD usermode helper.
2265

2266
    """
2267
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2268
    self._config_data.cluster.serial_no += 1
2269
    self._WriteConfig()
2270

    
2271
  @locking.ssynchronized(_config_lock, shared=1)
2272
  def GetMACPrefix(self):
2273
    """Return the mac prefix.
2274

2275
    """
2276
    return self._config_data.cluster.mac_prefix
2277

    
2278
  @locking.ssynchronized(_config_lock, shared=1)
2279
  def GetClusterInfo(self):
2280
    """Returns information about the cluster
2281

2282
    @rtype: L{objects.Cluster}
2283
    @return: the cluster object
2284

2285
    """
2286
    return self._config_data.cluster
2287

    
2288
  @locking.ssynchronized(_config_lock, shared=1)
2289
  def HasAnyDiskOfType(self, dev_type):
2290
    """Check if in there is at disk of the given type in the configuration.
2291

2292
    """
2293
    return self._config_data.HasAnyDiskOfType(dev_type)
2294

    
2295
  @locking.ssynchronized(_config_lock)
2296
  def Update(self, target, feedback_fn):
2297
    """Notify function to be called after updates.
2298

2299
    This function must be called when an object (as returned by
2300
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2301
    caller wants the modifications saved to the backing store. Note
2302
    that all modified objects will be saved, but the target argument
2303
    is the one the caller wants to ensure that it's saved.
2304

2305
    @param target: an instance of either L{objects.Cluster},
2306
        L{objects.Node} or L{objects.Instance} which is existing in
2307
        the cluster
2308
    @param feedback_fn: Callable feedback function
2309

2310
    """
2311
    if self._config_data is None:
2312
      raise errors.ProgrammerError("Configuration file not read,"
2313
                                   " cannot save.")
2314
    update_serial = False
2315
    if isinstance(target, objects.Cluster):
2316
      test = target == self._config_data.cluster
2317
    elif isinstance(target, objects.Node):
2318
      test = target in self._config_data.nodes.values()
2319
      update_serial = True
2320
    elif isinstance(target, objects.Instance):
2321
      test = target in self._config_data.instances.values()
2322
    elif isinstance(target, objects.NodeGroup):
2323
      test = target in self._config_data.nodegroups.values()
2324
    elif isinstance(target, objects.Network):
2325
      test = target in self._config_data.networks.values()
2326
    else:
2327
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2328
                                   " ConfigWriter.Update" % type(target))
2329
    if not test:
2330
      raise errors.ConfigurationError("Configuration updated since object"
2331
                                      " has been read or unknown object")
2332
    target.serial_no += 1
2333
    target.mtime = now = time.time()
2334

    
2335
    if update_serial:
2336
      # for node updates, we need to increase the cluster serial too
2337
      self._config_data.cluster.serial_no += 1
2338
      self._config_data.cluster.mtime = now
2339

    
2340
    if isinstance(target, objects.Instance):
2341
      self._UnlockedReleaseDRBDMinors(target.name)
2342

    
2343
    self._WriteConfig(feedback_fn=feedback_fn)
2344

    
2345
  @locking.ssynchronized(_config_lock)
2346
  def DropECReservations(self, ec_id):
2347
    """Drop per-execution-context reservations
2348

2349
    """
2350
    for rm in self._all_rms:
2351
      rm.DropECReservations(ec_id)
2352

    
2353
  @locking.ssynchronized(_config_lock, shared=1)
2354
  def GetAllNetworksInfo(self):
2355
    """Get the configuration of all networks
2356

2357
    """
2358
    return dict(self._config_data.networks)
2359

    
2360
  def _UnlockedGetNetworkList(self):
2361
    """Get the list of networks.
2362

2363
    This function is for internal use, when the config lock is already held.
2364

2365
    """
2366
    return self._config_data.networks.keys()
2367

    
2368
  @locking.ssynchronized(_config_lock, shared=1)
2369
  def GetNetworkList(self):
2370
    """Get the list of networks.
2371

2372
    @return: array of networks, ex. ["main", "vlan100", "200]
2373

2374
    """
2375
    return self._UnlockedGetNetworkList()
2376

    
2377
  @locking.ssynchronized(_config_lock, shared=1)
2378
  def GetNetworkNames(self):
2379
    """Get a list of network names
2380

2381
    """
2382
    names = [network.name
2383
             for network in self._config_data.networks.values()]
2384
    return names
2385

    
2386
  def _UnlockedGetNetwork(self, uuid):
2387
    """Returns information about a network.
2388

2389
    This function is for internal use, when the config lock is already held.
2390

2391
    """
2392
    if uuid not in self._config_data.networks:
2393
      return None
2394

    
2395
    return self._config_data.networks[uuid]
2396

    
2397
  @locking.ssynchronized(_config_lock, shared=1)
2398
  def GetNetwork(self, uuid):
2399
    """Returns information about a network.
2400

2401
    It takes the information from the configuration file.
2402

2403
    @param uuid: UUID of the network
2404

2405
    @rtype: L{objects.Network}
2406
    @return: the network object
2407

2408
    """
2409
    return self._UnlockedGetNetwork(uuid)
2410

    
2411
  @locking.ssynchronized(_config_lock)
2412
  def AddNetwork(self, net, ec_id, check_uuid=True):
2413
    """Add a network to the configuration.
2414

2415
    @type net: L{objects.Network}
2416
    @param net: the Network object to add
2417
    @type ec_id: string
2418
    @param ec_id: unique id for the job to use when creating a missing UUID
2419

2420
    """
2421
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2422
    self._WriteConfig()
2423

    
2424
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2425
    """Add a network to the configuration.
2426

2427
    """
2428
    logging.info("Adding network %s to configuration", net.name)
2429

    
2430
    if check_uuid:
2431
      self._EnsureUUID(net, ec_id)
2432

    
2433
    existing_uuid = self._UnlockedLookupNetwork(net.name)
2434
    if existing_uuid:
2435
      raise errors.OpPrereqError("Desired network name '%s' already"
2436
                                 " exists as a network (UUID: %s)" %
2437
                                 (net.name, existing_uuid),
2438
                                 errors.ECODE_EXISTS)
2439
    net.serial_no = 1
2440
    self._config_data.networks[net.uuid] = net
2441
    self._config_data.cluster.serial_no += 1
2442

    
2443
  def _UnlockedLookupNetwork(self, target):
2444
    """Lookup a network's UUID.
2445

2446
    @type target: string
2447
    @param target: network name or UUID
2448
    @rtype: string
2449
    @return: network UUID
2450
    @raises errors.OpPrereqError: when the target network cannot be found
2451

2452
    """
2453
    if target in self._config_data.networks:
2454
      return target
2455
    for net in self._config_data.networks.values():
2456
      if net.name == target:
2457
        return net.uuid
2458
    return None
2459

    
2460
  @locking.ssynchronized(_config_lock, shared=1)
2461
  def LookupNetwork(self, target):
2462
    """Lookup a network's UUID.
2463

2464
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2465

2466
    @type target: string
2467
    @param target: network name or UUID
2468
    @rtype: string
2469
    @return: network UUID
2470

2471
    """
2472
    return self._UnlockedLookupNetwork(target)
2473

    
2474
  @locking.ssynchronized(_config_lock)
2475
  def RemoveNetwork(self, network_uuid):
2476
    """Remove a network from the configuration.
2477

2478
    @type network_uuid: string
2479
    @param network_uuid: the UUID of the network to remove
2480

2481
    """
2482
    logging.info("Removing network %s from configuration", network_uuid)
2483

    
2484
    if network_uuid not in self._config_data.networks:
2485
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2486

    
2487
    del self._config_data.networks[network_uuid]
2488
    self._config_data.cluster.serial_no += 1
2489
    self._WriteConfig()
2490

    
2491
  def _UnlockedGetGroupNetParams(self, net, node):
2492
    """Get the netparams (mode, link) of a network.
2493

2494
    Get a network's netparams for a given node.
2495

2496
    @type net: string
2497
    @param net: network name
2498
    @type node: string
2499
    @param node: node name
2500
    @rtype: dict or None
2501
    @return: netparams
2502

2503
    """
2504
    net_uuid = self._UnlockedLookupNetwork(net)
2505
    if net_uuid is None:
2506
      return None
2507

    
2508
    node_info = self._UnlockedGetNodeInfo(node)
2509
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2510
    netparams = nodegroup_info.networks.get(net_uuid, None)
2511

    
2512
    return netparams
2513

    
2514
  @locking.ssynchronized(_config_lock, shared=1)
2515
  def GetGroupNetParams(self, net, node):
2516
    """Locking wrapper of _UnlockedGetGroupNetParams()
2517

2518
    """
2519
    return self._UnlockedGetGroupNetParams(net, node)
2520

    
2521

    
2522
  @locking.ssynchronized(_config_lock, shared=1)
2523
  def CheckIPInNodeGroup(self, ip, node):
2524
    """Check for conflictig IP.
2525

2526
    @type ip: string
2527
    @param ip: ip address
2528
    @type node: string
2529
    @param node: node name
2530
    @rtype: (string, dict) or (None, None)
2531
    @return: (network name, netparams)
2532

2533
    """
2534
    if ip is None:
2535
      return (None, None)
2536
    node_info = self._UnlockedGetNodeInfo(node)
2537
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2538
    for net_uuid in nodegroup_info.networks.keys():
2539
      net_info = self._UnlockedGetNetwork(net_uuid)
2540
      pool = network.AddressPool(net_info)
2541
      if pool._Contains(ip):
2542
        return (net_info.name, nodegroup_info.networks[net_uuid])
2543

    
2544
    return (None, None)