Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ c01a7953

History | View | Annotate | Download (86.9 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Configuration management for Ganeti
23

24
This module provides the interface to the Ganeti cluster configuration.
25

26
The configuration data is stored on every node but is updated on the master
27
only. After each update, the master distributes the data to the other nodes.
28

29
Currently, the data storage format is JSON. YAML was slow and consuming too
30
much memory.
31

32
"""
33

    
34
# pylint: disable=R0904
35
# R0904: Too many public methods
36

    
37
import copy
38
import os
39
import random
40
import logging
41
import time
42
import itertools
43

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

    
57

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

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

    
63

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

67
  This only verifies the version of the configuration.
68

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

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

    
76

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

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

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

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

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

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

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

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

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

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

126
    """
127
    assert callable(generate_one_fn)
128

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

    
142

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

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

    
149

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

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

159
  """
160
  result = []
161

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

    
167
  return result
168

    
169

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

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

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

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

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

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

216
    """
217
    self._context = context
218

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

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

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

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

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

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

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

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

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

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

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

    
263
  def _UnlockedGetGroupDiskParams(self, group):
264
    """Get the disk params populated with inherit chain down to node-group.
265

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

270
    """
271
    return self._config_data.cluster.SimpleFillDP(group.diskparams)
272

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

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

    
283
    return prefix
284

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

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

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

    
301
    return GenMac
302

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

307
    This should check the current instances for duplicates.
308

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

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

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

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

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

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

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

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

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

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

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

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

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

365
    This is just a wrapper around _UnlockedReleaseIp.
366

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

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

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

    
379
    def gen_one():
380
      try:
381
        ip = pool.GenerateFree()
382
      except errors.AddressPoolError:
383
        raise errors.OpPrereqError("Cannot generate IP."
384
                                   " Network '%s' is full." % nobj.name,
385
                                   errors.ECODE_STATE)
386
      return (constants.RESERVE_ACTION, ip, net_uuid, False)
387

    
388
    _, address, _, _ = self._temporary_ips.Generate([], gen_one, ec_id)
389
    return address
390

    
391
  def _UnlockedReserveIp(self, net_uuid, address, external, ec_id):
392
    """Reserve a given IPv4 address for use by an instance.
393

394
    """
395
    nobj = self._UnlockedGetNetwork(net_uuid)
396
    pool = network.AddressPool(nobj)
397
    if pool.IsReserved(address):
398
      raise errors.OpPrereqError("IP address '%s' already in use." %
399
                                 address, errors.ECODE_EXISTS)
400

    
401
    return self._temporary_ips.Reserve(ec_id,
402
                                       (constants.RESERVE_ACTION,
403
                                        address, net_uuid, external))
404

    
405
  @locking.ssynchronized(_config_lock, shared=1)
406
  def ReserveIp(self, net_uuid, address, external, ec_id):
407
    """Reserve a given IPv4 address for use by an instance.
408

409
    """
410
    if net_uuid:
411
      return self._UnlockedReserveIp(net_uuid, address, external, ec_id)
412

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

417
    @type lv_name: string
418
    @param lv_name: the logical volume name to reserve
419

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

    
427
  @locking.ssynchronized(_config_lock, shared=1)
428
  def GenerateDRBDSecret(self, ec_id):
429
    """Generate a DRBD secret.
430

431
    This checks the current disks for duplicates.
432

433
    """
434
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
435
                                            utils.GenerateSecret,
436
                                            ec_id)
437

    
438
  def _AllLVs(self):
439
    """Compute the list of all LVs.
440

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

    
449
  def _AllDisks(self):
450
    """Compute the list of all Disks.
451

452
    """
453
    disks = []
454
    for instance in self._config_data.instances.values():
455
      disks.extend(instance.disks)
456
    return disks
457

    
458
  def _AllNICs(self):
459
    """Compute the list of all NICs.
460

461
    """
462
    nics = []
463
    for instance in self._config_data.instances.values():
464
      nics.extend(instance.nics)
465
    return nics
466

    
467
  def _AllIDs(self, include_temporary):
468
    """Compute the list of all UUIDs and names we have.
469

470
    @type include_temporary: boolean
471
    @param include_temporary: whether to include the _temporary_ids set
472
    @rtype: set
473
    @return: a set of IDs
474

475
    """
476
    existing = set()
477
    if include_temporary:
478
      existing.update(self._temporary_ids.GetReserved())
479
    existing.update(self._AllLVs())
480
    existing.update(self._config_data.instances.keys())
481
    existing.update(self._config_data.nodes.keys())
482
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
483
    return existing
484

    
485
  def _GenerateUniqueID(self, ec_id):
486
    """Generate an unique UUID.
487

488
    This checks the current node, instances and disk names for
489
    duplicates.
490

491
    @rtype: string
492
    @return: the unique id
493

494
    """
495
    existing = self._AllIDs(include_temporary=False)
496
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
497

    
498
  @locking.ssynchronized(_config_lock, shared=1)
499
  def GenerateUniqueID(self, ec_id):
500
    """Generate an unique ID.
501

502
    This is just a wrapper over the unlocked version.
503

504
    @type ec_id: string
505
    @param ec_id: unique id for the job to reserve the id to
506

507
    """
508
    return self._GenerateUniqueID(ec_id)
509

    
510
  def _AllMACs(self):
511
    """Return all MACs present in the config.
512

513
    @rtype: list
514
    @return: the list of all MACs
515

516
    """
517
    result = []
518
    for instance in self._config_data.instances.values():
519
      for nic in instance.nics:
520
        result.append(nic.mac)
521

    
522
    return result
523

    
524
  def _AllDRBDSecrets(self):
525
    """Return all DRBD secrets present in the config.
526

527
    @rtype: list
528
    @return: the list of all DRBD secrets
529

530
    """
531
    def helper(disk, result):
532
      """Recursively gather secrets from this disk."""
533
      if disk.dev_type == constants.DT_DRBD8:
534
        result.append(disk.logical_id[5])
535
      if disk.children:
536
        for child in disk.children:
537
          helper(child, result)
538

    
539
    result = []
540
    for instance in self._config_data.instances.values():
541
      for disk in instance.disks:
542
        helper(disk, result)
543

    
544
    return result
545

    
546
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
547
    """Compute duplicate disk IDs
548

549
    @type disk: L{objects.Disk}
550
    @param disk: the disk at which to start searching
551
    @type l_ids: list
552
    @param l_ids: list of current logical ids
553
    @type p_ids: list
554
    @param p_ids: list of current physical ids
555
    @rtype: list
556
    @return: a list of error messages
557

558
    """
559
    result = []
560
    if disk.logical_id is not None:
561
      if disk.logical_id in l_ids:
562
        result.append("duplicate logical id %s" % str(disk.logical_id))
563
      else:
564
        l_ids.append(disk.logical_id)
565
    if disk.physical_id is not None:
566
      if disk.physical_id in p_ids:
567
        result.append("duplicate physical id %s" % str(disk.physical_id))
568
      else:
569
        p_ids.append(disk.physical_id)
570

    
571
    if disk.children:
572
      for child in disk.children:
573
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
574
    return result
575

    
576
  def _UnlockedVerifyConfig(self):
577
    """Verify function.
578

579
    @rtype: list
580
    @return: a list of error messages; a non-empty list signifies
581
        configuration errors
582

583
    """
584
    # pylint: disable=R0914
585
    result = []
586
    seen_macs = []
587
    ports = {}
588
    data = self._config_data
589
    cluster = data.cluster
590
    seen_lids = []
591
    seen_pids = []
592

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

    
606
    if not cluster.enabled_disk_templates:
607
      result.append("enabled disk templates list doesn't have any entries")
608
    invalid_disk_templates = set(cluster.enabled_disk_templates) \
609
                               - constants.DISK_TEMPLATES
610
    if invalid_disk_templates:
611
      result.append("enabled disk templates list contains invalid entries:"
612
                    " %s" % utils.CommaJoin(invalid_disk_templates))
613

    
614
    if cluster.master_node not in data.nodes:
615
      result.append("cluster has invalid primary node '%s'" %
616
                    cluster.master_node)
617

    
618
    def _helper(owner, attr, value, template):
619
      try:
620
        utils.ForceDictType(value, template)
621
      except errors.GenericError, err:
622
        result.append("%s has invalid %s: %s" % (owner, attr, err))
623

    
624
    def _helper_nic(owner, params):
625
      try:
626
        objects.NIC.CheckParameterSyntax(params)
627
      except errors.ConfigurationError, err:
628
        result.append("%s has invalid nicparams: %s" % (owner, err))
629

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

    
653
    def _helper_ispecs(owner, parentkey, params):
654
      for (key, value) in params.items():
655
        fullkey = "/".join([parentkey, key])
656
        _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
657

    
658
    # check cluster parameters
659
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
660
            constants.BES_PARAMETER_TYPES)
661
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
662
            constants.NICS_PARAMETER_TYPES)
663
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
664
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
665
            constants.NDS_PARAMETER_TYPES)
666
    _helper_ipolicy("cluster", cluster.ipolicy, True)
667

    
668
    # per-instance checks
669
    for instance_name in data.instances:
670
      instance = data.instances[instance_name]
671
      if instance.name != instance_name:
672
        result.append("instance '%s' is indexed by wrong name '%s'" %
673
                      (instance.name, instance_name))
674
      if instance.primary_node not in data.nodes:
675
        result.append("instance '%s' has invalid primary node '%s'" %
676
                      (instance_name, instance.primary_node))
677
      for snode in instance.secondary_nodes:
678
        if snode not in data.nodes:
679
          result.append("instance '%s' has invalid secondary node '%s'" %
680
                        (instance_name, snode))
681
      for idx, nic in enumerate(instance.nics):
682
        if nic.mac in seen_macs:
683
          result.append("instance '%s' has NIC %d mac %s duplicate" %
684
                        (instance_name, idx, nic.mac))
685
        else:
686
          seen_macs.append(nic.mac)
687
        if nic.nicparams:
688
          filled = cluster.SimpleFillNIC(nic.nicparams)
689
          owner = "instance %s nic %d" % (instance.name, idx)
690
          _helper(owner, "nicparams",
691
                  filled, constants.NICS_PARAMETER_TYPES)
692
          _helper_nic(owner, filled)
693

    
694
      # disk template checks
695
      if not instance.disk_template in data.cluster.enabled_disk_templates:
696
        result.append("instance '%s' uses the disabled disk template '%s'." %
697
                      (instance_name, instance.disk_template))
698

    
699
      # parameter checks
700
      if instance.beparams:
701
        _helper("instance %s" % instance.name, "beparams",
702
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
703

    
704
      # gather the drbd ports for duplicate checks
705
      for (idx, dsk) in enumerate(instance.disks):
706
        if dsk.dev_type in constants.LDS_DRBD:
707
          tcp_port = dsk.logical_id[2]
708
          if tcp_port not in ports:
709
            ports[tcp_port] = []
710
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
711
      # gather network port reservation
712
      net_port = getattr(instance, "network_port", None)
713
      if net_port is not None:
714
        if net_port not in ports:
715
          ports[net_port] = []
716
        ports[net_port].append((instance.name, "network port"))
717

    
718
      # instance disk verify
719
      for idx, disk in enumerate(instance.disks):
720
        result.extend(["instance '%s' disk %d error: %s" %
721
                       (instance.name, idx, msg) for msg in disk.Verify()])
722
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
723

    
724
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
725
      if wrong_names:
726
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
727
                         (idx, exp_name, actual_name))
728
                        for (idx, exp_name, actual_name) in wrong_names)
729

    
730
        result.append("Instance '%s' has wrongly named disks: %s" %
731
                      (instance.name, tmp))
732

    
733
    # cluster-wide pool of free ports
734
    for free_port in cluster.tcpudp_port_pool:
735
      if free_port not in ports:
736
        ports[free_port] = []
737
      ports[free_port].append(("cluster", "port marked as free"))
738

    
739
    # compute tcp/udp duplicate ports
740
    keys = ports.keys()
741
    keys.sort()
742
    for pnum in keys:
743
      pdata = ports[pnum]
744
      if len(pdata) > 1:
745
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
746
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
747

    
748
    # highest used tcp port check
749
    if keys:
750
      if keys[-1] > cluster.highest_used_port:
751
        result.append("Highest used port mismatch, saved %s, computed %s" %
752
                      (cluster.highest_used_port, keys[-1]))
753

    
754
    if not data.nodes[cluster.master_node].master_candidate:
755
      result.append("Master node is not a master candidate")
756

    
757
    # master candidate checks
758
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
759
    if mc_now < mc_max:
760
      result.append("Not enough master candidates: actual %d, target %d" %
761
                    (mc_now, mc_max))
762

    
763
    # node checks
764
    for node_name, node in data.nodes.items():
765
      if node.name != node_name:
766
        result.append("Node '%s' is indexed by wrong name '%s'" %
767
                      (node.name, node_name))
768
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
769
        result.append("Node %s state is invalid: master_candidate=%s,"
770
                      " drain=%s, offline=%s" %
771
                      (node.name, node.master_candidate, node.drained,
772
                       node.offline))
773
      if node.group not in data.nodegroups:
774
        result.append("Node '%s' has invalid group '%s'" %
775
                      (node.name, node.group))
776
      else:
777
        _helper("node %s" % node.name, "ndparams",
778
                cluster.FillND(node, data.nodegroups[node.group]),
779
                constants.NDS_PARAMETER_TYPES)
780
      used_globals = constants.NDC_GLOBALS.intersection(node.ndparams)
781
      if used_globals:
782
        result.append("Node '%s' has some global parameters set: %s" %
783
                      (node.name, utils.CommaJoin(used_globals)))
784

    
785
    # nodegroups checks
786
    nodegroups_names = set()
787
    for nodegroup_uuid in data.nodegroups:
788
      nodegroup = data.nodegroups[nodegroup_uuid]
789
      if nodegroup.uuid != nodegroup_uuid:
790
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
791
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
792
      if utils.UUID_RE.match(nodegroup.name.lower()):
793
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
794
                      (nodegroup.name, nodegroup.uuid))
795
      if nodegroup.name in nodegroups_names:
796
        result.append("duplicate node group name '%s'" % nodegroup.name)
797
      else:
798
        nodegroups_names.add(nodegroup.name)
799
      group_name = "group %s" % nodegroup.name
800
      _helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy),
801
                      False)
802
      if nodegroup.ndparams:
803
        _helper(group_name, "ndparams",
804
                cluster.SimpleFillND(nodegroup.ndparams),
805
                constants.NDS_PARAMETER_TYPES)
806

    
807
    # drbd minors check
808
    _, duplicates = self._UnlockedComputeDRBDMap()
809
    for node, minor, instance_a, instance_b in duplicates:
810
      result.append("DRBD minor %d on node %s is assigned twice to instances"
811
                    " %s and %s" % (minor, node, instance_a, instance_b))
812

    
813
    # IP checks
814
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
815
    ips = {}
816

    
817
    def _AddIpAddress(ip, name):
818
      ips.setdefault(ip, []).append(name)
819

    
820
    _AddIpAddress(cluster.master_ip, "cluster_ip")
821

    
822
    for node in data.nodes.values():
823
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
824
      if node.secondary_ip != node.primary_ip:
825
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
826

    
827
    for instance in data.instances.values():
828
      for idx, nic in enumerate(instance.nics):
829
        if nic.ip is None:
830
          continue
831

    
832
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
833
        nic_mode = nicparams[constants.NIC_MODE]
834
        nic_link = nicparams[constants.NIC_LINK]
835

    
836
        if nic_mode == constants.NIC_MODE_BRIDGED:
837
          link = "bridge:%s" % nic_link
838
        elif nic_mode == constants.NIC_MODE_ROUTED:
839
          link = "route:%s" % nic_link
840
        else:
841
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
842

    
843
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
844
                      "instance:%s/nic:%d" % (instance.name, idx))
845

    
846
    for ip, owners in ips.items():
847
      if len(owners) > 1:
848
        result.append("IP address %s is used by multiple owners: %s" %
849
                      (ip, utils.CommaJoin(owners)))
850

    
851
    return result
852

    
853
  @locking.ssynchronized(_config_lock, shared=1)
854
  def VerifyConfig(self):
855
    """Verify function.
856

857
    This is just a wrapper over L{_UnlockedVerifyConfig}.
858

859
    @rtype: list
860
    @return: a list of error messages; a non-empty list signifies
861
        configuration errors
862

863
    """
864
    return self._UnlockedVerifyConfig()
865

    
866
  def _UnlockedSetDiskID(self, disk, node_name):
867
    """Convert the unique ID to the ID needed on the target nodes.
868

869
    This is used only for drbd, which needs ip/port configuration.
870

871
    The routine descends down and updates its children also, because
872
    this helps when the only the top device is passed to the remote
873
    node.
874

875
    This function is for internal use, when the config lock is already held.
876

877
    """
878
    if disk.children:
879
      for child in disk.children:
880
        self._UnlockedSetDiskID(child, node_name)
881

    
882
    if disk.logical_id is None and disk.physical_id is not None:
883
      return
884
    if disk.dev_type == constants.LD_DRBD8:
885
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
886
      if node_name not in (pnode, snode):
887
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
888
                                        node_name)
889
      pnode_info = self._UnlockedGetNodeInfo(pnode)
890
      snode_info = self._UnlockedGetNodeInfo(snode)
891
      if pnode_info is None or snode_info is None:
892
        raise errors.ConfigurationError("Can't find primary or secondary node"
893
                                        " for %s" % str(disk))
894
      p_data = (pnode_info.secondary_ip, port)
895
      s_data = (snode_info.secondary_ip, port)
896
      if pnode == node_name:
897
        disk.physical_id = p_data + s_data + (pminor, secret)
898
      else: # it must be secondary, we tested above
899
        disk.physical_id = s_data + p_data + (sminor, secret)
900
    else:
901
      disk.physical_id = disk.logical_id
902
    return
903

    
904
  @locking.ssynchronized(_config_lock)
905
  def SetDiskID(self, disk, node_name):
906
    """Convert the unique ID to the ID needed on the target nodes.
907

908
    This is used only for drbd, which needs ip/port configuration.
909

910
    The routine descends down and updates its children also, because
911
    this helps when the only the top device is passed to the remote
912
    node.
913

914
    """
915
    return self._UnlockedSetDiskID(disk, node_name)
916

    
917
  @locking.ssynchronized(_config_lock)
918
  def AddTcpUdpPort(self, port):
919
    """Adds a new port to the available port pool.
920

921
    @warning: this method does not "flush" the configuration (via
922
        L{_WriteConfig}); callers should do that themselves once the
923
        configuration is stable
924

925
    """
926
    if not isinstance(port, int):
927
      raise errors.ProgrammerError("Invalid type passed for port")
928

    
929
    self._config_data.cluster.tcpudp_port_pool.add(port)
930

    
931
  @locking.ssynchronized(_config_lock, shared=1)
932
  def GetPortList(self):
933
    """Returns a copy of the current port list.
934

935
    """
936
    return self._config_data.cluster.tcpudp_port_pool.copy()
937

    
938
  @locking.ssynchronized(_config_lock)
939
  def AllocatePort(self):
940
    """Allocate a port.
941

942
    The port will be taken from the available port pool or from the
943
    default port range (and in this case we increase
944
    highest_used_port).
945

946
    """
947
    # If there are TCP/IP ports configured, we use them first.
948
    if self._config_data.cluster.tcpudp_port_pool:
949
      port = self._config_data.cluster.tcpudp_port_pool.pop()
950
    else:
951
      port = self._config_data.cluster.highest_used_port + 1
952
      if port >= constants.LAST_DRBD_PORT:
953
        raise errors.ConfigurationError("The highest used port is greater"
954
                                        " than %s. Aborting." %
955
                                        constants.LAST_DRBD_PORT)
956
      self._config_data.cluster.highest_used_port = port
957

    
958
    self._WriteConfig()
959
    return port
960

    
961
  def _UnlockedComputeDRBDMap(self):
962
    """Compute the used DRBD minor/nodes.
963

964
    @rtype: (dict, list)
965
    @return: dictionary of node_name: dict of minor: instance_name;
966
        the returned dict will have all the nodes in it (even if with
967
        an empty list), and a list of duplicates; if the duplicates
968
        list is not empty, the configuration is corrupted and its caller
969
        should raise an exception
970

971
    """
972
    def _AppendUsedPorts(instance_name, disk, used):
973
      duplicates = []
974
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
975
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
976
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
977
          assert node in used, ("Node '%s' of instance '%s' not found"
978
                                " in node list" % (node, instance_name))
979
          if port in used[node]:
980
            duplicates.append((node, port, instance_name, used[node][port]))
981
          else:
982
            used[node][port] = instance_name
983
      if disk.children:
984
        for child in disk.children:
985
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
986
      return duplicates
987

    
988
    duplicates = []
989
    my_dict = dict((node, {}) for node in self._config_data.nodes)
990
    for instance in self._config_data.instances.itervalues():
991
      for disk in instance.disks:
992
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
993
    for (node, minor), instance in self._temporary_drbds.iteritems():
994
      if minor in my_dict[node] and my_dict[node][minor] != instance:
995
        duplicates.append((node, minor, instance, my_dict[node][minor]))
996
      else:
997
        my_dict[node][minor] = instance
998
    return my_dict, duplicates
999

    
1000
  @locking.ssynchronized(_config_lock)
1001
  def ComputeDRBDMap(self):
1002
    """Compute the used DRBD minor/nodes.
1003

1004
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
1005

1006
    @return: dictionary of node_name: dict of minor: instance_name;
1007
        the returned dict will have all the nodes in it (even if with
1008
        an empty list).
1009

1010
    """
1011
    d_map, duplicates = self._UnlockedComputeDRBDMap()
1012
    if duplicates:
1013
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
1014
                                      str(duplicates))
1015
    return d_map
1016

    
1017
  @locking.ssynchronized(_config_lock)
1018
  def AllocateDRBDMinor(self, nodes, instance):
1019
    """Allocate a drbd minor.
1020

1021
    The free minor will be automatically computed from the existing
1022
    devices. A node can be given multiple times in order to allocate
1023
    multiple minors. The result is the list of minors, in the same
1024
    order as the passed nodes.
1025

1026
    @type instance: string
1027
    @param instance: the instance for which we allocate minors
1028

1029
    """
1030
    assert isinstance(instance, basestring), \
1031
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
1032

    
1033
    d_map, duplicates = self._UnlockedComputeDRBDMap()
1034
    if duplicates:
1035
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
1036
                                      str(duplicates))
1037
    result = []
1038
    for nname in nodes:
1039
      ndata = d_map[nname]
1040
      if not ndata:
1041
        # no minors used, we can start at 0
1042
        result.append(0)
1043
        ndata[0] = instance
1044
        self._temporary_drbds[(nname, 0)] = instance
1045
        continue
1046
      keys = ndata.keys()
1047
      keys.sort()
1048
      ffree = utils.FirstFree(keys)
1049
      if ffree is None:
1050
        # return the next minor
1051
        # TODO: implement high-limit check
1052
        minor = keys[-1] + 1
1053
      else:
1054
        minor = ffree
1055
      # double-check minor against current instances
1056
      assert minor not in d_map[nname], \
1057
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
1058
              " already allocated to instance %s" %
1059
              (minor, nname, d_map[nname][minor]))
1060
      ndata[minor] = instance
1061
      # double-check minor against reservation
1062
      r_key = (nname, minor)
1063
      assert r_key not in self._temporary_drbds, \
1064
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
1065
              " reserved for instance %s" %
1066
              (minor, nname, self._temporary_drbds[r_key]))
1067
      self._temporary_drbds[r_key] = instance
1068
      result.append(minor)
1069
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
1070
                  nodes, result)
1071
    return result
1072

    
1073
  def _UnlockedReleaseDRBDMinors(self, instance):
1074
    """Release temporary drbd minors allocated for a given instance.
1075

1076
    @type instance: string
1077
    @param instance: the instance for which temporary minors should be
1078
                     released
1079

1080
    """
1081
    assert isinstance(instance, basestring), \
1082
           "Invalid argument passed to ReleaseDRBDMinors"
1083
    for key, name in self._temporary_drbds.items():
1084
      if name == instance:
1085
        del self._temporary_drbds[key]
1086

    
1087
  @locking.ssynchronized(_config_lock)
1088
  def ReleaseDRBDMinors(self, instance):
1089
    """Release temporary drbd minors allocated for a given instance.
1090

1091
    This should be called on the error paths, on the success paths
1092
    it's automatically called by the ConfigWriter add and update
1093
    functions.
1094

1095
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1096

1097
    @type instance: string
1098
    @param instance: the instance for which temporary minors should be
1099
                     released
1100

1101
    """
1102
    self._UnlockedReleaseDRBDMinors(instance)
1103

    
1104
  @locking.ssynchronized(_config_lock, shared=1)
1105
  def GetConfigVersion(self):
1106
    """Get the configuration version.
1107

1108
    @return: Config version
1109

1110
    """
1111
    return self._config_data.version
1112

    
1113
  @locking.ssynchronized(_config_lock, shared=1)
1114
  def GetClusterName(self):
1115
    """Get cluster name.
1116

1117
    @return: Cluster name
1118

1119
    """
1120
    return self._config_data.cluster.cluster_name
1121

    
1122
  @locking.ssynchronized(_config_lock, shared=1)
1123
  def GetMasterNode(self):
1124
    """Get the hostname of the master node for this cluster.
1125

1126
    @return: Master hostname
1127

1128
    """
1129
    return self._config_data.cluster.master_node
1130

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

1135
    @return: Master IP
1136

1137
    """
1138
    return self._config_data.cluster.master_ip
1139

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

1144
    """
1145
    return self._config_data.cluster.master_netdev
1146

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

1151
    """
1152
    return self._config_data.cluster.master_netmask
1153

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

1158
    """
1159
    return self._config_data.cluster.use_external_mip_script
1160

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

1165
    """
1166
    return self._config_data.cluster.file_storage_dir
1167

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

1172
    """
1173
    return self._config_data.cluster.shared_file_storage_dir
1174

    
1175
  @locking.ssynchronized(_config_lock, shared=1)
1176
  def GetHypervisorType(self):
1177
    """Get the hypervisor type for this cluster.
1178

1179
    """
1180
    return self._config_data.cluster.enabled_hypervisors[0]
1181

    
1182
  @locking.ssynchronized(_config_lock, shared=1)
1183
  def GetHostKey(self):
1184
    """Return the rsa hostkey from the config.
1185

1186
    @rtype: string
1187
    @return: the rsa hostkey
1188

1189
    """
1190
    return self._config_data.cluster.rsahostkeypub
1191

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

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

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

1203
    @return: primary ip family
1204

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

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

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

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

    
1222
    return result
1223

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1343
    return self._config_data.nodegroups[uuid]
1344

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1417
    self._EnsureUUID(instance, ec_id)
1418

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

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

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

1433
    """
1434
    if not item.uuid:
1435
      item.uuid = self._GenerateUniqueID(ec_id)
1436
    elif item.uuid in self._AllIDs(include_temporary=True):
1437
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1438
                                      " in use" % (item.name, item.uuid))
1439

    
1440
  def _SetInstanceStatus(self, instance_name, status):
1441
    """Set the instance's status to a given value.
1442

1443
    """
1444
    assert status in constants.ADMINST_ALL, \
1445
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1446

    
1447
    if instance_name not in self._config_data.instances:
1448
      raise errors.ConfigurationError("Unknown instance '%s'" %
1449
                                      instance_name)
1450
    instance = self._config_data.instances[instance_name]
1451
    if instance.admin_state != status:
1452
      instance.admin_state = status
1453
      instance.serial_no += 1
1454
      instance.mtime = time.time()
1455
      self._WriteConfig()
1456

    
1457
  @locking.ssynchronized(_config_lock)
1458
  def MarkInstanceUp(self, instance_name):
1459
    """Mark the instance status to up in the config.
1460

1461
    """
1462
    self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1463

    
1464
  @locking.ssynchronized(_config_lock)
1465
  def MarkInstanceOffline(self, instance_name):
1466
    """Mark the instance status to down in the config.
1467

1468
    """
1469
    self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1470

    
1471
  @locking.ssynchronized(_config_lock)
1472
  def RemoveInstance(self, instance_name):
1473
    """Remove the instance from the configuration.
1474

1475
    """
1476
    if instance_name not in self._config_data.instances:
1477
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1478

    
1479
    # If a network port has been allocated to the instance,
1480
    # return it to the pool of free ports.
1481
    inst = self._config_data.instances[instance_name]
1482
    network_port = getattr(inst, "network_port", None)
1483
    if network_port is not None:
1484
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1485

    
1486
    instance = self._UnlockedGetInstanceInfo(instance_name)
1487

    
1488
    for nic in instance.nics:
1489
      if nic.network and nic.ip:
1490
        # Return all IP addresses to the respective address pools
1491
        self._UnlockedCommitIp(constants.RELEASE_ACTION,
1492
                               nic.network, nic.ip, False)
1493

    
1494
    del self._config_data.instances[instance_name]
1495
    self._config_data.cluster.serial_no += 1
1496
    self._WriteConfig()
1497

    
1498
  @locking.ssynchronized(_config_lock)
1499
  def RenameInstance(self, old_name, new_name):
1500
    """Rename an instance.
1501

1502
    This needs to be done in ConfigWriter and not by RemoveInstance
1503
    combined with AddInstance as only we can guarantee an atomic
1504
    rename.
1505

1506
    """
1507
    if old_name not in self._config_data.instances:
1508
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1509

    
1510
    # Operate on a copy to not loose instance object in case of a failure
1511
    inst = self._config_data.instances[old_name].Copy()
1512
    inst.name = new_name
1513

    
1514
    for (idx, disk) in enumerate(inst.disks):
1515
      if disk.dev_type == constants.LD_FILE:
1516
        # rename the file paths in logical and physical id
1517
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1518
        disk.logical_id = (disk.logical_id[0],
1519
                           utils.PathJoin(file_storage_dir, inst.name,
1520
                                          "disk%s" % idx))
1521
        disk.physical_id = disk.logical_id
1522

    
1523
    # Actually replace instance object
1524
    del self._config_data.instances[old_name]
1525
    self._config_data.instances[inst.name] = inst
1526

    
1527
    # Force update of ssconf files
1528
    self._config_data.cluster.serial_no += 1
1529

    
1530
    self._WriteConfig()
1531

    
1532
  @locking.ssynchronized(_config_lock)
1533
  def MarkInstanceDown(self, instance_name):
1534
    """Mark the status of an instance to down in the configuration.
1535

1536
    """
1537
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1538

    
1539
  def _UnlockedGetInstanceList(self):
1540
    """Get the list of instances.
1541

1542
    This function is for internal use, when the config lock is already held.
1543

1544
    """
1545
    return self._config_data.instances.keys()
1546

    
1547
  @locking.ssynchronized(_config_lock, shared=1)
1548
  def GetInstanceList(self):
1549
    """Get the list of instances.
1550

1551
    @return: array of instances, ex. ['instance2.example.com',
1552
        'instance1.example.com']
1553

1554
    """
1555
    return self._UnlockedGetInstanceList()
1556

    
1557
  def ExpandInstanceName(self, short_name):
1558
    """Attempt to expand an incomplete instance name.
1559

1560
    """
1561
    # Locking is done in L{ConfigWriter.GetInstanceList}
1562
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1563

    
1564
  def _UnlockedGetInstanceInfo(self, instance_name):
1565
    """Returns information about an instance.
1566

1567
    This function is for internal use, when the config lock is already held.
1568

1569
    """
1570
    if instance_name not in self._config_data.instances:
1571
      return None
1572

    
1573
    return self._config_data.instances[instance_name]
1574

    
1575
  @locking.ssynchronized(_config_lock, shared=1)
1576
  def GetInstanceInfo(self, instance_name):
1577
    """Returns information about an instance.
1578

1579
    It takes the information from the configuration file. Other information of
1580
    an instance are taken from the live systems.
1581

1582
    @param instance_name: name of the instance, e.g.
1583
        I{instance1.example.com}
1584

1585
    @rtype: L{objects.Instance}
1586
    @return: the instance object
1587

1588
    """
1589
    return self._UnlockedGetInstanceInfo(instance_name)
1590

    
1591
  @locking.ssynchronized(_config_lock, shared=1)
1592
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1593
    """Returns set of node group UUIDs for instance's nodes.
1594

1595
    @rtype: frozenset
1596

1597
    """
1598
    instance = self._UnlockedGetInstanceInfo(instance_name)
1599
    if not instance:
1600
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1601

    
1602
    if primary_only:
1603
      nodes = [instance.primary_node]
1604
    else:
1605
      nodes = instance.all_nodes
1606

    
1607
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1608
                     for node_name in nodes)
1609

    
1610
  @locking.ssynchronized(_config_lock, shared=1)
1611
  def GetInstanceNetworks(self, instance_name):
1612
    """Returns set of network UUIDs for instance's nics.
1613

1614
    @rtype: frozenset
1615

1616
    """
1617
    instance = self._UnlockedGetInstanceInfo(instance_name)
1618
    if not instance:
1619
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1620

    
1621
    networks = set()
1622
    for nic in instance.nics:
1623
      if nic.network:
1624
        networks.add(nic.network)
1625

    
1626
    return frozenset(networks)
1627

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

1632
    @param instances: list of instance names
1633
    @rtype: list
1634
    @return: list of tuples (instance, instance_info), where
1635
        instance_info is what would GetInstanceInfo return for the
1636
        node, while keeping the original order
1637

1638
    """
1639
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1640

    
1641
  @locking.ssynchronized(_config_lock, shared=1)
1642
  def GetAllInstancesInfo(self):
1643
    """Get the configuration of all instances.
1644

1645
    @rtype: dict
1646
    @return: dict of (instance, instance_info), where instance_info is what
1647
              would GetInstanceInfo return for the node
1648

1649
    """
1650
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1651
                    for instance in self._UnlockedGetInstanceList()])
1652
    return my_dict
1653

    
1654
  @locking.ssynchronized(_config_lock, shared=1)
1655
  def GetInstancesInfoByFilter(self, filter_fn):
1656
    """Get instance configuration with a filter.
1657

1658
    @type filter_fn: callable
1659
    @param filter_fn: Filter function receiving instance object as parameter,
1660
      returning boolean. Important: this function is called while the
1661
      configuration locks is held. It must not do any complex work or call
1662
      functions potentially leading to a deadlock. Ideally it doesn't call any
1663
      other functions and just compares instance attributes.
1664

1665
    """
1666
    return dict((name, inst)
1667
                for (name, inst) in self._config_data.instances.items()
1668
                if filter_fn(inst))
1669

    
1670
  @locking.ssynchronized(_config_lock)
1671
  def AddNode(self, node, ec_id):
1672
    """Add a node to the configuration.
1673

1674
    @type node: L{objects.Node}
1675
    @param node: a Node instance
1676

1677
    """
1678
    logging.info("Adding node %s to configuration", node.name)
1679

    
1680
    self._EnsureUUID(node, ec_id)
1681

    
1682
    node.serial_no = 1
1683
    node.ctime = node.mtime = time.time()
1684
    self._UnlockedAddNodeToGroup(node.name, node.group)
1685
    self._config_data.nodes[node.name] = node
1686
    self._config_data.cluster.serial_no += 1
1687
    self._WriteConfig()
1688

    
1689
  @locking.ssynchronized(_config_lock)
1690
  def RemoveNode(self, node_name):
1691
    """Remove a node from the configuration.
1692

1693
    """
1694
    logging.info("Removing node %s from configuration", node_name)
1695

    
1696
    if node_name not in self._config_data.nodes:
1697
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1698

    
1699
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1700
    del self._config_data.nodes[node_name]
1701
    self._config_data.cluster.serial_no += 1
1702
    self._WriteConfig()
1703

    
1704
  def ExpandNodeName(self, short_name):
1705
    """Attempt to expand an incomplete node name.
1706

1707
    """
1708
    # Locking is done in L{ConfigWriter.GetNodeList}
1709
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1710

    
1711
  def _UnlockedGetNodeInfo(self, node_name):
1712
    """Get the configuration of a node, as stored in the config.
1713

1714
    This function is for internal use, when the config lock is already
1715
    held.
1716

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

1719
    @rtype: L{objects.Node}
1720
    @return: the node object
1721

1722
    """
1723
    if node_name not in self._config_data.nodes:
1724
      return None
1725

    
1726
    return self._config_data.nodes[node_name]
1727

    
1728
  @locking.ssynchronized(_config_lock, shared=1)
1729
  def GetNodeInfo(self, node_name):
1730
    """Get the configuration of a node, as stored in the config.
1731

1732
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1733

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

1736
    @rtype: L{objects.Node}
1737
    @return: the node object
1738

1739
    """
1740
    return self._UnlockedGetNodeInfo(node_name)
1741

    
1742
  @locking.ssynchronized(_config_lock, shared=1)
1743
  def GetNodeInstances(self, node_name):
1744
    """Get the instances of a node, as stored in the config.
1745

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

1748
    @rtype: (list, list)
1749
    @return: a tuple with two lists: the primary and the secondary instances
1750

1751
    """
1752
    pri = []
1753
    sec = []
1754
    for inst in self._config_data.instances.values():
1755
      if inst.primary_node == node_name:
1756
        pri.append(inst.name)
1757
      if node_name in inst.secondary_nodes:
1758
        sec.append(inst.name)
1759
    return (pri, sec)
1760

    
1761
  @locking.ssynchronized(_config_lock, shared=1)
1762
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1763
    """Get the instances of a node group.
1764

1765
    @param uuid: Node group UUID
1766
    @param primary_only: Whether to only consider primary nodes
1767
    @rtype: frozenset
1768
    @return: List of instance names in node group
1769

1770
    """
1771
    if primary_only:
1772
      nodes_fn = lambda inst: [inst.primary_node]
1773
    else:
1774
      nodes_fn = lambda inst: inst.all_nodes
1775

    
1776
    return frozenset(inst.name
1777
                     for inst in self._config_data.instances.values()
1778
                     for node_name in nodes_fn(inst)
1779
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1780

    
1781
  def _UnlockedGetNodeList(self):
1782
    """Return the list of nodes which are in the configuration.
1783

1784
    This function is for internal use, when the config lock is already
1785
    held.
1786

1787
    @rtype: list
1788

1789
    """
1790
    return self._config_data.nodes.keys()
1791

    
1792
  @locking.ssynchronized(_config_lock, shared=1)
1793
  def GetNodeList(self):
1794
    """Return the list of nodes which are in the configuration.
1795

1796
    """
1797
    return self._UnlockedGetNodeList()
1798

    
1799
  def _UnlockedGetOnlineNodeList(self):
1800
    """Return the list of nodes which are online.
1801

1802
    """
1803
    all_nodes = [self._UnlockedGetNodeInfo(node)
1804
                 for node in self._UnlockedGetNodeList()]
1805
    return [node.name for node in all_nodes if not node.offline]
1806

    
1807
  @locking.ssynchronized(_config_lock, shared=1)
1808
  def GetOnlineNodeList(self):
1809
    """Return the list of nodes which are online.
1810

1811
    """
1812
    return self._UnlockedGetOnlineNodeList()
1813

    
1814
  @locking.ssynchronized(_config_lock, shared=1)
1815
  def GetVmCapableNodeList(self):
1816
    """Return the list of nodes which are not vm capable.
1817

1818
    """
1819
    all_nodes = [self._UnlockedGetNodeInfo(node)
1820
                 for node in self._UnlockedGetNodeList()]
1821
    return [node.name for node in all_nodes if node.vm_capable]
1822

    
1823
  @locking.ssynchronized(_config_lock, shared=1)
1824
  def GetNonVmCapableNodeList(self):
1825
    """Return the list of nodes which are not vm capable.
1826

1827
    """
1828
    all_nodes = [self._UnlockedGetNodeInfo(node)
1829
                 for node in self._UnlockedGetNodeList()]
1830
    return [node.name for node in all_nodes if not node.vm_capable]
1831

    
1832
  @locking.ssynchronized(_config_lock, shared=1)
1833
  def GetMultiNodeInfo(self, nodes):
1834
    """Get the configuration of multiple nodes.
1835

1836
    @param nodes: list of node names
1837
    @rtype: list
1838
    @return: list of tuples of (node, node_info), where node_info is
1839
        what would GetNodeInfo return for the node, in the original
1840
        order
1841

1842
    """
1843
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1844

    
1845
  @locking.ssynchronized(_config_lock, shared=1)
1846
  def GetAllNodesInfo(self):
1847
    """Get the configuration of all nodes.
1848

1849
    @rtype: dict
1850
    @return: dict of (node, node_info), where node_info is what
1851
              would GetNodeInfo return for the node
1852

1853
    """
1854
    return self._UnlockedGetAllNodesInfo()
1855

    
1856
  def _UnlockedGetAllNodesInfo(self):
1857
    """Gets configuration of all nodes.
1858

1859
    @note: See L{GetAllNodesInfo}
1860

1861
    """
1862
    return dict([(node, self._UnlockedGetNodeInfo(node))
1863
                 for node in self._UnlockedGetNodeList()])
1864

    
1865
  @locking.ssynchronized(_config_lock, shared=1)
1866
  def GetNodeGroupsFromNodes(self, nodes):
1867
    """Returns groups for a list of nodes.
1868

1869
    @type nodes: list of string
1870
    @param nodes: List of node names
1871
    @rtype: frozenset
1872

1873
    """
1874
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1875

    
1876
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1877
    """Get the number of current and maximum desired and possible candidates.
1878

1879
    @type exceptions: list
1880
    @param exceptions: if passed, list of nodes that should be ignored
1881
    @rtype: tuple
1882
    @return: tuple of (current, desired and possible, possible)
1883

1884
    """
1885
    mc_now = mc_should = mc_max = 0
1886
    for node in self._config_data.nodes.values():
1887
      if exceptions and node.name in exceptions:
1888
        continue
1889
      if not (node.offline or node.drained) and node.master_capable:
1890
        mc_max += 1
1891
      if node.master_candidate:
1892
        mc_now += 1
1893
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1894
    return (mc_now, mc_should, mc_max)
1895

    
1896
  @locking.ssynchronized(_config_lock, shared=1)
1897
  def GetMasterCandidateStats(self, exceptions=None):
1898
    """Get the number of current and maximum possible candidates.
1899

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

1902
    @type exceptions: list
1903
    @param exceptions: if passed, list of nodes that should be ignored
1904
    @rtype: tuple
1905
    @return: tuple of (current, max)
1906

1907
    """
1908
    return self._UnlockedGetMasterCandidateStats(exceptions)
1909

    
1910
  @locking.ssynchronized(_config_lock)
1911
  def MaintainCandidatePool(self, exceptions):
1912
    """Try to grow the candidate pool to the desired size.
1913

1914
    @type exceptions: list
1915
    @param exceptions: if passed, list of nodes that should be ignored
1916
    @rtype: list
1917
    @return: list with the adjusted nodes (L{objects.Node} instances)
1918

1919
    """
1920
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1921
    mod_list = []
1922
    if mc_now < mc_max:
1923
      node_list = self._config_data.nodes.keys()
1924
      random.shuffle(node_list)
1925
      for name in node_list:
1926
        if mc_now >= mc_max:
1927
          break
1928
        node = self._config_data.nodes[name]
1929
        if (node.master_candidate or node.offline or node.drained or
1930
            node.name in exceptions or not node.master_capable):
1931
          continue
1932
        mod_list.append(node)
1933
        node.master_candidate = True
1934
        node.serial_no += 1
1935
        mc_now += 1
1936
      if mc_now != mc_max:
1937
        # this should not happen
1938
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1939
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1940
      if mod_list:
1941
        self._config_data.cluster.serial_no += 1
1942
        self._WriteConfig()
1943

    
1944
    return mod_list
1945

    
1946
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1947
    """Add a given node to the specified group.
1948

1949
    """
1950
    if nodegroup_uuid not in self._config_data.nodegroups:
1951
      # This can happen if a node group gets deleted between its lookup and
1952
      # when we're adding the first node to it, since we don't keep a lock in
1953
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1954
      # is not found anymore.
1955
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1956
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1957
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1958

    
1959
  def _UnlockedRemoveNodeFromGroup(self, node):
1960
    """Remove a given node from its group.
1961

1962
    """
1963
    nodegroup = node.group
1964
    if nodegroup not in self._config_data.nodegroups:
1965
      logging.warning("Warning: node '%s' has unknown node group '%s'"
1966
                      " (while being removed from it)", node.name, nodegroup)
1967
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1968
    if node.name not in nodegroup_obj.members:
1969
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
1970
                      " (while being removed from it)", node.name, nodegroup)
1971
    else:
1972
      nodegroup_obj.members.remove(node.name)
1973

    
1974
  @locking.ssynchronized(_config_lock)
1975
  def AssignGroupNodes(self, mods):
1976
    """Changes the group of a number of nodes.
1977

1978
    @type mods: list of tuples; (node name, new group UUID)
1979
    @param mods: Node membership modifications
1980

1981
    """
1982
    groups = self._config_data.nodegroups
1983
    nodes = self._config_data.nodes
1984

    
1985
    resmod = []
1986

    
1987
    # Try to resolve names/UUIDs first
1988
    for (node_name, new_group_uuid) in mods:
1989
      try:
1990
        node = nodes[node_name]
1991
      except KeyError:
1992
        raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1993

    
1994
      if node.group == new_group_uuid:
1995
        # Node is being assigned to its current group
1996
        logging.debug("Node '%s' was assigned to its current group (%s)",
1997
                      node_name, node.group)
1998
        continue
1999

    
2000
      # Try to find current group of node
2001
      try:
2002
        old_group = groups[node.group]
2003
      except KeyError:
2004
        raise errors.ConfigurationError("Unable to find old group '%s'" %
2005
                                        node.group)
2006

    
2007
      # Try to find new group for node
2008
      try:
2009
        new_group = groups[new_group_uuid]
2010
      except KeyError:
2011
        raise errors.ConfigurationError("Unable to find new group '%s'" %
2012
                                        new_group_uuid)
2013

    
2014
      assert node.name in old_group.members, \
2015
        ("Inconsistent configuration: node '%s' not listed in members for its"
2016
         " old group '%s'" % (node.name, old_group.uuid))
2017
      assert node.name not in new_group.members, \
2018
        ("Inconsistent configuration: node '%s' already listed in members for"
2019
         " its new group '%s'" % (node.name, new_group.uuid))
2020

    
2021
      resmod.append((node, old_group, new_group))
2022

    
2023
    # Apply changes
2024
    for (node, old_group, new_group) in resmod:
2025
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
2026
        "Assigning to current group is not possible"
2027

    
2028
      node.group = new_group.uuid
2029

    
2030
      # Update members of involved groups
2031
      if node.name in old_group.members:
2032
        old_group.members.remove(node.name)
2033
      if node.name not in new_group.members:
2034
        new_group.members.append(node.name)
2035

    
2036
    # Update timestamps and serials (only once per node/group object)
2037
    now = time.time()
2038
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
2039
      obj.serial_no += 1
2040
      obj.mtime = now
2041

    
2042
    # Force ssconf update
2043
    self._config_data.cluster.serial_no += 1
2044

    
2045
    self._WriteConfig()
2046

    
2047
  def _BumpSerialNo(self):
2048
    """Bump up the serial number of the config.
2049

2050
    """
2051
    self._config_data.serial_no += 1
2052
    self._config_data.mtime = time.time()
2053

    
2054
  def _AllUUIDObjects(self):
2055
    """Returns all objects with uuid attributes.
2056

2057
    """
2058
    return (self._config_data.instances.values() +
2059
            self._config_data.nodes.values() +
2060
            self._config_data.nodegroups.values() +
2061
            self._config_data.networks.values() +
2062
            self._AllDisks() +
2063
            self._AllNICs() +
2064
            [self._config_data.cluster])
2065

    
2066
  def _OpenConfig(self, accept_foreign):
2067
    """Read the config data from disk.
2068

2069
    """
2070
    raw_data = utils.ReadFile(self._cfg_file)
2071

    
2072
    try:
2073
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
2074
    except Exception, err:
2075
      raise errors.ConfigurationError(err)
2076

    
2077
    # Make sure the configuration has the right version
2078
    _ValidateConfig(data)
2079

    
2080
    if (not hasattr(data, "cluster") or
2081
        not hasattr(data.cluster, "rsahostkeypub")):
2082
      raise errors.ConfigurationError("Incomplete configuration"
2083
                                      " (missing cluster.rsahostkeypub)")
2084

    
2085
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
2086
      msg = ("The configuration denotes node %s as master, while my"
2087
             " hostname is %s; opening a foreign configuration is only"
2088
             " possible in accept_foreign mode" %
2089
             (data.cluster.master_node, self._my_hostname))
2090
      raise errors.ConfigurationError(msg)
2091

    
2092
    self._config_data = data
2093
    # reset the last serial as -1 so that the next write will cause
2094
    # ssconf update
2095
    self._last_cluster_serial = -1
2096

    
2097
    # Upgrade configuration if needed
2098
    self._UpgradeConfig()
2099

    
2100
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2101

    
2102
  def _UpgradeConfig(self):
2103
    """Run any upgrade steps.
2104

2105
    This method performs both in-object upgrades and also update some data
2106
    elements that need uniqueness across the whole configuration or interact
2107
    with other objects.
2108

2109
    @warning: this function will call L{_WriteConfig()}, but also
2110
        L{DropECReservations} so it needs to be called only from a
2111
        "safe" place (the constructor). If one wanted to call it with
2112
        the lock held, a DropECReservationUnlocked would need to be
2113
        created first, to avoid causing deadlock.
2114

2115
    """
2116
    # Keep a copy of the persistent part of _config_data to check for changes
2117
    # Serialization doesn't guarantee order in dictionaries
2118
    oldconf = copy.deepcopy(self._config_data.ToDict())
2119

    
2120
    # In-object upgrades
2121
    self._config_data.UpgradeConfig()
2122

    
2123
    for item in self._AllUUIDObjects():
2124
      if item.uuid is None:
2125
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
2126
    if not self._config_data.nodegroups:
2127
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
2128
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
2129
                                            members=[])
2130
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
2131
    for node in self._config_data.nodes.values():
2132
      if not node.group:
2133
        node.group = self.LookupNodeGroup(None)
2134
      # This is technically *not* an upgrade, but needs to be done both when
2135
      # nodegroups are being added, and upon normally loading the config,
2136
      # because the members list of a node group is discarded upon
2137
      # serializing/deserializing the object.
2138
      self._UnlockedAddNodeToGroup(node.name, node.group)
2139

    
2140
    modified = (oldconf != self._config_data.ToDict())
2141
    if modified:
2142
      self._WriteConfig()
2143
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
2144
      # only called at config init time, without the lock held
2145
      self.DropECReservations(_UPGRADE_CONFIG_JID)
2146
    else:
2147
      config_errors = self._UnlockedVerifyConfig()
2148
      if config_errors:
2149
        errmsg = ("Loaded configuration data is not consistent: %s" %
2150
                  (utils.CommaJoin(config_errors)))
2151
        logging.critical(errmsg)
2152

    
2153
  def _DistributeConfig(self, feedback_fn):
2154
    """Distribute the configuration to the other nodes.
2155

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

2159
    """
2160
    if self._offline:
2161
      return True
2162

    
2163
    bad = False
2164

    
2165
    node_list = []
2166
    addr_list = []
2167
    myhostname = self._my_hostname
2168
    # we can skip checking whether _UnlockedGetNodeInfo returns None
2169
    # since the node list comes from _UnlocketGetNodeList, and we are
2170
    # called with the lock held, so no modifications should take place
2171
    # in between
2172
    for node_name in self._UnlockedGetNodeList():
2173
      if node_name == myhostname:
2174
        continue
2175
      node_info = self._UnlockedGetNodeInfo(node_name)
2176
      if not node_info.master_candidate:
2177
        continue
2178
      node_list.append(node_info.name)
2179
      addr_list.append(node_info.primary_ip)
2180

    
2181
    # TODO: Use dedicated resolver talking to config writer for name resolution
2182
    result = \
2183
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2184
    for to_node, to_result in result.items():
2185
      msg = to_result.fail_msg
2186
      if msg:
2187
        msg = ("Copy of file %s to node %s failed: %s" %
2188
               (self._cfg_file, to_node, msg))
2189
        logging.error(msg)
2190

    
2191
        if feedback_fn:
2192
          feedback_fn(msg)
2193

    
2194
        bad = True
2195

    
2196
    return not bad
2197

    
2198
  def _WriteConfig(self, destination=None, feedback_fn=None):
2199
    """Write the configuration data to persistent storage.
2200

2201
    """
2202
    assert feedback_fn is None or callable(feedback_fn)
2203

    
2204
    # Warn on config errors, but don't abort the save - the
2205
    # configuration has already been modified, and we can't revert;
2206
    # the best we can do is to warn the user and save as is, leaving
2207
    # recovery to the user
2208
    config_errors = self._UnlockedVerifyConfig()
2209
    if config_errors:
2210
      errmsg = ("Configuration data is not consistent: %s" %
2211
                (utils.CommaJoin(config_errors)))
2212
      logging.critical(errmsg)
2213
      if feedback_fn:
2214
        feedback_fn(errmsg)
2215

    
2216
    if destination is None:
2217
      destination = self._cfg_file
2218
    self._BumpSerialNo()
2219
    txt = serializer.Dump(self._config_data.ToDict())
2220

    
2221
    getents = self._getents()
2222
    try:
2223
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2224
                               close=False, gid=getents.confd_gid, mode=0640)
2225
    except errors.LockError:
2226
      raise errors.ConfigurationError("The configuration file has been"
2227
                                      " modified since the last write, cannot"
2228
                                      " update")
2229
    try:
2230
      self._cfg_id = utils.GetFileID(fd=fd)
2231
    finally:
2232
      os.close(fd)
2233

    
2234
    self.write_count += 1
2235

    
2236
    # and redistribute the config file to master candidates
2237
    self._DistributeConfig(feedback_fn)
2238

    
2239
    # Write ssconf files on all nodes (including locally)
2240
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2241
      if not self._offline:
2242
        result = self._GetRpc(None).call_write_ssconf_files(
2243
          self._UnlockedGetOnlineNodeList(),
2244
          self._UnlockedGetSsconfValues())
2245

    
2246
        for nname, nresu in result.items():
2247
          msg = nresu.fail_msg
2248
          if msg:
2249
            errmsg = ("Error while uploading ssconf files to"
2250
                      " node %s: %s" % (nname, msg))
2251
            logging.warning(errmsg)
2252

    
2253
            if feedback_fn:
2254
              feedback_fn(errmsg)
2255

    
2256
      self._last_cluster_serial = self._config_data.cluster.serial_no
2257

    
2258
  def _UnlockedGetSsconfValues(self):
2259
    """Return the values needed by ssconf.
2260

2261
    @rtype: dict
2262
    @return: a dictionary with keys the ssconf names and values their
2263
        associated value
2264

2265
    """
2266
    fn = "\n".join
2267
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
2268
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
2269
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
2270
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2271
                    for ninfo in node_info]
2272
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2273
                    for ninfo in node_info]
2274

    
2275
    instance_data = fn(instance_names)
2276
    off_data = fn(node.name for node in node_info if node.offline)
2277
    on_data = fn(node.name for node in node_info if not node.offline)
2278
    mc_data = fn(node.name for node in node_info if node.master_candidate)
2279
    mc_ips_data = fn(node.primary_ip for node in node_info
2280
                     if node.master_candidate)
2281
    node_data = fn(node_names)
2282
    node_pri_ips_data = fn(node_pri_ips)
2283
    node_snd_ips_data = fn(node_snd_ips)
2284

    
2285
    cluster = self._config_data.cluster
2286
    cluster_tags = fn(cluster.GetTags())
2287

    
2288
    hypervisor_list = fn(cluster.enabled_hypervisors)
2289

    
2290
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2291

    
2292
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2293
                  self._config_data.nodegroups.values()]
2294
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2295
    networks = ["%s %s" % (net.uuid, net.name) for net in
2296
                self._config_data.networks.values()]
2297
    networks_data = fn(utils.NiceSort(networks))
2298

    
2299
    ssconf_values = {
2300
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
2301
      constants.SS_CLUSTER_TAGS: cluster_tags,
2302
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2303
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2304
      constants.SS_MASTER_CANDIDATES: mc_data,
2305
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2306
      constants.SS_MASTER_IP: cluster.master_ip,
2307
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
2308
      constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2309
      constants.SS_MASTER_NODE: cluster.master_node,
2310
      constants.SS_NODE_LIST: node_data,
2311
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2312
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2313
      constants.SS_OFFLINE_NODES: off_data,
2314
      constants.SS_ONLINE_NODES: on_data,
2315
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2316
      constants.SS_INSTANCE_LIST: instance_data,
2317
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2318
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
2319
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2320
      constants.SS_UID_POOL: uid_pool,
2321
      constants.SS_NODEGROUPS: nodegroups_data,
2322
      constants.SS_NETWORKS: networks_data,
2323
      }
2324
    bad_values = [(k, v) for k, v in ssconf_values.items()
2325
                  if not isinstance(v, (str, basestring))]
2326
    if bad_values:
2327
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2328
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2329
                                      " values: %s" % err)
2330
    return ssconf_values
2331

    
2332
  @locking.ssynchronized(_config_lock, shared=1)
2333
  def GetSsconfValues(self):
2334
    """Wrapper using lock around _UnlockedGetSsconf().
2335

2336
    """
2337
    return self._UnlockedGetSsconfValues()
2338

    
2339
  @locking.ssynchronized(_config_lock, shared=1)
2340
  def GetVGName(self):
2341
    """Return the volume group name.
2342

2343
    """
2344
    return self._config_data.cluster.volume_group_name
2345

    
2346
  @locking.ssynchronized(_config_lock)
2347
  def SetVGName(self, vg_name):
2348
    """Set the volume group name.
2349

2350
    """
2351
    self._config_data.cluster.volume_group_name = vg_name
2352
    self._config_data.cluster.serial_no += 1
2353
    self._WriteConfig()
2354

    
2355
  @locking.ssynchronized(_config_lock, shared=1)
2356
  def GetDRBDHelper(self):
2357
    """Return DRBD usermode helper.
2358

2359
    """
2360
    return self._config_data.cluster.drbd_usermode_helper
2361

    
2362
  @locking.ssynchronized(_config_lock)
2363
  def SetDRBDHelper(self, drbd_helper):
2364
    """Set DRBD usermode helper.
2365

2366
    """
2367
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2368
    self._config_data.cluster.serial_no += 1
2369
    self._WriteConfig()
2370

    
2371
  @locking.ssynchronized(_config_lock, shared=1)
2372
  def GetMACPrefix(self):
2373
    """Return the mac prefix.
2374

2375
    """
2376
    return self._config_data.cluster.mac_prefix
2377

    
2378
  @locking.ssynchronized(_config_lock, shared=1)
2379
  def GetClusterInfo(self):
2380
    """Returns information about the cluster
2381

2382
    @rtype: L{objects.Cluster}
2383
    @return: the cluster object
2384

2385
    """
2386
    return self._config_data.cluster
2387

    
2388
  @locking.ssynchronized(_config_lock, shared=1)
2389
  def HasAnyDiskOfType(self, dev_type):
2390
    """Check if in there is at disk of the given type in the configuration.
2391

2392
    """
2393
    return self._config_data.HasAnyDiskOfType(dev_type)
2394

    
2395
  @locking.ssynchronized(_config_lock)
2396
  def Update(self, target, feedback_fn, ec_id=None):
2397
    """Notify function to be called after updates.
2398

2399
    This function must be called when an object (as returned by
2400
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2401
    caller wants the modifications saved to the backing store. Note
2402
    that all modified objects will be saved, but the target argument
2403
    is the one the caller wants to ensure that it's saved.
2404

2405
    @param target: an instance of either L{objects.Cluster},
2406
        L{objects.Node} or L{objects.Instance} which is existing in
2407
        the cluster
2408
    @param feedback_fn: Callable feedback function
2409

2410
    """
2411
    if self._config_data is None:
2412
      raise errors.ProgrammerError("Configuration file not read,"
2413
                                   " cannot save.")
2414
    update_serial = False
2415
    if isinstance(target, objects.Cluster):
2416
      test = target == self._config_data.cluster
2417
    elif isinstance(target, objects.Node):
2418
      test = target in self._config_data.nodes.values()
2419
      update_serial = True
2420
    elif isinstance(target, objects.Instance):
2421
      test = target in self._config_data.instances.values()
2422
    elif isinstance(target, objects.NodeGroup):
2423
      test = target in self._config_data.nodegroups.values()
2424
    elif isinstance(target, objects.Network):
2425
      test = target in self._config_data.networks.values()
2426
    else:
2427
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2428
                                   " ConfigWriter.Update" % type(target))
2429
    if not test:
2430
      raise errors.ConfigurationError("Configuration updated since object"
2431
                                      " has been read or unknown object")
2432
    target.serial_no += 1
2433
    target.mtime = now = time.time()
2434

    
2435
    if update_serial:
2436
      # for node updates, we need to increase the cluster serial too
2437
      self._config_data.cluster.serial_no += 1
2438
      self._config_data.cluster.mtime = now
2439

    
2440
    if isinstance(target, objects.Instance):
2441
      self._UnlockedReleaseDRBDMinors(target.name)
2442

    
2443
    self._UnlockedCommitTemporaryIps(ec_id)
2444

    
2445
    self._WriteConfig(feedback_fn=feedback_fn)
2446

    
2447
  @locking.ssynchronized(_config_lock)
2448
  def DropECReservations(self, ec_id):
2449
    """Drop per-execution-context reservations
2450

2451
    """
2452
    for rm in self._all_rms:
2453
      rm.DropECReservations(ec_id)
2454

    
2455
  @locking.ssynchronized(_config_lock, shared=1)
2456
  def GetAllNetworksInfo(self):
2457
    """Get configuration info of all the networks.
2458

2459
    """
2460
    return dict(self._config_data.networks)
2461

    
2462
  def _UnlockedGetNetworkList(self):
2463
    """Get the list of networks.
2464

2465
    This function is for internal use, when the config lock is already held.
2466

2467
    """
2468
    return self._config_data.networks.keys()
2469

    
2470
  @locking.ssynchronized(_config_lock, shared=1)
2471
  def GetNetworkList(self):
2472
    """Get the list of networks.
2473

2474
    @return: array of networks, ex. ["main", "vlan100", "200]
2475

2476
    """
2477
    return self._UnlockedGetNetworkList()
2478

    
2479
  @locking.ssynchronized(_config_lock, shared=1)
2480
  def GetNetworkNames(self):
2481
    """Get a list of network names
2482

2483
    """
2484
    names = [net.name
2485
             for net in self._config_data.networks.values()]
2486
    return names
2487

    
2488
  def _UnlockedGetNetwork(self, uuid):
2489
    """Returns information about a network.
2490

2491
    This function is for internal use, when the config lock is already held.
2492

2493
    """
2494
    if uuid not in self._config_data.networks:
2495
      return None
2496

    
2497
    return self._config_data.networks[uuid]
2498

    
2499
  @locking.ssynchronized(_config_lock, shared=1)
2500
  def GetNetwork(self, uuid):
2501
    """Returns information about a network.
2502

2503
    It takes the information from the configuration file.
2504

2505
    @param uuid: UUID of the network
2506

2507
    @rtype: L{objects.Network}
2508
    @return: the network object
2509

2510
    """
2511
    return self._UnlockedGetNetwork(uuid)
2512

    
2513
  @locking.ssynchronized(_config_lock)
2514
  def AddNetwork(self, net, ec_id, check_uuid=True):
2515
    """Add a network to the configuration.
2516

2517
    @type net: L{objects.Network}
2518
    @param net: the Network object to add
2519
    @type ec_id: string
2520
    @param ec_id: unique id for the job to use when creating a missing UUID
2521

2522
    """
2523
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2524
    self._WriteConfig()
2525

    
2526
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2527
    """Add a network to the configuration.
2528

2529
    """
2530
    logging.info("Adding network %s to configuration", net.name)
2531

    
2532
    if check_uuid:
2533
      self._EnsureUUID(net, ec_id)
2534

    
2535
    net.serial_no = 1
2536
    self._config_data.networks[net.uuid] = net
2537
    self._config_data.cluster.serial_no += 1
2538

    
2539
  def _UnlockedLookupNetwork(self, target):
2540
    """Lookup a network's UUID.
2541

2542
    @type target: string
2543
    @param target: network name or UUID
2544
    @rtype: string
2545
    @return: network UUID
2546
    @raises errors.OpPrereqError: when the target network cannot be found
2547

2548
    """
2549
    if target is None:
2550
      return None
2551
    if target in self._config_data.networks:
2552
      return target
2553
    for net in self._config_data.networks.values():
2554
      if net.name == target:
2555
        return net.uuid
2556
    raise errors.OpPrereqError("Network '%s' not found" % target,
2557
                               errors.ECODE_NOENT)
2558

    
2559
  @locking.ssynchronized(_config_lock, shared=1)
2560
  def LookupNetwork(self, target):
2561
    """Lookup a network's UUID.
2562

2563
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2564

2565
    @type target: string
2566
    @param target: network name or UUID
2567
    @rtype: string
2568
    @return: network UUID
2569

2570
    """
2571
    return self._UnlockedLookupNetwork(target)
2572

    
2573
  @locking.ssynchronized(_config_lock)
2574
  def RemoveNetwork(self, network_uuid):
2575
    """Remove a network from the configuration.
2576

2577
    @type network_uuid: string
2578
    @param network_uuid: the UUID of the network to remove
2579

2580
    """
2581
    logging.info("Removing network %s from configuration", network_uuid)
2582

    
2583
    if network_uuid not in self._config_data.networks:
2584
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2585

    
2586
    del self._config_data.networks[network_uuid]
2587
    self._config_data.cluster.serial_no += 1
2588
    self._WriteConfig()
2589

    
2590
  def _UnlockedGetGroupNetParams(self, net_uuid, node):
2591
    """Get the netparams (mode, link) of a network.
2592

2593
    Get a network's netparams for a given node.
2594

2595
    @type net_uuid: string
2596
    @param net_uuid: network uuid
2597
    @type node: string
2598
    @param node: node name
2599
    @rtype: dict or None
2600
    @return: netparams
2601

2602
    """
2603
    node_info = self._UnlockedGetNodeInfo(node)
2604
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2605
    netparams = nodegroup_info.networks.get(net_uuid, None)
2606

    
2607
    return netparams
2608

    
2609
  @locking.ssynchronized(_config_lock, shared=1)
2610
  def GetGroupNetParams(self, net_uuid, node):
2611
    """Locking wrapper of _UnlockedGetGroupNetParams()
2612

2613
    """
2614
    return self._UnlockedGetGroupNetParams(net_uuid, node)
2615

    
2616
  @locking.ssynchronized(_config_lock, shared=1)
2617
  def CheckIPInNodeGroup(self, ip, node):
2618
    """Check IP uniqueness in nodegroup.
2619

2620
    Check networks that are connected in the node's node group
2621
    if ip is contained in any of them. Used when creating/adding
2622
    a NIC to ensure uniqueness among nodegroups.
2623

2624
    @type ip: string
2625
    @param ip: ip address
2626
    @type node: string
2627
    @param node: node name
2628
    @rtype: (string, dict) or (None, None)
2629
    @return: (network name, netparams)
2630

2631
    """
2632
    if ip is None:
2633
      return (None, None)
2634
    node_info = self._UnlockedGetNodeInfo(node)
2635
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2636
    for net_uuid in nodegroup_info.networks.keys():
2637
      net_info = self._UnlockedGetNetwork(net_uuid)
2638
      pool = network.AddressPool(net_info)
2639
      if pool.Contains(ip):
2640
        return (net_info.name, nodegroup_info.networks[net_uuid])
2641

    
2642
    return (None, None)