Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 41044e04

History | View | Annotate | Download (86.8 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 in self._temporary_ips.GetECReserved(ec_id):
334
      self._UnlockedCommitIp(action, net_uuid, address)
335

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

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

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

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

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

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

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

363
    This is just a wrapper around _UnlockedReleaseIp.
364

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

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

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

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

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

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

390
    """
391
    nobj = self._UnlockedGetNetwork(net_uuid)
392
    pool = network.AddressPool(nobj)
393
    try:
394
      isreserved = pool.IsReserved(address)
395
    except errors.AddressPoolError:
396
      raise errors.ReservationError("IP address not in network")
397
    if isreserved:
398
      raise errors.ReservationError("IP address already in use")
399

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

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

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

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

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

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

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

430
    This checks the current disks for duplicates.
431

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
521
    return result
522

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

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

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

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

    
543
    return result
544

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
850
    return result
851

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
957
    self._WriteConfig()
958
    return port
959

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1107
    @return: Config version
1108

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

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

1116
    @return: Cluster name
1117

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

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

1125
    @return: Master hostname
1126

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

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

1134
    @return: Master IP
1135

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1202
    @return: primary ip family
1203

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

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

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

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

    
1221
    return result
1222

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1342
    return self._config_data.nodegroups[uuid]
1343

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1416
    self._EnsureUUID(instance, ec_id)
1417

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1485
    instance = self._UnlockedGetInstanceInfo(instance_name)
1486

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

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

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

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

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

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

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

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

    
1525
    # Force update of ssconf files
1526
    self._config_data.cluster.serial_no += 1
1527

    
1528
    self._WriteConfig()
1529

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

1534
    """
1535
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1536

    
1537
  def _UnlockedGetInstanceList(self):
1538
    """Get the list of instances.
1539

1540
    This function is for internal use, when the config lock is already held.
1541

1542
    """
1543
    return self._config_data.instances.keys()
1544

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

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

1552
    """
1553
    return self._UnlockedGetInstanceList()
1554

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

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

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

1565
    This function is for internal use, when the config lock is already held.
1566

1567
    """
1568
    if instance_name not in self._config_data.instances:
1569
      return None
1570

    
1571
    return self._config_data.instances[instance_name]
1572

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

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

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

1583
    @rtype: L{objects.Instance}
1584
    @return: the instance object
1585

1586
    """
1587
    return self._UnlockedGetInstanceInfo(instance_name)
1588

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

1593
    @rtype: frozenset
1594

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

    
1600
    if primary_only:
1601
      nodes = [instance.primary_node]
1602
    else:
1603
      nodes = instance.all_nodes
1604

    
1605
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1606
                     for node_name in nodes)
1607

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

1612
    @rtype: frozenset
1613

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

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

    
1624
    return frozenset(networks)
1625

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

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

1636
    """
1637
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1638

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

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

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

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

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

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

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

1672
    @type node: L{objects.Node}
1673
    @param node: a Node instance
1674

1675
    """
1676
    logging.info("Adding node %s to configuration", node.name)
1677

    
1678
    self._EnsureUUID(node, ec_id)
1679

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

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

1691
    """
1692
    logging.info("Removing node %s from configuration", node_name)
1693

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

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

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

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

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

1712
    This function is for internal use, when the config lock is already
1713
    held.
1714

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

1717
    @rtype: L{objects.Node}
1718
    @return: the node object
1719

1720
    """
1721
    if node_name not in self._config_data.nodes:
1722
      return None
1723

    
1724
    return self._config_data.nodes[node_name]
1725

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

1730
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1731

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

1734
    @rtype: L{objects.Node}
1735
    @return: the node object
1736

1737
    """
1738
    return self._UnlockedGetNodeInfo(node_name)
1739

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

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

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

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

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

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

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

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

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

1782
    This function is for internal use, when the config lock is already
1783
    held.
1784

1785
    @rtype: list
1786

1787
    """
1788
    return self._config_data.nodes.keys()
1789

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

1794
    """
1795
    return self._UnlockedGetNodeList()
1796

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

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

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

1809
    """
1810
    return self._UnlockedGetOnlineNodeList()
1811

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

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

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

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

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

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

1840
    """
1841
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1842

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

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

1851
    """
1852
    return self._UnlockedGetAllNodesInfo()
1853

    
1854
  def _UnlockedGetAllNodesInfo(self):
1855
    """Gets configuration of all nodes.
1856

1857
    @note: See L{GetAllNodesInfo}
1858

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

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

1867
    @type nodes: list of string
1868
    @param nodes: List of node names
1869
    @rtype: frozenset
1870

1871
    """
1872
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1873

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

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

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

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

1898
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1899

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

1905
    """
1906
    return self._UnlockedGetMasterCandidateStats(exceptions)
1907

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

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

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

    
1942
    return mod_list
1943

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

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

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

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

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

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

1979
    """
1980
    groups = self._config_data.nodegroups
1981
    nodes = self._config_data.nodes
1982

    
1983
    resmod = []
1984

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

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

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

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

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

    
2019
      resmod.append((node, old_group, new_group))
2020

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

    
2026
      node.group = new_group.uuid
2027

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

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

    
2040
    # Force ssconf update
2041
    self._config_data.cluster.serial_no += 1
2042

    
2043
    self._WriteConfig()
2044

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

2048
    """
2049
    self._config_data.serial_no += 1
2050
    self._config_data.mtime = time.time()
2051

    
2052
  def _AllUUIDObjects(self):
2053
    """Returns all objects with uuid attributes.
2054

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

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

2067
    """
2068
    raw_data = utils.ReadFile(self._cfg_file)
2069

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

    
2075
    # Make sure the configuration has the right version
2076
    _ValidateConfig(data)
2077

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

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

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

    
2095
    # Upgrade configuration if needed
2096
    self._UpgradeConfig()
2097

    
2098
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2099

    
2100
  def _UpgradeConfig(self):
2101
    """Run any upgrade steps.
2102

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

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

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

    
2118
    # In-object upgrades
2119
    self._config_data.UpgradeConfig()
2120

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

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

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

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

2157
    """
2158
    if self._offline:
2159
      return True
2160

    
2161
    bad = False
2162

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

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

    
2189
        if feedback_fn:
2190
          feedback_fn(msg)
2191

    
2192
        bad = True
2193

    
2194
    return not bad
2195

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

2199
    """
2200
    assert feedback_fn is None or callable(feedback_fn)
2201

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

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

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

    
2232
    self.write_count += 1
2233

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

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

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

    
2251
            if feedback_fn:
2252
              feedback_fn(errmsg)
2253

    
2254
      self._last_cluster_serial = self._config_data.cluster.serial_no
2255

    
2256
  def _UnlockedGetSsconfValues(self):
2257
    """Return the values needed by ssconf.
2258

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

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

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

    
2283
    cluster = self._config_data.cluster
2284
    cluster_tags = fn(cluster.GetTags())
2285

    
2286
    hypervisor_list = fn(cluster.enabled_hypervisors)
2287

    
2288
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2289

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

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

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

2334
    """
2335
    return self._UnlockedGetSsconfValues()
2336

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

2341
    """
2342
    return self._config_data.cluster.volume_group_name
2343

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

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

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

2357
    """
2358
    return self._config_data.cluster.drbd_usermode_helper
2359

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

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

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

2373
    """
2374
    return self._config_data.cluster.mac_prefix
2375

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

2380
    @rtype: L{objects.Cluster}
2381
    @return: the cluster object
2382

2383
    """
2384
    return self._config_data.cluster
2385

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

2390
    """
2391
    return self._config_data.HasAnyDiskOfType(dev_type)
2392

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

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

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

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

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

    
2438
    if isinstance(target, objects.Instance):
2439
      self._UnlockedReleaseDRBDMinors(target.name)
2440

    
2441
    if ec_id is not None:
2442
      # Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
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)