Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 33ca83e9

History | View | Annotate | Download (85 kB)

1
#
2
#
3

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

    
21

    
22
"""Configuration management for Ganeti
23

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

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

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

32
"""
33

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

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

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

    
56

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

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

    
62

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

66
  This only verifies the version of the configuration.
67

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

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

    
75

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

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

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

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

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

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

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

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

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

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

125
    """
126
    assert callable(generate_one_fn)
127

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

    
141

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

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

    
148

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

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

158
  """
159
  result = []
160

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

    
166
  return result
167

    
168

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

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

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

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

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

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

215
    """
216
    self._context = context
217

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
284
    return prefix
285

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

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

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

    
302
    return GenMac
303

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

308
    This should check the current instances for duplicates.
309

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

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

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

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

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

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

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

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

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

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

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

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

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

364
    This is just a wrapper around _UnlockedReleaseIp.
365

366
    """
367
    net_uuid = self._UnlockedLookupNetwork(net)
368
    if net_uuid:
369
      self._UnlockedReleaseIp(net_uuid, address, ec_id)
370

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

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

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

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

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

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

    
403
    return self._temporary_ips.Reserve(ec_id,
404
                                       (constants.RESERVE_ACTION,
405
                                        address, net_uuid))
406

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

411
    """
412
    net_uuid = self._UnlockedLookupNetwork(net)
413
    if net_uuid:
414
      return self._UnlockedReserveIp(net_uuid, address, ec_id)
415

    
416
  @locking.ssynchronized(_config_lock)
417
  def UpdateDeviceUniqueIdx(self, instance, dev_type):
418

    
419
    instance.dev_idxs[dev_type] += 1
420
    self._WriteConfig()
421

    
422
  @locking.ssynchronized(_config_lock, shared=1)
423
  def ReserveLV(self, lv_name, ec_id):
424
    """Reserve an VG/LV pair for an instance.
425

426
    @type lv_name: string
427
    @param lv_name: the logical volume name to reserve
428

429
    """
430
    all_lvs = self._AllLVs()
431
    if lv_name in all_lvs:
432
      raise errors.ReservationError("LV already in use")
433
    else:
434
      self._temporary_lvs.Reserve(ec_id, lv_name)
435

    
436
  @locking.ssynchronized(_config_lock, shared=1)
437
  def GenerateDRBDSecret(self, ec_id):
438
    """Generate a DRBD secret.
439

440
    This checks the current disks for duplicates.
441

442
    """
443
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
444
                                            utils.GenerateSecret,
445
                                            ec_id)
446

    
447
  def _AllLVs(self):
448
    """Compute the list of all LVs.
449

450
    """
451
    lvnames = set()
452
    for instance in self._config_data.instances.values():
453
      node_data = instance.MapLVsByNode()
454
      for lv_list in node_data.values():
455
        lvnames.update(lv_list)
456
    return lvnames
457

    
458
  def _AllIDs(self, include_temporary):
459
    """Compute the list of all UUIDs and names we have.
460

461
    @type include_temporary: boolean
462
    @param include_temporary: whether to include the _temporary_ids set
463
    @rtype: set
464
    @return: a set of IDs
465

466
    """
467
    existing = set()
468
    if include_temporary:
469
      existing.update(self._temporary_ids.GetReserved())
470
    existing.update(self._AllLVs())
471
    existing.update(self._config_data.instances.keys())
472
    existing.update(self._config_data.nodes.keys())
473
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
474
    return existing
475

    
476
  def _GenerateUniqueID(self, ec_id):
477
    """Generate an unique UUID.
478

479
    This checks the current node, instances and disk names for
480
    duplicates.
481

482
    @rtype: string
483
    @return: the unique id
484

485
    """
486
    existing = self._AllIDs(include_temporary=False)
487
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
488

    
489
  @locking.ssynchronized(_config_lock, shared=1)
490
  def GenerateUniqueID(self, ec_id):
491
    """Generate an unique ID.
492

493
    This is just a wrapper over the unlocked version.
494

495
    @type ec_id: string
496
    @param ec_id: unique id for the job to reserve the id to
497

498
    """
499
    return self._GenerateUniqueID(ec_id)
500

    
501
  def _AllMACs(self):
502
    """Return all MACs present in the config.
503

504
    @rtype: list
505
    @return: the list of all MACs
506

507
    """
508
    result = []
509
    for instance in self._config_data.instances.values():
510
      for nic in instance.nics:
511
        result.append(nic.mac)
512

    
513
    return result
514

    
515
  def _AllDRBDSecrets(self):
516
    """Return all DRBD secrets present in the config.
517

518
    @rtype: list
519
    @return: the list of all DRBD secrets
520

521
    """
522
    def helper(disk, result):
523
      """Recursively gather secrets from this disk."""
524
      if disk.dev_type == constants.DT_DRBD8:
525
        result.append(disk.logical_id[5])
526
      if disk.children:
527
        for child in disk.children:
528
          helper(child, result)
529

    
530
    result = []
531
    for instance in self._config_data.instances.values():
532
      for disk in instance.disks:
533
        helper(disk, result)
534

    
535
    return result
536

    
537
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
538
    """Compute duplicate disk IDs
539

540
    @type disk: L{objects.Disk}
541
    @param disk: the disk at which to start searching
542
    @type l_ids: list
543
    @param l_ids: list of current logical ids
544
    @type p_ids: list
545
    @param p_ids: list of current physical ids
546
    @rtype: list
547
    @return: a list of error messages
548

549
    """
550
    result = []
551
    if disk.logical_id is not None:
552
      if disk.logical_id in l_ids:
553
        result.append("duplicate logical id %s" % str(disk.logical_id))
554
      else:
555
        l_ids.append(disk.logical_id)
556
    if disk.physical_id is not None:
557
      if disk.physical_id in p_ids:
558
        result.append("duplicate physical id %s" % str(disk.physical_id))
559
      else:
560
        p_ids.append(disk.physical_id)
561

    
562
    if disk.children:
563
      for child in disk.children:
564
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
565
    return result
566

    
567
  def _UnlockedVerifyConfig(self):
568
    """Verify function.
569

570
    @rtype: list
571
    @return: a list of error messages; a non-empty list signifies
572
        configuration errors
573

574
    """
575
    # pylint: disable=R0914
576
    result = []
577
    seen_macs = []
578
    ports = {}
579
    data = self._config_data
580
    cluster = data.cluster
581
    seen_lids = []
582
    seen_pids = []
583

    
584
    # global cluster checks
585
    if not cluster.enabled_hypervisors:
586
      result.append("enabled hypervisors list doesn't have any entries")
587
    invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
588
    if invalid_hvs:
589
      result.append("enabled hypervisors contains invalid entries: %s" %
590
                    invalid_hvs)
591
    missing_hvp = (set(cluster.enabled_hypervisors) -
592
                   set(cluster.hvparams.keys()))
593
    if missing_hvp:
594
      result.append("hypervisor parameters missing for the enabled"
595
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
596

    
597
    if cluster.master_node not in data.nodes:
598
      result.append("cluster has invalid primary node '%s'" %
599
                    cluster.master_node)
600

    
601
    def _helper(owner, attr, value, template):
602
      try:
603
        utils.ForceDictType(value, template)
604
      except errors.GenericError, err:
605
        result.append("%s has invalid %s: %s" % (owner, attr, err))
606

    
607
    def _helper_nic(owner, params):
608
      try:
609
        objects.NIC.CheckParameterSyntax(params)
610
      except errors.ConfigurationError, err:
611
        result.append("%s has invalid nicparams: %s" % (owner, err))
612

    
613
    def _helper_ipolicy(owner, params, check_std):
614
      try:
615
        objects.InstancePolicy.CheckParameterSyntax(params, check_std)
616
      except errors.ConfigurationError, err:
617
        result.append("%s has invalid instance policy: %s" % (owner, err))
618

    
619
    def _helper_ispecs(owner, params):
620
      for key, value in params.items():
621
        if key in constants.IPOLICY_ISPECS:
622
          fullkey = "ipolicy/" + key
623
          _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
624
        else:
625
          # FIXME: assuming list type
626
          if key in constants.IPOLICY_PARAMETERS:
627
            exp_type = float
628
          else:
629
            exp_type = list
630
          if not isinstance(value, exp_type):
631
            result.append("%s has invalid instance policy: for %s,"
632
                          " expecting %s, got %s" %
633
                          (owner, key, exp_type.__name__, type(value)))
634

    
635
    # check cluster parameters
636
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
637
            constants.BES_PARAMETER_TYPES)
638
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
639
            constants.NICS_PARAMETER_TYPES)
640
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
641
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
642
            constants.NDS_PARAMETER_TYPES)
643
    _helper_ipolicy("cluster", cluster.SimpleFillIPolicy({}), True)
644
    _helper_ispecs("cluster", cluster.SimpleFillIPolicy({}))
645

    
646
    # per-instance checks
647
    for instance_name in data.instances:
648
      instance = data.instances[instance_name]
649
      if instance.name != instance_name:
650
        result.append("instance '%s' is indexed by wrong name '%s'" %
651
                      (instance.name, instance_name))
652
      if instance.primary_node not in data.nodes:
653
        result.append("instance '%s' has invalid primary node '%s'" %
654
                      (instance_name, instance.primary_node))
655
      for snode in instance.secondary_nodes:
656
        if snode not in data.nodes:
657
          result.append("instance '%s' has invalid secondary node '%s'" %
658
                        (instance_name, snode))
659
      for idx, nic in enumerate(instance.nics):
660
        if nic.mac in seen_macs:
661
          result.append("instance '%s' has NIC %d mac %s duplicate" %
662
                        (instance_name, idx, nic.mac))
663
        else:
664
          seen_macs.append(nic.mac)
665
        if nic.nicparams:
666
          filled = cluster.SimpleFillNIC(nic.nicparams)
667
          owner = "instance %s nic %d" % (instance.name, idx)
668
          _helper(owner, "nicparams",
669
                  filled, constants.NICS_PARAMETER_TYPES)
670
          _helper_nic(owner, filled)
671

    
672
      # parameter checks
673
      if instance.beparams:
674
        _helper("instance %s" % instance.name, "beparams",
675
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
676

    
677
      # gather the drbd ports for duplicate checks
678
      for (idx, dsk) in enumerate(instance.disks):
679
        if dsk.dev_type in constants.LDS_DRBD:
680
          tcp_port = dsk.logical_id[2]
681
          if tcp_port not in ports:
682
            ports[tcp_port] = []
683
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
684
      # gather network port reservation
685
      net_port = getattr(instance, "network_port", None)
686
      if net_port is not None:
687
        if net_port not in ports:
688
          ports[net_port] = []
689
        ports[net_port].append((instance.name, "network port"))
690

    
691
      # instance disk verify
692
      for idx, disk in enumerate(instance.disks):
693
        result.extend(["instance '%s' disk %d error: %s" %
694
                       (instance.name, idx, msg) for msg in disk.Verify()])
695
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
696

    
697
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
698
      if wrong_names:
699
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
700
                         (idx, exp_name, actual_name))
701
                        for (idx, exp_name, actual_name) in wrong_names)
702

    
703
        result.append("Instance '%s' has wrongly named disks: %s" %
704
                      (instance.name, tmp))
705

    
706
    # cluster-wide pool of free ports
707
    for free_port in cluster.tcpudp_port_pool:
708
      if free_port not in ports:
709
        ports[free_port] = []
710
      ports[free_port].append(("cluster", "port marked as free"))
711

    
712
    # compute tcp/udp duplicate ports
713
    keys = ports.keys()
714
    keys.sort()
715
    for pnum in keys:
716
      pdata = ports[pnum]
717
      if len(pdata) > 1:
718
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
719
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
720

    
721
    # highest used tcp port check
722
    if keys:
723
      if keys[-1] > cluster.highest_used_port:
724
        result.append("Highest used port mismatch, saved %s, computed %s" %
725
                      (cluster.highest_used_port, keys[-1]))
726

    
727
    if not data.nodes[cluster.master_node].master_candidate:
728
      result.append("Master node is not a master candidate")
729

    
730
    # master candidate checks
731
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
732
    if mc_now < mc_max:
733
      result.append("Not enough master candidates: actual %d, target %d" %
734
                    (mc_now, mc_max))
735

    
736
    # node checks
737
    for node_name, node in data.nodes.items():
738
      if node.name != node_name:
739
        result.append("Node '%s' is indexed by wrong name '%s'" %
740
                      (node.name, node_name))
741
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
742
        result.append("Node %s state is invalid: master_candidate=%s,"
743
                      " drain=%s, offline=%s" %
744
                      (node.name, node.master_candidate, node.drained,
745
                       node.offline))
746
      if node.group not in data.nodegroups:
747
        result.append("Node '%s' has invalid group '%s'" %
748
                      (node.name, node.group))
749
      else:
750
        _helper("node %s" % node.name, "ndparams",
751
                cluster.FillND(node, data.nodegroups[node.group]),
752
                constants.NDS_PARAMETER_TYPES)
753

    
754
    # nodegroups checks
755
    nodegroups_names = set()
756
    for nodegroup_uuid in data.nodegroups:
757
      nodegroup = data.nodegroups[nodegroup_uuid]
758
      if nodegroup.uuid != nodegroup_uuid:
759
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
760
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
761
      if utils.UUID_RE.match(nodegroup.name.lower()):
762
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
763
                      (nodegroup.name, nodegroup.uuid))
764
      if nodegroup.name in nodegroups_names:
765
        result.append("duplicate node group name '%s'" % nodegroup.name)
766
      else:
767
        nodegroups_names.add(nodegroup.name)
768
      group_name = "group %s" % nodegroup.name
769
      _helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy),
770
                      False)
771
      _helper_ispecs(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy))
772
      if nodegroup.ndparams:
773
        _helper(group_name, "ndparams",
774
                cluster.SimpleFillND(nodegroup.ndparams),
775
                constants.NDS_PARAMETER_TYPES)
776

    
777
    # drbd minors check
778
    _, duplicates = self._UnlockedComputeDRBDMap()
779
    for node, minor, instance_a, instance_b in duplicates:
780
      result.append("DRBD minor %d on node %s is assigned twice to instances"
781
                    " %s and %s" % (minor, node, instance_a, instance_b))
782

    
783
    # IP checks
784
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
785
    ips = {}
786

    
787
    def _AddIpAddress(ip, name):
788
      ips.setdefault(ip, []).append(name)
789

    
790
    _AddIpAddress(cluster.master_ip, "cluster_ip")
791

    
792
    for node in data.nodes.values():
793
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
794
      if node.secondary_ip != node.primary_ip:
795
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
796

    
797
    for instance in data.instances.values():
798
      for idx, nic in enumerate(instance.nics):
799
        if nic.ip is None:
800
          continue
801

    
802
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
803
        nic_mode = nicparams[constants.NIC_MODE]
804
        nic_link = nicparams[constants.NIC_LINK]
805

    
806
        if nic_mode == constants.NIC_MODE_BRIDGED:
807
          link = "bridge:%s" % nic_link
808
        elif nic_mode == constants.NIC_MODE_ROUTED:
809
          link = "route:%s" % nic_link
810
        else:
811
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
812

    
813
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
814
                      "instance:%s/nic:%d" % (instance.name, idx))
815

    
816
    for ip, owners in ips.items():
817
      if len(owners) > 1:
818
        result.append("IP address %s is used by multiple owners: %s" %
819
                      (ip, utils.CommaJoin(owners)))
820

    
821
    return result
822

    
823
  @locking.ssynchronized(_config_lock, shared=1)
824
  def VerifyConfig(self):
825
    """Verify function.
826

827
    This is just a wrapper over L{_UnlockedVerifyConfig}.
828

829
    @rtype: list
830
    @return: a list of error messages; a non-empty list signifies
831
        configuration errors
832

833
    """
834
    return self._UnlockedVerifyConfig()
835

    
836
  def _UnlockedSetDiskID(self, disk, node_name):
837
    """Convert the unique ID to the ID needed on the target nodes.
838

839
    This is used only for drbd, which needs ip/port configuration.
840

841
    The routine descends down and updates its children also, because
842
    this helps when the only the top device is passed to the remote
843
    node.
844

845
    This function is for internal use, when the config lock is already held.
846

847
    """
848
    if disk.children:
849
      for child in disk.children:
850
        self._UnlockedSetDiskID(child, node_name)
851

    
852
    if disk.logical_id is None and disk.physical_id is not None:
853
      return
854
    if disk.dev_type == constants.LD_DRBD8:
855
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
856
      if node_name not in (pnode, snode):
857
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
858
                                        node_name)
859
      pnode_info = self._UnlockedGetNodeInfo(pnode)
860
      snode_info = self._UnlockedGetNodeInfo(snode)
861
      if pnode_info is None or snode_info is None:
862
        raise errors.ConfigurationError("Can't find primary or secondary node"
863
                                        " for %s" % str(disk))
864
      p_data = (pnode_info.secondary_ip, port)
865
      s_data = (snode_info.secondary_ip, port)
866
      if pnode == node_name:
867
        disk.physical_id = p_data + s_data + (pminor, secret)
868
      else: # it must be secondary, we tested above
869
        disk.physical_id = s_data + p_data + (sminor, secret)
870
    else:
871
      disk.physical_id = disk.logical_id
872
    return
873

    
874
  @locking.ssynchronized(_config_lock)
875
  def SetDiskID(self, disk, node_name):
876
    """Convert the unique ID to the ID needed on the target nodes.
877

878
    This is used only for drbd, which needs ip/port configuration.
879

880
    The routine descends down and updates its children also, because
881
    this helps when the only the top device is passed to the remote
882
    node.
883

884
    """
885
    return self._UnlockedSetDiskID(disk, node_name)
886

    
887
  @locking.ssynchronized(_config_lock)
888
  def AddTcpUdpPort(self, port):
889
    """Adds a new port to the available port pool.
890

891
    @warning: this method does not "flush" the configuration (via
892
        L{_WriteConfig}); callers should do that themselves once the
893
        configuration is stable
894

895
    """
896
    if not isinstance(port, int):
897
      raise errors.ProgrammerError("Invalid type passed for port")
898

    
899
    self._config_data.cluster.tcpudp_port_pool.add(port)
900

    
901
  @locking.ssynchronized(_config_lock, shared=1)
902
  def GetPortList(self):
903
    """Returns a copy of the current port list.
904

905
    """
906
    return self._config_data.cluster.tcpudp_port_pool.copy()
907

    
908
  @locking.ssynchronized(_config_lock)
909
  def AllocatePort(self):
910
    """Allocate a port.
911

912
    The port will be taken from the available port pool or from the
913
    default port range (and in this case we increase
914
    highest_used_port).
915

916
    """
917
    # If there are TCP/IP ports configured, we use them first.
918
    if self._config_data.cluster.tcpudp_port_pool:
919
      port = self._config_data.cluster.tcpudp_port_pool.pop()
920
    else:
921
      port = self._config_data.cluster.highest_used_port + 1
922
      if port >= constants.LAST_DRBD_PORT:
923
        raise errors.ConfigurationError("The highest used port is greater"
924
                                        " than %s. Aborting." %
925
                                        constants.LAST_DRBD_PORT)
926
      self._config_data.cluster.highest_used_port = port
927

    
928
    self._WriteConfig()
929
    return port
930

    
931
  def _UnlockedComputeDRBDMap(self):
932
    """Compute the used DRBD minor/nodes.
933

934
    @rtype: (dict, list)
935
    @return: dictionary of node_name: dict of minor: instance_name;
936
        the returned dict will have all the nodes in it (even if with
937
        an empty list), and a list of duplicates; if the duplicates
938
        list is not empty, the configuration is corrupted and its caller
939
        should raise an exception
940

941
    """
942
    def _AppendUsedPorts(instance_name, disk, used):
943
      duplicates = []
944
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
945
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
946
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
947
          assert node in used, ("Node '%s' of instance '%s' not found"
948
                                " in node list" % (node, instance_name))
949
          if port in used[node]:
950
            duplicates.append((node, port, instance_name, used[node][port]))
951
          else:
952
            used[node][port] = instance_name
953
      if disk.children:
954
        for child in disk.children:
955
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
956
      return duplicates
957

    
958
    duplicates = []
959
    my_dict = dict((node, {}) for node in self._config_data.nodes)
960
    for instance in self._config_data.instances.itervalues():
961
      for disk in instance.disks:
962
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
963
    for (node, minor), instance in self._temporary_drbds.iteritems():
964
      if minor in my_dict[node] and my_dict[node][minor] != instance:
965
        duplicates.append((node, minor, instance, my_dict[node][minor]))
966
      else:
967
        my_dict[node][minor] = instance
968
    return my_dict, duplicates
969

    
970
  @locking.ssynchronized(_config_lock)
971
  def ComputeDRBDMap(self):
972
    """Compute the used DRBD minor/nodes.
973

974
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
975

976
    @return: dictionary of node_name: dict of minor: instance_name;
977
        the returned dict will have all the nodes in it (even if with
978
        an empty list).
979

980
    """
981
    d_map, duplicates = self._UnlockedComputeDRBDMap()
982
    if duplicates:
983
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
984
                                      str(duplicates))
985
    return d_map
986

    
987
  @locking.ssynchronized(_config_lock)
988
  def AllocateDRBDMinor(self, nodes, instance):
989
    """Allocate a drbd minor.
990

991
    The free minor will be automatically computed from the existing
992
    devices. A node can be given multiple times in order to allocate
993
    multiple minors. The result is the list of minors, in the same
994
    order as the passed nodes.
995

996
    @type instance: string
997
    @param instance: the instance for which we allocate minors
998

999
    """
1000
    assert isinstance(instance, basestring), \
1001
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
1002

    
1003
    d_map, duplicates = self._UnlockedComputeDRBDMap()
1004
    if duplicates:
1005
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
1006
                                      str(duplicates))
1007
    result = []
1008
    for nname in nodes:
1009
      ndata = d_map[nname]
1010
      if not ndata:
1011
        # no minors used, we can start at 0
1012
        result.append(0)
1013
        ndata[0] = instance
1014
        self._temporary_drbds[(nname, 0)] = instance
1015
        continue
1016
      keys = ndata.keys()
1017
      keys.sort()
1018
      ffree = utils.FirstFree(keys)
1019
      if ffree is None:
1020
        # return the next minor
1021
        # TODO: implement high-limit check
1022
        minor = keys[-1] + 1
1023
      else:
1024
        minor = ffree
1025
      # double-check minor against current instances
1026
      assert minor not in d_map[nname], \
1027
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
1028
              " already allocated to instance %s" %
1029
              (minor, nname, d_map[nname][minor]))
1030
      ndata[minor] = instance
1031
      # double-check minor against reservation
1032
      r_key = (nname, minor)
1033
      assert r_key not in self._temporary_drbds, \
1034
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
1035
              " reserved for instance %s" %
1036
              (minor, nname, self._temporary_drbds[r_key]))
1037
      self._temporary_drbds[r_key] = instance
1038
      result.append(minor)
1039
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
1040
                  nodes, result)
1041
    return result
1042

    
1043
  def _UnlockedReleaseDRBDMinors(self, instance):
1044
    """Release temporary drbd minors allocated for a given instance.
1045

1046
    @type instance: string
1047
    @param instance: the instance for which temporary minors should be
1048
                     released
1049

1050
    """
1051
    assert isinstance(instance, basestring), \
1052
           "Invalid argument passed to ReleaseDRBDMinors"
1053
    for key, name in self._temporary_drbds.items():
1054
      if name == instance:
1055
        del self._temporary_drbds[key]
1056

    
1057
  @locking.ssynchronized(_config_lock)
1058
  def ReleaseDRBDMinors(self, instance):
1059
    """Release temporary drbd minors allocated for a given instance.
1060

1061
    This should be called on the error paths, on the success paths
1062
    it's automatically called by the ConfigWriter add and update
1063
    functions.
1064

1065
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1066

1067
    @type instance: string
1068
    @param instance: the instance for which temporary minors should be
1069
                     released
1070

1071
    """
1072
    self._UnlockedReleaseDRBDMinors(instance)
1073

    
1074
  @locking.ssynchronized(_config_lock, shared=1)
1075
  def GetConfigVersion(self):
1076
    """Get the configuration version.
1077

1078
    @return: Config version
1079

1080
    """
1081
    return self._config_data.version
1082

    
1083
  @locking.ssynchronized(_config_lock, shared=1)
1084
  def GetClusterName(self):
1085
    """Get cluster name.
1086

1087
    @return: Cluster name
1088

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

    
1092
  @locking.ssynchronized(_config_lock, shared=1)
1093
  def GetMasterNode(self):
1094
    """Get the hostname of the master node for this cluster.
1095

1096
    @return: Master hostname
1097

1098
    """
1099
    return self._config_data.cluster.master_node
1100

    
1101
  @locking.ssynchronized(_config_lock, shared=1)
1102
  def GetMasterIP(self):
1103
    """Get the IP of the master node for this cluster.
1104

1105
    @return: Master IP
1106

1107
    """
1108
    return self._config_data.cluster.master_ip
1109

    
1110
  @locking.ssynchronized(_config_lock, shared=1)
1111
  def GetMasterNetdev(self):
1112
    """Get the master network device for this cluster.
1113

1114
    """
1115
    return self._config_data.cluster.master_netdev
1116

    
1117
  @locking.ssynchronized(_config_lock, shared=1)
1118
  def GetMasterNetmask(self):
1119
    """Get the netmask of the master node for this cluster.
1120

1121
    """
1122
    return self._config_data.cluster.master_netmask
1123

    
1124
  @locking.ssynchronized(_config_lock, shared=1)
1125
  def GetUseExternalMipScript(self):
1126
    """Get flag representing whether to use the external master IP setup script.
1127

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

    
1131
  @locking.ssynchronized(_config_lock, shared=1)
1132
  def GetFileStorageDir(self):
1133
    """Get the file storage dir for this cluster.
1134

1135
    """
1136
    return self._config_data.cluster.file_storage_dir
1137

    
1138
  @locking.ssynchronized(_config_lock, shared=1)
1139
  def GetSharedFileStorageDir(self):
1140
    """Get the shared file storage dir for this cluster.
1141

1142
    """
1143
    return self._config_data.cluster.shared_file_storage_dir
1144

    
1145
  @locking.ssynchronized(_config_lock, shared=1)
1146
  def GetHypervisorType(self):
1147
    """Get the hypervisor type for this cluster.
1148

1149
    """
1150
    return self._config_data.cluster.enabled_hypervisors[0]
1151

    
1152
  @locking.ssynchronized(_config_lock, shared=1)
1153
  def GetHostKey(self):
1154
    """Return the rsa hostkey from the config.
1155

1156
    @rtype: string
1157
    @return: the rsa hostkey
1158

1159
    """
1160
    return self._config_data.cluster.rsahostkeypub
1161

    
1162
  @locking.ssynchronized(_config_lock, shared=1)
1163
  def GetDefaultIAllocator(self):
1164
    """Get the default instance allocator for this cluster.
1165

1166
    """
1167
    return self._config_data.cluster.default_iallocator
1168

    
1169
  @locking.ssynchronized(_config_lock, shared=1)
1170
  def GetPrimaryIPFamily(self):
1171
    """Get cluster primary ip family.
1172

1173
    @return: primary ip family
1174

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

    
1178
  @locking.ssynchronized(_config_lock, shared=1)
1179
  def GetMasterNetworkParameters(self):
1180
    """Get network parameters of the master node.
1181

1182
    @rtype: L{object.MasterNetworkParameters}
1183
    @return: network parameters of the master node
1184

1185
    """
1186
    cluster = self._config_data.cluster
1187
    result = objects.MasterNetworkParameters(
1188
      name=cluster.master_node, ip=cluster.master_ip,
1189
      netmask=cluster.master_netmask, netdev=cluster.master_netdev,
1190
      ip_family=cluster.primary_ip_family)
1191

    
1192
    return result
1193

    
1194
  @locking.ssynchronized(_config_lock)
1195
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1196
    """Add a node group to the configuration.
1197

1198
    This method calls group.UpgradeConfig() to fill any missing attributes
1199
    according to their default values.
1200

1201
    @type group: L{objects.NodeGroup}
1202
    @param group: the NodeGroup object to add
1203
    @type ec_id: string
1204
    @param ec_id: unique id for the job to use when creating a missing UUID
1205
    @type check_uuid: bool
1206
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1207
                       it does, ensure that it does not exist in the
1208
                       configuration already
1209

1210
    """
1211
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1212
    self._WriteConfig()
1213

    
1214
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1215
    """Add a node group to the configuration.
1216

1217
    """
1218
    logging.info("Adding node group %s to configuration", group.name)
1219

    
1220
    # Some code might need to add a node group with a pre-populated UUID
1221
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1222
    # the "does this UUID" exist already check.
1223
    if check_uuid:
1224
      self._EnsureUUID(group, ec_id)
1225

    
1226
    try:
1227
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1228
    except errors.OpPrereqError:
1229
      pass
1230
    else:
1231
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1232
                                 " node group (UUID: %s)" %
1233
                                 (group.name, existing_uuid),
1234
                                 errors.ECODE_EXISTS)
1235

    
1236
    group.serial_no = 1
1237
    group.ctime = group.mtime = time.time()
1238
    group.UpgradeConfig()
1239

    
1240
    self._config_data.nodegroups[group.uuid] = group
1241
    self._config_data.cluster.serial_no += 1
1242

    
1243
  @locking.ssynchronized(_config_lock)
1244
  def RemoveNodeGroup(self, group_uuid):
1245
    """Remove a node group from the configuration.
1246

1247
    @type group_uuid: string
1248
    @param group_uuid: the UUID of the node group to remove
1249

1250
    """
1251
    logging.info("Removing node group %s from configuration", group_uuid)
1252

    
1253
    if group_uuid not in self._config_data.nodegroups:
1254
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1255

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

    
1259
    del self._config_data.nodegroups[group_uuid]
1260
    self._config_data.cluster.serial_no += 1
1261
    self._WriteConfig()
1262

    
1263
  def _UnlockedLookupNodeGroup(self, target):
1264
    """Lookup a node group's UUID.
1265

1266
    @type target: string or None
1267
    @param target: group name or UUID or None to look for the default
1268
    @rtype: string
1269
    @return: nodegroup UUID
1270
    @raises errors.OpPrereqError: when the target group cannot be found
1271

1272
    """
1273
    if target is None:
1274
      if len(self._config_data.nodegroups) != 1:
1275
        raise errors.OpPrereqError("More than one node group exists. Target"
1276
                                   " group must be specified explicitly.")
1277
      else:
1278
        return self._config_data.nodegroups.keys()[0]
1279
    if target in self._config_data.nodegroups:
1280
      return target
1281
    for nodegroup in self._config_data.nodegroups.values():
1282
      if nodegroup.name == target:
1283
        return nodegroup.uuid
1284
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1285
                               errors.ECODE_NOENT)
1286

    
1287
  @locking.ssynchronized(_config_lock, shared=1)
1288
  def LookupNodeGroup(self, target):
1289
    """Lookup a node group's UUID.
1290

1291
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1292

1293
    @type target: string or None
1294
    @param target: group name or UUID or None to look for the default
1295
    @rtype: string
1296
    @return: nodegroup UUID
1297

1298
    """
1299
    return self._UnlockedLookupNodeGroup(target)
1300

    
1301
  def _UnlockedGetNodeGroup(self, uuid):
1302
    """Lookup a node group.
1303

1304
    @type uuid: string
1305
    @param uuid: group UUID
1306
    @rtype: L{objects.NodeGroup} or None
1307
    @return: nodegroup object, or None if not found
1308

1309
    """
1310
    if uuid not in self._config_data.nodegroups:
1311
      return None
1312

    
1313
    return self._config_data.nodegroups[uuid]
1314

    
1315
  @locking.ssynchronized(_config_lock, shared=1)
1316
  def GetNodeGroup(self, uuid):
1317
    """Lookup a node group.
1318

1319
    @type uuid: string
1320
    @param uuid: group UUID
1321
    @rtype: L{objects.NodeGroup} or None
1322
    @return: nodegroup object, or None if not found
1323

1324
    """
1325
    return self._UnlockedGetNodeGroup(uuid)
1326

    
1327
  @locking.ssynchronized(_config_lock, shared=1)
1328
  def GetAllNodeGroupsInfo(self):
1329
    """Get the configuration of all node groups.
1330

1331
    """
1332
    return dict(self._config_data.nodegroups)
1333

    
1334
  @locking.ssynchronized(_config_lock, shared=1)
1335
  def GetNodeGroupList(self):
1336
    """Get a list of node groups.
1337

1338
    """
1339
    return self._config_data.nodegroups.keys()
1340

    
1341
  @locking.ssynchronized(_config_lock, shared=1)
1342
  def GetNodeGroupMembersByNodes(self, nodes):
1343
    """Get nodes which are member in the same nodegroups as the given nodes.
1344

1345
    """
1346
    ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1347
    return frozenset(member_name
1348
                     for node_name in nodes
1349
                     for member_name in
1350
                       self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1351

    
1352
  @locking.ssynchronized(_config_lock, shared=1)
1353
  def GetMultiNodeGroupInfo(self, group_uuids):
1354
    """Get the configuration of multiple node groups.
1355

1356
    @param group_uuids: List of node group UUIDs
1357
    @rtype: list
1358
    @return: List of tuples of (group_uuid, group_info)
1359

1360
    """
1361
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1362

    
1363
  @locking.ssynchronized(_config_lock)
1364
  def AddInstance(self, instance, ec_id):
1365
    """Add an instance to the config.
1366

1367
    This should be used after creating a new instance.
1368

1369
    @type instance: L{objects.Instance}
1370
    @param instance: the instance object
1371

1372
    """
1373
    if not isinstance(instance, objects.Instance):
1374
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1375

    
1376
    if instance.disk_template != constants.DT_DISKLESS:
1377
      all_lvs = instance.MapLVsByNode()
1378
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1379

    
1380
    all_macs = self._AllMACs()
1381
    for nic in instance.nics:
1382
      if nic.mac in all_macs:
1383
        raise errors.ConfigurationError("Cannot add instance %s:"
1384
                                        " MAC address '%s' already in use." %
1385
                                        (instance.name, nic.mac))
1386

    
1387
    self._EnsureUUID(instance, ec_id)
1388

    
1389
    instance.serial_no = 1
1390
    instance.ctime = instance.mtime = time.time()
1391
    self._config_data.instances[instance.name] = instance
1392
    self._config_data.cluster.serial_no += 1
1393
    self._UnlockedReleaseDRBDMinors(instance.name)
1394
    self._UnlockedCommitTemporaryIps(ec_id)
1395
    self._WriteConfig()
1396

    
1397
  def _EnsureUUID(self, item, ec_id):
1398
    """Ensures a given object has a valid UUID.
1399

1400
    @param item: the instance or node to be checked
1401
    @param ec_id: the execution context id for the uuid reservation
1402

1403
    """
1404
    if not item.uuid:
1405
      item.uuid = self._GenerateUniqueID(ec_id)
1406
    elif item.uuid in self._AllIDs(include_temporary=True):
1407
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1408
                                      " in use" % (item.name, item.uuid))
1409

    
1410
  def _SetInstanceStatus(self, instance_name, status):
1411
    """Set the instance's status to a given value.
1412

1413
    """
1414
    assert status in constants.ADMINST_ALL, \
1415
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1416

    
1417
    if instance_name not in self._config_data.instances:
1418
      raise errors.ConfigurationError("Unknown instance '%s'" %
1419
                                      instance_name)
1420
    instance = self._config_data.instances[instance_name]
1421
    if instance.admin_state != status:
1422
      instance.admin_state = status
1423
      instance.serial_no += 1
1424
      instance.mtime = time.time()
1425
      self._WriteConfig()
1426

    
1427
  @locking.ssynchronized(_config_lock)
1428
  def MarkInstanceUp(self, instance_name):
1429
    """Mark the instance status to up in the config.
1430

1431
    """
1432
    self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1433

    
1434
  @locking.ssynchronized(_config_lock)
1435
  def MarkInstanceOffline(self, instance_name):
1436
    """Mark the instance status to down in the config.
1437

1438
    """
1439
    self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1440

    
1441
  @locking.ssynchronized(_config_lock)
1442
  def RemoveInstance(self, instance_name):
1443
    """Remove the instance from the configuration.
1444

1445
    """
1446
    if instance_name not in self._config_data.instances:
1447
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1448

    
1449
    # If a network port has been allocated to the instance,
1450
    # return it to the pool of free ports.
1451
    inst = self._config_data.instances[instance_name]
1452
    network_port = getattr(inst, "network_port", None)
1453
    if network_port is not None:
1454
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1455

    
1456
    instance = self._UnlockedGetInstanceInfo(instance_name)
1457

    
1458
    for nic in instance.nics:
1459
      if nic.network is not None and nic.ip is not None:
1460
        net_uuid = self._UnlockedLookupNetwork(nic.network)
1461
        if net_uuid:
1462
          # Return all IP addresses to the respective address pools
1463
          self._UnlockedCommitIp(constants.RELEASE_ACTION, net_uuid, nic.ip)
1464

    
1465
    del self._config_data.instances[instance_name]
1466
    self._config_data.cluster.serial_no += 1
1467
    self._WriteConfig()
1468

    
1469
  @locking.ssynchronized(_config_lock)
1470
  def RenameInstance(self, old_name, new_name):
1471
    """Rename an instance.
1472

1473
    This needs to be done in ConfigWriter and not by RemoveInstance
1474
    combined with AddInstance as only we can guarantee an atomic
1475
    rename.
1476

1477
    """
1478
    if old_name not in self._config_data.instances:
1479
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1480

    
1481
    # Operate on a copy to not loose instance object in case of a failure
1482
    inst = self._config_data.instances[old_name].Copy()
1483
    inst.name = new_name
1484

    
1485
    for (idx, disk) in enumerate(inst.disks):
1486
      if disk.dev_type == constants.LD_FILE:
1487
        # rename the file paths in logical and physical id
1488
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1489
        disk.logical_id = (disk.logical_id[0],
1490
                           utils.PathJoin(file_storage_dir, inst.name,
1491
                                          "disk%s" % idx))
1492
        disk.physical_id = disk.logical_id
1493

    
1494
    # Actually replace instance object
1495
    del self._config_data.instances[old_name]
1496
    self._config_data.instances[inst.name] = inst
1497

    
1498
    # Force update of ssconf files
1499
    self._config_data.cluster.serial_no += 1
1500

    
1501
    self._WriteConfig()
1502

    
1503
  @locking.ssynchronized(_config_lock)
1504
  def MarkInstanceDown(self, instance_name):
1505
    """Mark the status of an instance to down in the configuration.
1506

1507
    """
1508
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1509

    
1510
  def _UnlockedGetInstanceList(self):
1511
    """Get the list of instances.
1512

1513
    This function is for internal use, when the config lock is already held.
1514

1515
    """
1516
    return self._config_data.instances.keys()
1517

    
1518
  @locking.ssynchronized(_config_lock, shared=1)
1519
  def GetInstanceList(self):
1520
    """Get the list of instances.
1521

1522
    @return: array of instances, ex. ['instance2.example.com',
1523
        'instance1.example.com']
1524

1525
    """
1526
    return self._UnlockedGetInstanceList()
1527

    
1528
  def ExpandInstanceName(self, short_name):
1529
    """Attempt to expand an incomplete instance name.
1530

1531
    """
1532
    # Locking is done in L{ConfigWriter.GetInstanceList}
1533
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1534

    
1535
  def _UnlockedGetInstanceInfo(self, instance_name):
1536
    """Returns information about an instance.
1537

1538
    This function is for internal use, when the config lock is already held.
1539

1540
    """
1541
    if instance_name not in self._config_data.instances:
1542
      return None
1543

    
1544
    return self._config_data.instances[instance_name]
1545

    
1546
  @locking.ssynchronized(_config_lock, shared=1)
1547
  def GetInstanceInfo(self, instance_name):
1548
    """Returns information about an instance.
1549

1550
    It takes the information from the configuration file. Other information of
1551
    an instance are taken from the live systems.
1552

1553
    @param instance_name: name of the instance, e.g.
1554
        I{instance1.example.com}
1555

1556
    @rtype: L{objects.Instance}
1557
    @return: the instance object
1558

1559
    """
1560
    return self._UnlockedGetInstanceInfo(instance_name)
1561

    
1562
  @locking.ssynchronized(_config_lock, shared=1)
1563
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1564
    """Returns set of node group UUIDs for instance's nodes.
1565

1566
    @rtype: frozenset
1567

1568
    """
1569
    instance = self._UnlockedGetInstanceInfo(instance_name)
1570
    if not instance:
1571
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1572

    
1573
    if primary_only:
1574
      nodes = [instance.primary_node]
1575
    else:
1576
      nodes = instance.all_nodes
1577

    
1578
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1579
                     for node_name in nodes)
1580

    
1581
  @locking.ssynchronized(_config_lock, shared=1)
1582
  def GetMultiInstanceInfo(self, instances):
1583
    """Get the configuration of multiple instances.
1584

1585
    @param instances: list of instance names
1586
    @rtype: list
1587
    @return: list of tuples (instance, instance_info), where
1588
        instance_info is what would GetInstanceInfo return for the
1589
        node, while keeping the original order
1590

1591
    """
1592
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1593

    
1594
  @locking.ssynchronized(_config_lock, shared=1)
1595
  def GetAllInstancesInfo(self):
1596
    """Get the configuration of all instances.
1597

1598
    @rtype: dict
1599
    @return: dict of (instance, instance_info), where instance_info is what
1600
              would GetInstanceInfo return for the node
1601

1602
    """
1603
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1604
                    for instance in self._UnlockedGetInstanceList()])
1605
    return my_dict
1606

    
1607
  @locking.ssynchronized(_config_lock, shared=1)
1608
  def GetInstancesInfoByFilter(self, filter_fn):
1609
    """Get instance configuration with a filter.
1610

1611
    @type filter_fn: callable
1612
    @param filter_fn: Filter function receiving instance object as parameter,
1613
      returning boolean. Important: this function is called while the
1614
      configuration locks is held. It must not do any complex work or call
1615
      functions potentially leading to a deadlock. Ideally it doesn't call any
1616
      other functions and just compares instance attributes.
1617

1618
    """
1619
    return dict((name, inst)
1620
                for (name, inst) in self._config_data.instances.items()
1621
                if filter_fn(inst))
1622

    
1623
  @locking.ssynchronized(_config_lock)
1624
  def AddNode(self, node, ec_id):
1625
    """Add a node to the configuration.
1626

1627
    @type node: L{objects.Node}
1628
    @param node: a Node instance
1629

1630
    """
1631
    logging.info("Adding node %s to configuration", node.name)
1632

    
1633
    self._EnsureUUID(node, ec_id)
1634

    
1635
    node.serial_no = 1
1636
    node.ctime = node.mtime = time.time()
1637
    self._UnlockedAddNodeToGroup(node.name, node.group)
1638
    self._config_data.nodes[node.name] = node
1639
    self._config_data.cluster.serial_no += 1
1640
    self._WriteConfig()
1641

    
1642
  @locking.ssynchronized(_config_lock)
1643
  def RemoveNode(self, node_name):
1644
    """Remove a node from the configuration.
1645

1646
    """
1647
    logging.info("Removing node %s from configuration", node_name)
1648

    
1649
    if node_name not in self._config_data.nodes:
1650
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1651

    
1652
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1653
    del self._config_data.nodes[node_name]
1654
    self._config_data.cluster.serial_no += 1
1655
    self._WriteConfig()
1656

    
1657
  def ExpandNodeName(self, short_name):
1658
    """Attempt to expand an incomplete node name.
1659

1660
    """
1661
    # Locking is done in L{ConfigWriter.GetNodeList}
1662
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1663

    
1664
  def _UnlockedGetNodeInfo(self, node_name):
1665
    """Get the configuration of a node, as stored in the config.
1666

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

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

1672
    @rtype: L{objects.Node}
1673
    @return: the node object
1674

1675
    """
1676
    if node_name not in self._config_data.nodes:
1677
      return None
1678

    
1679
    return self._config_data.nodes[node_name]
1680

    
1681
  @locking.ssynchronized(_config_lock, shared=1)
1682
  def GetNodeInfo(self, node_name):
1683
    """Get the configuration of a node, as stored in the config.
1684

1685
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1686

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

1689
    @rtype: L{objects.Node}
1690
    @return: the node object
1691

1692
    """
1693
    return self._UnlockedGetNodeInfo(node_name)
1694

    
1695
  @locking.ssynchronized(_config_lock, shared=1)
1696
  def GetNodeInstances(self, node_name):
1697
    """Get the instances of a node, as stored in the config.
1698

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

1701
    @rtype: (list, list)
1702
    @return: a tuple with two lists: the primary and the secondary instances
1703

1704
    """
1705
    pri = []
1706
    sec = []
1707
    for inst in self._config_data.instances.values():
1708
      if inst.primary_node == node_name:
1709
        pri.append(inst.name)
1710
      if node_name in inst.secondary_nodes:
1711
        sec.append(inst.name)
1712
    return (pri, sec)
1713

    
1714
  @locking.ssynchronized(_config_lock, shared=1)
1715
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1716
    """Get the instances of a node group.
1717

1718
    @param uuid: Node group UUID
1719
    @param primary_only: Whether to only consider primary nodes
1720
    @rtype: frozenset
1721
    @return: List of instance names in node group
1722

1723
    """
1724
    if primary_only:
1725
      nodes_fn = lambda inst: [inst.primary_node]
1726
    else:
1727
      nodes_fn = lambda inst: inst.all_nodes
1728

    
1729
    return frozenset(inst.name
1730
                     for inst in self._config_data.instances.values()
1731
                     for node_name in nodes_fn(inst)
1732
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1733

    
1734
  def _UnlockedGetNodeList(self):
1735
    """Return the list of nodes which are in the configuration.
1736

1737
    This function is for internal use, when the config lock is already
1738
    held.
1739

1740
    @rtype: list
1741

1742
    """
1743
    return self._config_data.nodes.keys()
1744

    
1745
  @locking.ssynchronized(_config_lock, shared=1)
1746
  def GetNodeList(self):
1747
    """Return the list of nodes which are in the configuration.
1748

1749
    """
1750
    return self._UnlockedGetNodeList()
1751

    
1752
  def _UnlockedGetOnlineNodeList(self):
1753
    """Return the list of nodes which are online.
1754

1755
    """
1756
    all_nodes = [self._UnlockedGetNodeInfo(node)
1757
                 for node in self._UnlockedGetNodeList()]
1758
    return [node.name for node in all_nodes if not node.offline]
1759

    
1760
  @locking.ssynchronized(_config_lock, shared=1)
1761
  def GetOnlineNodeList(self):
1762
    """Return the list of nodes which are online.
1763

1764
    """
1765
    return self._UnlockedGetOnlineNodeList()
1766

    
1767
  @locking.ssynchronized(_config_lock, shared=1)
1768
  def GetVmCapableNodeList(self):
1769
    """Return the list of nodes which are not vm capable.
1770

1771
    """
1772
    all_nodes = [self._UnlockedGetNodeInfo(node)
1773
                 for node in self._UnlockedGetNodeList()]
1774
    return [node.name for node in all_nodes if node.vm_capable]
1775

    
1776
  @locking.ssynchronized(_config_lock, shared=1)
1777
  def GetNonVmCapableNodeList(self):
1778
    """Return the list of nodes which are not vm capable.
1779

1780
    """
1781
    all_nodes = [self._UnlockedGetNodeInfo(node)
1782
                 for node in self._UnlockedGetNodeList()]
1783
    return [node.name for node in all_nodes if not node.vm_capable]
1784

    
1785
  @locking.ssynchronized(_config_lock, shared=1)
1786
  def GetMultiNodeInfo(self, nodes):
1787
    """Get the configuration of multiple nodes.
1788

1789
    @param nodes: list of node names
1790
    @rtype: list
1791
    @return: list of tuples of (node, node_info), where node_info is
1792
        what would GetNodeInfo return for the node, in the original
1793
        order
1794

1795
    """
1796
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1797

    
1798
  @locking.ssynchronized(_config_lock, shared=1)
1799
  def GetAllNodesInfo(self):
1800
    """Get the configuration of all nodes.
1801

1802
    @rtype: dict
1803
    @return: dict of (node, node_info), where node_info is what
1804
              would GetNodeInfo return for the node
1805

1806
    """
1807
    return self._UnlockedGetAllNodesInfo()
1808

    
1809
  def _UnlockedGetAllNodesInfo(self):
1810
    """Gets configuration of all nodes.
1811

1812
    @note: See L{GetAllNodesInfo}
1813

1814
    """
1815
    return dict([(node, self._UnlockedGetNodeInfo(node))
1816
                 for node in self._UnlockedGetNodeList()])
1817

    
1818
  @locking.ssynchronized(_config_lock, shared=1)
1819
  def GetNodeGroupsFromNodes(self, nodes):
1820
    """Returns groups for a list of nodes.
1821

1822
    @type nodes: list of string
1823
    @param nodes: List of node names
1824
    @rtype: frozenset
1825

1826
    """
1827
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1828

    
1829
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1830
    """Get the number of current and maximum desired and possible candidates.
1831

1832
    @type exceptions: list
1833
    @param exceptions: if passed, list of nodes that should be ignored
1834
    @rtype: tuple
1835
    @return: tuple of (current, desired and possible, possible)
1836

1837
    """
1838
    mc_now = mc_should = mc_max = 0
1839
    for node in self._config_data.nodes.values():
1840
      if exceptions and node.name in exceptions:
1841
        continue
1842
      if not (node.offline or node.drained) and node.master_capable:
1843
        mc_max += 1
1844
      if node.master_candidate:
1845
        mc_now += 1
1846
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1847
    return (mc_now, mc_should, mc_max)
1848

    
1849
  @locking.ssynchronized(_config_lock, shared=1)
1850
  def GetMasterCandidateStats(self, exceptions=None):
1851
    """Get the number of current and maximum possible candidates.
1852

1853
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1854

1855
    @type exceptions: list
1856
    @param exceptions: if passed, list of nodes that should be ignored
1857
    @rtype: tuple
1858
    @return: tuple of (current, max)
1859

1860
    """
1861
    return self._UnlockedGetMasterCandidateStats(exceptions)
1862

    
1863
  @locking.ssynchronized(_config_lock)
1864
  def MaintainCandidatePool(self, exceptions):
1865
    """Try to grow the candidate pool to the desired size.
1866

1867
    @type exceptions: list
1868
    @param exceptions: if passed, list of nodes that should be ignored
1869
    @rtype: list
1870
    @return: list with the adjusted nodes (L{objects.Node} instances)
1871

1872
    """
1873
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1874
    mod_list = []
1875
    if mc_now < mc_max:
1876
      node_list = self._config_data.nodes.keys()
1877
      random.shuffle(node_list)
1878
      for name in node_list:
1879
        if mc_now >= mc_max:
1880
          break
1881
        node = self._config_data.nodes[name]
1882
        if (node.master_candidate or node.offline or node.drained or
1883
            node.name in exceptions or not node.master_capable):
1884
          continue
1885
        mod_list.append(node)
1886
        node.master_candidate = True
1887
        node.serial_no += 1
1888
        mc_now += 1
1889
      if mc_now != mc_max:
1890
        # this should not happen
1891
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1892
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1893
      if mod_list:
1894
        self._config_data.cluster.serial_no += 1
1895
        self._WriteConfig()
1896

    
1897
    return mod_list
1898

    
1899
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1900
    """Add a given node to the specified group.
1901

1902
    """
1903
    if nodegroup_uuid not in self._config_data.nodegroups:
1904
      # This can happen if a node group gets deleted between its lookup and
1905
      # when we're adding the first node to it, since we don't keep a lock in
1906
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1907
      # is not found anymore.
1908
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1909
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1910
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1911

    
1912
  def _UnlockedRemoveNodeFromGroup(self, node):
1913
    """Remove a given node from its group.
1914

1915
    """
1916
    nodegroup = node.group
1917
    if nodegroup not in self._config_data.nodegroups:
1918
      logging.warning("Warning: node '%s' has unknown node group '%s'"
1919
                      " (while being removed from it)", node.name, nodegroup)
1920
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1921
    if node.name not in nodegroup_obj.members:
1922
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
1923
                      " (while being removed from it)", node.name, nodegroup)
1924
    else:
1925
      nodegroup_obj.members.remove(node.name)
1926

    
1927
  @locking.ssynchronized(_config_lock)
1928
  def AssignGroupNodes(self, mods):
1929
    """Changes the group of a number of nodes.
1930

1931
    @type mods: list of tuples; (node name, new group UUID)
1932
    @param mods: Node membership modifications
1933

1934
    """
1935
    groups = self._config_data.nodegroups
1936
    nodes = self._config_data.nodes
1937

    
1938
    resmod = []
1939

    
1940
    # Try to resolve names/UUIDs first
1941
    for (node_name, new_group_uuid) in mods:
1942
      try:
1943
        node = nodes[node_name]
1944
      except KeyError:
1945
        raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1946

    
1947
      if node.group == new_group_uuid:
1948
        # Node is being assigned to its current group
1949
        logging.debug("Node '%s' was assigned to its current group (%s)",
1950
                      node_name, node.group)
1951
        continue
1952

    
1953
      # Try to find current group of node
1954
      try:
1955
        old_group = groups[node.group]
1956
      except KeyError:
1957
        raise errors.ConfigurationError("Unable to find old group '%s'" %
1958
                                        node.group)
1959

    
1960
      # Try to find new group for node
1961
      try:
1962
        new_group = groups[new_group_uuid]
1963
      except KeyError:
1964
        raise errors.ConfigurationError("Unable to find new group '%s'" %
1965
                                        new_group_uuid)
1966

    
1967
      assert node.name in old_group.members, \
1968
        ("Inconsistent configuration: node '%s' not listed in members for its"
1969
         " old group '%s'" % (node.name, old_group.uuid))
1970
      assert node.name not in new_group.members, \
1971
        ("Inconsistent configuration: node '%s' already listed in members for"
1972
         " its new group '%s'" % (node.name, new_group.uuid))
1973

    
1974
      resmod.append((node, old_group, new_group))
1975

    
1976
    # Apply changes
1977
    for (node, old_group, new_group) in resmod:
1978
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
1979
        "Assigning to current group is not possible"
1980

    
1981
      node.group = new_group.uuid
1982

    
1983
      # Update members of involved groups
1984
      if node.name in old_group.members:
1985
        old_group.members.remove(node.name)
1986
      if node.name not in new_group.members:
1987
        new_group.members.append(node.name)
1988

    
1989
    # Update timestamps and serials (only once per node/group object)
1990
    now = time.time()
1991
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
1992
      obj.serial_no += 1
1993
      obj.mtime = now
1994

    
1995
    # Force ssconf update
1996
    self._config_data.cluster.serial_no += 1
1997

    
1998
    self._WriteConfig()
1999

    
2000
  def _BumpSerialNo(self):
2001
    """Bump up the serial number of the config.
2002

2003
    """
2004
    self._config_data.serial_no += 1
2005
    self._config_data.mtime = time.time()
2006

    
2007
  def _AllUUIDObjects(self):
2008
    """Returns all objects with uuid attributes.
2009

2010
    """
2011
    return (self._config_data.instances.values() +
2012
            self._config_data.nodes.values() +
2013
            self._config_data.nodegroups.values() +
2014
            [self._config_data.cluster])
2015

    
2016
  def _OpenConfig(self, accept_foreign):
2017
    """Read the config data from disk.
2018

2019
    """
2020
    raw_data = utils.ReadFile(self._cfg_file)
2021

    
2022
    try:
2023
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
2024
    except Exception, err:
2025
      raise errors.ConfigurationError(err)
2026

    
2027
    # Make sure the configuration has the right version
2028
    _ValidateConfig(data)
2029

    
2030
    if (not hasattr(data, "cluster") or
2031
        not hasattr(data.cluster, "rsahostkeypub")):
2032
      raise errors.ConfigurationError("Incomplete configuration"
2033
                                      " (missing cluster.rsahostkeypub)")
2034

    
2035
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
2036
      msg = ("The configuration denotes node %s as master, while my"
2037
             " hostname is %s; opening a foreign configuration is only"
2038
             " possible in accept_foreign mode" %
2039
             (data.cluster.master_node, self._my_hostname))
2040
      raise errors.ConfigurationError(msg)
2041

    
2042
    # Upgrade configuration if needed
2043
    data.UpgradeConfig()
2044

    
2045
    self._config_data = data
2046
    # reset the last serial as -1 so that the next write will cause
2047
    # ssconf update
2048
    self._last_cluster_serial = -1
2049

    
2050
    # And finally run our (custom) config upgrade sequence
2051
    self._UpgradeConfig()
2052

    
2053
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2054

    
2055
  def _UpgradeConfig(self):
2056
    """Run upgrade steps that cannot be done purely in the objects.
2057

2058
    This is because some data elements need uniqueness across the
2059
    whole configuration, etc.
2060

2061
    @warning: this function will call L{_WriteConfig()}, but also
2062
        L{DropECReservations} so it needs to be called only from a
2063
        "safe" place (the constructor). If one wanted to call it with
2064
        the lock held, a DropECReservationUnlocked would need to be
2065
        created first, to avoid causing deadlock.
2066

2067
    """
2068
    modified = False
2069
    for item in self._AllUUIDObjects():
2070
      if item.uuid is None:
2071
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
2072
        modified = True
2073
    if not self._config_data.nodegroups:
2074
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
2075
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
2076
                                            members=[])
2077
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
2078
      modified = True
2079
    for node in self._config_data.nodes.values():
2080
      if not node.group:
2081
        node.group = self.LookupNodeGroup(None)
2082
        modified = True
2083
      # This is technically *not* an upgrade, but needs to be done both when
2084
      # nodegroups are being added, and upon normally loading the config,
2085
      # because the members list of a node group is discarded upon
2086
      # serializing/deserializing the object.
2087
      self._UnlockedAddNodeToGroup(node.name, node.group)
2088
    if modified:
2089
      self._WriteConfig()
2090
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
2091
      # only called at config init time, without the lock held
2092
      self.DropECReservations(_UPGRADE_CONFIG_JID)
2093

    
2094
  def _DistributeConfig(self, feedback_fn):
2095
    """Distribute the configuration to the other nodes.
2096

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

2100
    """
2101
    if self._offline:
2102
      return True
2103

    
2104
    bad = False
2105

    
2106
    node_list = []
2107
    addr_list = []
2108
    myhostname = self._my_hostname
2109
    # we can skip checking whether _UnlockedGetNodeInfo returns None
2110
    # since the node list comes from _UnlocketGetNodeList, and we are
2111
    # called with the lock held, so no modifications should take place
2112
    # in between
2113
    for node_name in self._UnlockedGetNodeList():
2114
      if node_name == myhostname:
2115
        continue
2116
      node_info = self._UnlockedGetNodeInfo(node_name)
2117
      if not node_info.master_candidate:
2118
        continue
2119
      node_list.append(node_info.name)
2120
      addr_list.append(node_info.primary_ip)
2121

    
2122
    # TODO: Use dedicated resolver talking to config writer for name resolution
2123
    result = \
2124
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2125
    for to_node, to_result in result.items():
2126
      msg = to_result.fail_msg
2127
      if msg:
2128
        msg = ("Copy of file %s to node %s failed: %s" %
2129
               (self._cfg_file, to_node, msg))
2130
        logging.error(msg)
2131

    
2132
        if feedback_fn:
2133
          feedback_fn(msg)
2134

    
2135
        bad = True
2136

    
2137
    return not bad
2138

    
2139
  def _WriteConfig(self, destination=None, feedback_fn=None):
2140
    """Write the configuration data to persistent storage.
2141

2142
    """
2143
    assert feedback_fn is None or callable(feedback_fn)
2144

    
2145
    # Warn on config errors, but don't abort the save - the
2146
    # configuration has already been modified, and we can't revert;
2147
    # the best we can do is to warn the user and save as is, leaving
2148
    # recovery to the user
2149
    config_errors = self._UnlockedVerifyConfig()
2150
    if config_errors:
2151
      errmsg = ("Configuration data is not consistent: %s" %
2152
                (utils.CommaJoin(config_errors)))
2153
      logging.critical(errmsg)
2154
      if feedback_fn:
2155
        feedback_fn(errmsg)
2156

    
2157
    if destination is None:
2158
      destination = self._cfg_file
2159
    self._BumpSerialNo()
2160
    txt = serializer.Dump(self._config_data.ToDict())
2161

    
2162
    getents = self._getents()
2163
    try:
2164
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2165
                               close=False, gid=getents.confd_gid, mode=0640)
2166
    except errors.LockError:
2167
      raise errors.ConfigurationError("The configuration file has been"
2168
                                      " modified since the last write, cannot"
2169
                                      " update")
2170
    try:
2171
      self._cfg_id = utils.GetFileID(fd=fd)
2172
    finally:
2173
      os.close(fd)
2174

    
2175
    self.write_count += 1
2176

    
2177
    # and redistribute the config file to master candidates
2178
    self._DistributeConfig(feedback_fn)
2179

    
2180
    # Write ssconf files on all nodes (including locally)
2181
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2182
      if not self._offline:
2183
        result = self._GetRpc(None).call_write_ssconf_files(
2184
          self._UnlockedGetOnlineNodeList(),
2185
          self._UnlockedGetSsconfValues())
2186

    
2187
        for nname, nresu in result.items():
2188
          msg = nresu.fail_msg
2189
          if msg:
2190
            errmsg = ("Error while uploading ssconf files to"
2191
                      " node %s: %s" % (nname, msg))
2192
            logging.warning(errmsg)
2193

    
2194
            if feedback_fn:
2195
              feedback_fn(errmsg)
2196

    
2197
      self._last_cluster_serial = self._config_data.cluster.serial_no
2198

    
2199
  def _UnlockedGetSsconfValues(self):
2200
    """Return the values needed by ssconf.
2201

2202
    @rtype: dict
2203
    @return: a dictionary with keys the ssconf names and values their
2204
        associated value
2205

2206
    """
2207
    fn = "\n".join
2208
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
2209
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
2210
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
2211
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2212
                    for ninfo in node_info]
2213
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2214
                    for ninfo in node_info]
2215

    
2216
    instance_data = fn(instance_names)
2217
    off_data = fn(node.name for node in node_info if node.offline)
2218
    on_data = fn(node.name for node in node_info if not node.offline)
2219
    mc_data = fn(node.name for node in node_info if node.master_candidate)
2220
    mc_ips_data = fn(node.primary_ip for node in node_info
2221
                     if node.master_candidate)
2222
    node_data = fn(node_names)
2223
    node_pri_ips_data = fn(node_pri_ips)
2224
    node_snd_ips_data = fn(node_snd_ips)
2225

    
2226
    cluster = self._config_data.cluster
2227
    cluster_tags = fn(cluster.GetTags())
2228

    
2229
    hypervisor_list = fn(cluster.enabled_hypervisors)
2230

    
2231
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2232

    
2233
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2234
                  self._config_data.nodegroups.values()]
2235
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2236
    networks = ["%s %s" % (net.uuid, net.name) for net in
2237
                self._config_data.networks.values()]
2238
    networks_data = fn(utils.NiceSort(networks))
2239

    
2240
    ssconf_values = {
2241
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
2242
      constants.SS_CLUSTER_TAGS: cluster_tags,
2243
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2244
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2245
      constants.SS_MASTER_CANDIDATES: mc_data,
2246
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2247
      constants.SS_MASTER_IP: cluster.master_ip,
2248
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
2249
      constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2250
      constants.SS_MASTER_NODE: cluster.master_node,
2251
      constants.SS_NODE_LIST: node_data,
2252
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2253
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2254
      constants.SS_OFFLINE_NODES: off_data,
2255
      constants.SS_ONLINE_NODES: on_data,
2256
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2257
      constants.SS_INSTANCE_LIST: instance_data,
2258
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2259
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
2260
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2261
      constants.SS_UID_POOL: uid_pool,
2262
      constants.SS_NODEGROUPS: nodegroups_data,
2263
      constants.SS_NETWORKS: networks_data,
2264
      }
2265
    bad_values = [(k, v) for k, v in ssconf_values.items()
2266
                  if not isinstance(v, (str, basestring))]
2267
    if bad_values:
2268
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2269
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2270
                                      " values: %s" % err)
2271
    return ssconf_values
2272

    
2273
  @locking.ssynchronized(_config_lock, shared=1)
2274
  def GetSsconfValues(self):
2275
    """Wrapper using lock around _UnlockedGetSsconf().
2276

2277
    """
2278
    return self._UnlockedGetSsconfValues()
2279

    
2280
  @locking.ssynchronized(_config_lock, shared=1)
2281
  def GetVGName(self):
2282
    """Return the volume group name.
2283

2284
    """
2285
    return self._config_data.cluster.volume_group_name
2286

    
2287
  @locking.ssynchronized(_config_lock)
2288
  def SetVGName(self, vg_name):
2289
    """Set the volume group name.
2290

2291
    """
2292
    self._config_data.cluster.volume_group_name = vg_name
2293
    self._config_data.cluster.serial_no += 1
2294
    self._WriteConfig()
2295

    
2296
  @locking.ssynchronized(_config_lock, shared=1)
2297
  def GetDRBDHelper(self):
2298
    """Return DRBD usermode helper.
2299

2300
    """
2301
    return self._config_data.cluster.drbd_usermode_helper
2302

    
2303
  @locking.ssynchronized(_config_lock)
2304
  def SetDRBDHelper(self, drbd_helper):
2305
    """Set DRBD usermode helper.
2306

2307
    """
2308
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2309
    self._config_data.cluster.serial_no += 1
2310
    self._WriteConfig()
2311

    
2312
  @locking.ssynchronized(_config_lock, shared=1)
2313
  def GetMACPrefix(self):
2314
    """Return the mac prefix.
2315

2316
    """
2317
    return self._config_data.cluster.mac_prefix
2318

    
2319
  @locking.ssynchronized(_config_lock, shared=1)
2320
  def GetClusterInfo(self):
2321
    """Returns information about the cluster
2322

2323
    @rtype: L{objects.Cluster}
2324
    @return: the cluster object
2325

2326
    """
2327
    return self._config_data.cluster
2328

    
2329
  @locking.ssynchronized(_config_lock, shared=1)
2330
  def HasAnyDiskOfType(self, dev_type):
2331
    """Check if in there is at disk of the given type in the configuration.
2332

2333
    """
2334
    return self._config_data.HasAnyDiskOfType(dev_type)
2335

    
2336
  @locking.ssynchronized(_config_lock)
2337
  def Update(self, target, feedback_fn, ec_id=None):
2338
    """Notify function to be called after updates.
2339

2340
    This function must be called when an object (as returned by
2341
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2342
    caller wants the modifications saved to the backing store. Note
2343
    that all modified objects will be saved, but the target argument
2344
    is the one the caller wants to ensure that it's saved.
2345

2346
    @param target: an instance of either L{objects.Cluster},
2347
        L{objects.Node} or L{objects.Instance} which is existing in
2348
        the cluster
2349
    @param feedback_fn: Callable feedback function
2350

2351
    """
2352
    if self._config_data is None:
2353
      raise errors.ProgrammerError("Configuration file not read,"
2354
                                   " cannot save.")
2355
    update_serial = False
2356
    if isinstance(target, objects.Cluster):
2357
      test = target == self._config_data.cluster
2358
    elif isinstance(target, objects.Node):
2359
      test = target in self._config_data.nodes.values()
2360
      update_serial = True
2361
    elif isinstance(target, objects.Instance):
2362
      test = target in self._config_data.instances.values()
2363
    elif isinstance(target, objects.NodeGroup):
2364
      test = target in self._config_data.nodegroups.values()
2365
    elif isinstance(target, objects.Network):
2366
      test = target in self._config_data.networks.values()
2367
    else:
2368
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2369
                                   " ConfigWriter.Update" % type(target))
2370
    if not test:
2371
      raise errors.ConfigurationError("Configuration updated since object"
2372
                                      " has been read or unknown object")
2373
    target.serial_no += 1
2374
    target.mtime = now = time.time()
2375

    
2376
    if update_serial:
2377
      # for node updates, we need to increase the cluster serial too
2378
      self._config_data.cluster.serial_no += 1
2379
      self._config_data.cluster.mtime = now
2380

    
2381
    if isinstance(target, objects.Instance):
2382
      self._UnlockedReleaseDRBDMinors(target.name)
2383

    
2384
    if ec_id is not None:
2385
      # Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
2386
      self._UnlockedCommitTemporaryIps(ec_id)
2387

    
2388
    self._WriteConfig(feedback_fn=feedback_fn)
2389

    
2390
  @locking.ssynchronized(_config_lock)
2391
  def DropECReservations(self, ec_id):
2392
    """Drop per-execution-context reservations
2393

2394
    """
2395
    for rm in self._all_rms:
2396
      rm.DropECReservations(ec_id)
2397

    
2398
  @locking.ssynchronized(_config_lock, shared=1)
2399
  def GetAllNetworksInfo(self):
2400
    """Get configuration info of all the networks.
2401

2402
    """
2403
    return dict(self._config_data.networks)
2404

    
2405
  def _UnlockedGetNetworkList(self):
2406
    """Get the list of networks.
2407

2408
    This function is for internal use, when the config lock is already held.
2409

2410
    """
2411
    return self._config_data.networks.keys()
2412

    
2413
  @locking.ssynchronized(_config_lock, shared=1)
2414
  def GetNetworkList(self):
2415
    """Get the list of networks.
2416

2417
    @return: array of networks, ex. ["main", "vlan100", "200]
2418

2419
    """
2420
    return self._UnlockedGetNetworkList()
2421

    
2422
  @locking.ssynchronized(_config_lock, shared=1)
2423
  def GetNetworkNames(self):
2424
    """Get a list of network names
2425

2426
    """
2427
    names = [net.name
2428
             for net in self._config_data.networks.values()]
2429
    return names
2430

    
2431
  def _UnlockedGetNetwork(self, uuid):
2432
    """Returns information about a network.
2433

2434
    This function is for internal use, when the config lock is already held.
2435

2436
    """
2437
    if uuid not in self._config_data.networks:
2438
      return None
2439

    
2440
    return self._config_data.networks[uuid]
2441

    
2442
  @locking.ssynchronized(_config_lock, shared=1)
2443
  def GetNetwork(self, uuid):
2444
    """Returns information about a network.
2445

2446
    It takes the information from the configuration file.
2447

2448
    @param uuid: UUID of the network
2449

2450
    @rtype: L{objects.Network}
2451
    @return: the network object
2452

2453
    """
2454
    return self._UnlockedGetNetwork(uuid)
2455

    
2456
  @locking.ssynchronized(_config_lock)
2457
  def AddNetwork(self, net, ec_id, check_uuid=True):
2458
    """Add a network to the configuration.
2459

2460
    @type net: L{objects.Network}
2461
    @param net: the Network object to add
2462
    @type ec_id: string
2463
    @param ec_id: unique id for the job to use when creating a missing UUID
2464

2465
    """
2466
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2467
    self._WriteConfig()
2468

    
2469
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2470
    """Add a network to the configuration.
2471

2472
    """
2473
    logging.info("Adding network %s to configuration", net.name)
2474

    
2475
    if check_uuid:
2476
      self._EnsureUUID(net, ec_id)
2477

    
2478
    existing_uuid = self._UnlockedLookupNetwork(net.name)
2479
    if existing_uuid:
2480
      raise errors.OpPrereqError("Desired network name '%s' already"
2481
                                 " exists as a network (UUID: %s)" %
2482
                                 (net.name, existing_uuid),
2483
                                 errors.ECODE_EXISTS)
2484
    net.serial_no = 1
2485
    self._config_data.networks[net.uuid] = net
2486
    self._config_data.cluster.serial_no += 1
2487

    
2488
  def _UnlockedLookupNetwork(self, target):
2489
    """Lookup a network's UUID.
2490

2491
    @type target: string
2492
    @param target: network name or UUID
2493
    @rtype: string
2494
    @return: network UUID
2495
    @raises errors.OpPrereqError: when the target network cannot be found
2496

2497
    """
2498
    if target in self._config_data.networks:
2499
      return target
2500
    for net in self._config_data.networks.values():
2501
      if net.name == target:
2502
        return net.uuid
2503
    return None
2504

    
2505
  @locking.ssynchronized(_config_lock, shared=1)
2506
  def LookupNetwork(self, target):
2507
    """Lookup a network's UUID.
2508

2509
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2510

2511
    @type target: string
2512
    @param target: network name or UUID
2513
    @rtype: string
2514
    @return: network UUID
2515

2516
    """
2517
    return self._UnlockedLookupNetwork(target)
2518

    
2519
  @locking.ssynchronized(_config_lock)
2520
  def RemoveNetwork(self, network_uuid):
2521
    """Remove a network from the configuration.
2522

2523
    @type network_uuid: string
2524
    @param network_uuid: the UUID of the network to remove
2525

2526
    """
2527
    logging.info("Removing network %s from configuration", network_uuid)
2528

    
2529
    if network_uuid not in self._config_data.networks:
2530
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2531

    
2532
    del self._config_data.networks[network_uuid]
2533
    self._config_data.cluster.serial_no += 1
2534
    self._WriteConfig()
2535

    
2536
  def _UnlockedGetGroupNetParams(self, net, node):
2537
    """Get the netparams (mode, link) of a network.
2538

2539
    Get a network's netparams for a given node.
2540

2541
    @type net: string
2542
    @param net: network name
2543
    @type node: string
2544
    @param node: node name
2545
    @rtype: dict or None
2546
    @return: netparams
2547

2548
    """
2549
    net_uuid = self._UnlockedLookupNetwork(net)
2550
    if net_uuid is None:
2551
      return None
2552

    
2553
    node_info = self._UnlockedGetNodeInfo(node)
2554
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2555
    netparams = nodegroup_info.networks.get(net_uuid, None)
2556

    
2557
    return netparams
2558

    
2559
  @locking.ssynchronized(_config_lock, shared=1)
2560
  def GetGroupNetParams(self, net, node):
2561
    """Locking wrapper of _UnlockedGetGroupNetParams()
2562

2563
    """
2564
    return self._UnlockedGetGroupNetParams(net, node)
2565

    
2566
  @locking.ssynchronized(_config_lock, shared=1)
2567
  def CheckIPInNodeGroup(self, ip, node):
2568
    """Check IP uniqueness in nodegroup.
2569

2570
    Check networks that are connected in the node's node group
2571
    if ip is contained in any of them. Used when creating/adding
2572
    a NIC to ensure uniqueness among nodegroups.
2573

2574
    @type ip: string
2575
    @param ip: ip address
2576
    @type node: string
2577
    @param node: node name
2578
    @rtype: (string, dict) or (None, None)
2579
    @return: (network name, netparams)
2580

2581
    """
2582
    if ip is None:
2583
      return (None, None)
2584
    node_info = self._UnlockedGetNodeInfo(node)
2585
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2586
    for net_uuid in nodegroup_info.networks.keys():
2587
      net_info = self._UnlockedGetNetwork(net_uuid)
2588
      pool = network.AddressPool(net_info)
2589
      if pool.Contains(ip):
2590
        return (net_info.name, nodegroup_info.networks[net_uuid])
2591

    
2592
    return (None, None)