Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 1cce2c47

History | View | Annotate | Download (84.5 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
      nobj = self._UnlockedGetNetwork(net_uuid)
280
      if nobj.mac_prefix:
281
        prefix = nobj.mac_prefix
282

    
283
    return prefix
284

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

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

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

    
301
    return GenMac
302

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

307
    This should check the current instances for duplicates.
308

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

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

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

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

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

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

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

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

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

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

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

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

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

363
    This is just a wrapper around _UnlockedReleaseIp.
364

365
    """
366
    net_uuid = self._UnlockedLookupNetwork(net)
367
    self._UnlockedReleaseIp(net_uuid, address, ec_id)
368

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

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

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

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

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

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

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

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

409
    """
410
    net_uuid = self._UnlockedLookupNetwork(net)
411
    return self._UnlockedReserveIp(net_uuid, address, ec_id)
412

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

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

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

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

431
    This checks the current disks for duplicates.
432

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

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

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

    
449
  def _AllIDs(self, include_temporary):
450
    """Compute the list of all UUIDs and names we have.
451

452
    @type include_temporary: boolean
453
    @param include_temporary: whether to include the _temporary_ids set
454
    @rtype: set
455
    @return: a set of IDs
456

457
    """
458
    existing = set()
459
    if include_temporary:
460
      existing.update(self._temporary_ids.GetReserved())
461
    existing.update(self._AllLVs())
462
    existing.update(self._config_data.instances.keys())
463
    existing.update(self._config_data.nodes.keys())
464
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
465
    return existing
466

    
467
  def _GenerateUniqueID(self, ec_id):
468
    """Generate an unique UUID.
469

470
    This checks the current node, instances and disk names for
471
    duplicates.
472

473
    @rtype: string
474
    @return: the unique id
475

476
    """
477
    existing = self._AllIDs(include_temporary=False)
478
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
479

    
480
  @locking.ssynchronized(_config_lock, shared=1)
481
  def GenerateUniqueID(self, ec_id):
482
    """Generate an unique ID.
483

484
    This is just a wrapper over the unlocked version.
485

486
    @type ec_id: string
487
    @param ec_id: unique id for the job to reserve the id to
488

489
    """
490
    return self._GenerateUniqueID(ec_id)
491

    
492
  def _AllMACs(self):
493
    """Return all MACs present in the config.
494

495
    @rtype: list
496
    @return: the list of all MACs
497

498
    """
499
    result = []
500
    for instance in self._config_data.instances.values():
501
      for nic in instance.nics:
502
        result.append(nic.mac)
503

    
504
    return result
505

    
506
  def _AllDRBDSecrets(self):
507
    """Return all DRBD secrets present in the config.
508

509
    @rtype: list
510
    @return: the list of all DRBD secrets
511

512
    """
513
    def helper(disk, result):
514
      """Recursively gather secrets from this disk."""
515
      if disk.dev_type == constants.DT_DRBD8:
516
        result.append(disk.logical_id[5])
517
      if disk.children:
518
        for child in disk.children:
519
          helper(child, result)
520

    
521
    result = []
522
    for instance in self._config_data.instances.values():
523
      for disk in instance.disks:
524
        helper(disk, result)
525

    
526
    return result
527

    
528
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
529
    """Compute duplicate disk IDs
530

531
    @type disk: L{objects.Disk}
532
    @param disk: the disk at which to start searching
533
    @type l_ids: list
534
    @param l_ids: list of current logical ids
535
    @type p_ids: list
536
    @param p_ids: list of current physical ids
537
    @rtype: list
538
    @return: a list of error messages
539

540
    """
541
    result = []
542
    if disk.logical_id is not None:
543
      if disk.logical_id in l_ids:
544
        result.append("duplicate logical id %s" % str(disk.logical_id))
545
      else:
546
        l_ids.append(disk.logical_id)
547
    if disk.physical_id is not None:
548
      if disk.physical_id in p_ids:
549
        result.append("duplicate physical id %s" % str(disk.physical_id))
550
      else:
551
        p_ids.append(disk.physical_id)
552

    
553
    if disk.children:
554
      for child in disk.children:
555
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
556
    return result
557

    
558
  def _UnlockedVerifyConfig(self):
559
    """Verify function.
560

561
    @rtype: list
562
    @return: a list of error messages; a non-empty list signifies
563
        configuration errors
564

565
    """
566
    # pylint: disable=R0914
567
    result = []
568
    seen_macs = []
569
    ports = {}
570
    data = self._config_data
571
    cluster = data.cluster
572
    seen_lids = []
573
    seen_pids = []
574

    
575
    # global cluster checks
576
    if not cluster.enabled_hypervisors:
577
      result.append("enabled hypervisors list doesn't have any entries")
578
    invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
579
    if invalid_hvs:
580
      result.append("enabled hypervisors contains invalid entries: %s" %
581
                    invalid_hvs)
582
    missing_hvp = (set(cluster.enabled_hypervisors) -
583
                   set(cluster.hvparams.keys()))
584
    if missing_hvp:
585
      result.append("hypervisor parameters missing for the enabled"
586
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
587

    
588
    if cluster.master_node not in data.nodes:
589
      result.append("cluster has invalid primary node '%s'" %
590
                    cluster.master_node)
591

    
592
    def _helper(owner, attr, value, template):
593
      try:
594
        utils.ForceDictType(value, template)
595
      except errors.GenericError, err:
596
        result.append("%s has invalid %s: %s" % (owner, attr, err))
597

    
598
    def _helper_nic(owner, params):
599
      try:
600
        objects.NIC.CheckParameterSyntax(params)
601
      except errors.ConfigurationError, err:
602
        result.append("%s has invalid nicparams: %s" % (owner, err))
603

    
604
    def _helper_ipolicy(owner, params, check_std):
605
      try:
606
        objects.InstancePolicy.CheckParameterSyntax(params, check_std)
607
      except errors.ConfigurationError, err:
608
        result.append("%s has invalid instance policy: %s" % (owner, err))
609

    
610
    def _helper_ispecs(owner, params):
611
      for key, value in params.items():
612
        if key in constants.IPOLICY_ISPECS:
613
          fullkey = "ipolicy/" + key
614
          _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
615
        else:
616
          # FIXME: assuming list type
617
          if key in constants.IPOLICY_PARAMETERS:
618
            exp_type = float
619
          else:
620
            exp_type = list
621
          if not isinstance(value, exp_type):
622
            result.append("%s has invalid instance policy: for %s,"
623
                          " expecting %s, got %s" %
624
                          (owner, key, exp_type.__name__, type(value)))
625

    
626
    # check cluster parameters
627
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
628
            constants.BES_PARAMETER_TYPES)
629
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
630
            constants.NICS_PARAMETER_TYPES)
631
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
632
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
633
            constants.NDS_PARAMETER_TYPES)
634
    _helper_ipolicy("cluster", cluster.SimpleFillIPolicy({}), True)
635
    _helper_ispecs("cluster", cluster.SimpleFillIPolicy({}))
636

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

    
663
      # parameter checks
664
      if instance.beparams:
665
        _helper("instance %s" % instance.name, "beparams",
666
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
667

    
668
      # gather the drbd ports for duplicate checks
669
      for (idx, dsk) in enumerate(instance.disks):
670
        if dsk.dev_type in constants.LDS_DRBD:
671
          tcp_port = dsk.logical_id[2]
672
          if tcp_port not in ports:
673
            ports[tcp_port] = []
674
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
675
      # gather network port reservation
676
      net_port = getattr(instance, "network_port", None)
677
      if net_port is not None:
678
        if net_port not in ports:
679
          ports[net_port] = []
680
        ports[net_port].append((instance.name, "network port"))
681

    
682
      # instance disk verify
683
      for idx, disk in enumerate(instance.disks):
684
        result.extend(["instance '%s' disk %d error: %s" %
685
                       (instance.name, idx, msg) for msg in disk.Verify()])
686
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
687

    
688
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
689
      if wrong_names:
690
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
691
                         (idx, exp_name, actual_name))
692
                        for (idx, exp_name, actual_name) in wrong_names)
693

    
694
        result.append("Instance '%s' has wrongly named disks: %s" %
695
                      (instance.name, tmp))
696

    
697
    # cluster-wide pool of free ports
698
    for free_port in cluster.tcpudp_port_pool:
699
      if free_port not in ports:
700
        ports[free_port] = []
701
      ports[free_port].append(("cluster", "port marked as free"))
702

    
703
    # compute tcp/udp duplicate ports
704
    keys = ports.keys()
705
    keys.sort()
706
    for pnum in keys:
707
      pdata = ports[pnum]
708
      if len(pdata) > 1:
709
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
710
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
711

    
712
    # highest used tcp port check
713
    if keys:
714
      if keys[-1] > cluster.highest_used_port:
715
        result.append("Highest used port mismatch, saved %s, computed %s" %
716
                      (cluster.highest_used_port, keys[-1]))
717

    
718
    if not data.nodes[cluster.master_node].master_candidate:
719
      result.append("Master node is not a master candidate")
720

    
721
    # master candidate checks
722
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
723
    if mc_now < mc_max:
724
      result.append("Not enough master candidates: actual %d, target %d" %
725
                    (mc_now, mc_max))
726

    
727
    # node checks
728
    for node_name, node in data.nodes.items():
729
      if node.name != node_name:
730
        result.append("Node '%s' is indexed by wrong name '%s'" %
731
                      (node.name, node_name))
732
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
733
        result.append("Node %s state is invalid: master_candidate=%s,"
734
                      " drain=%s, offline=%s" %
735
                      (node.name, node.master_candidate, node.drained,
736
                       node.offline))
737
      if node.group not in data.nodegroups:
738
        result.append("Node '%s' has invalid group '%s'" %
739
                      (node.name, node.group))
740
      else:
741
        _helper("node %s" % node.name, "ndparams",
742
                cluster.FillND(node, data.nodegroups[node.group]),
743
                constants.NDS_PARAMETER_TYPES)
744

    
745
    # nodegroups checks
746
    nodegroups_names = set()
747
    for nodegroup_uuid in data.nodegroups:
748
      nodegroup = data.nodegroups[nodegroup_uuid]
749
      if nodegroup.uuid != nodegroup_uuid:
750
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
751
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
752
      if utils.UUID_RE.match(nodegroup.name.lower()):
753
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
754
                      (nodegroup.name, nodegroup.uuid))
755
      if nodegroup.name in nodegroups_names:
756
        result.append("duplicate node group name '%s'" % nodegroup.name)
757
      else:
758
        nodegroups_names.add(nodegroup.name)
759
      group_name = "group %s" % nodegroup.name
760
      _helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy),
761
                      False)
762
      _helper_ispecs(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy))
763
      if nodegroup.ndparams:
764
        _helper(group_name, "ndparams",
765
                cluster.SimpleFillND(nodegroup.ndparams),
766
                constants.NDS_PARAMETER_TYPES)
767

    
768
    # drbd minors check
769
    _, duplicates = self._UnlockedComputeDRBDMap()
770
    for node, minor, instance_a, instance_b in duplicates:
771
      result.append("DRBD minor %d on node %s is assigned twice to instances"
772
                    " %s and %s" % (minor, node, instance_a, instance_b))
773

    
774
    # IP checks
775
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
776
    ips = {}
777

    
778
    def _AddIpAddress(ip, name):
779
      ips.setdefault(ip, []).append(name)
780

    
781
    _AddIpAddress(cluster.master_ip, "cluster_ip")
782

    
783
    for node in data.nodes.values():
784
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
785
      if node.secondary_ip != node.primary_ip:
786
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
787

    
788
    for instance in data.instances.values():
789
      for idx, nic in enumerate(instance.nics):
790
        if nic.ip is None:
791
          continue
792

    
793
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
794
        nic_mode = nicparams[constants.NIC_MODE]
795
        nic_link = nicparams[constants.NIC_LINK]
796

    
797
        if nic_mode == constants.NIC_MODE_BRIDGED:
798
          link = "bridge:%s" % nic_link
799
        elif nic_mode == constants.NIC_MODE_ROUTED:
800
          link = "route:%s" % nic_link
801
        else:
802
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
803

    
804
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
805
                      "instance:%s/nic:%d" % (instance.name, idx))
806

    
807
    for ip, owners in ips.items():
808
      if len(owners) > 1:
809
        result.append("IP address %s is used by multiple owners: %s" %
810
                      (ip, utils.CommaJoin(owners)))
811

    
812
    return result
813

    
814
  @locking.ssynchronized(_config_lock, shared=1)
815
  def VerifyConfig(self):
816
    """Verify function.
817

818
    This is just a wrapper over L{_UnlockedVerifyConfig}.
819

820
    @rtype: list
821
    @return: a list of error messages; a non-empty list signifies
822
        configuration errors
823

824
    """
825
    return self._UnlockedVerifyConfig()
826

    
827
  def _UnlockedSetDiskID(self, disk, node_name):
828
    """Convert the unique ID to the ID needed on the target nodes.
829

830
    This is used only for drbd, which needs ip/port configuration.
831

832
    The routine descends down and updates its children also, because
833
    this helps when the only the top device is passed to the remote
834
    node.
835

836
    This function is for internal use, when the config lock is already held.
837

838
    """
839
    if disk.children:
840
      for child in disk.children:
841
        self._UnlockedSetDiskID(child, node_name)
842

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

    
865
  @locking.ssynchronized(_config_lock)
866
  def SetDiskID(self, disk, node_name):
867
    """Convert the unique ID to the ID needed on the target nodes.
868

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

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

875
    """
876
    return self._UnlockedSetDiskID(disk, node_name)
877

    
878
  @locking.ssynchronized(_config_lock)
879
  def AddTcpUdpPort(self, port):
880
    """Adds a new port to the available port pool.
881

882
    @warning: this method does not "flush" the configuration (via
883
        L{_WriteConfig}); callers should do that themselves once the
884
        configuration is stable
885

886
    """
887
    if not isinstance(port, int):
888
      raise errors.ProgrammerError("Invalid type passed for port")
889

    
890
    self._config_data.cluster.tcpudp_port_pool.add(port)
891

    
892
  @locking.ssynchronized(_config_lock, shared=1)
893
  def GetPortList(self):
894
    """Returns a copy of the current port list.
895

896
    """
897
    return self._config_data.cluster.tcpudp_port_pool.copy()
898

    
899
  @locking.ssynchronized(_config_lock)
900
  def AllocatePort(self):
901
    """Allocate a port.
902

903
    The port will be taken from the available port pool or from the
904
    default port range (and in this case we increase
905
    highest_used_port).
906

907
    """
908
    # If there are TCP/IP ports configured, we use them first.
909
    if self._config_data.cluster.tcpudp_port_pool:
910
      port = self._config_data.cluster.tcpudp_port_pool.pop()
911
    else:
912
      port = self._config_data.cluster.highest_used_port + 1
913
      if port >= constants.LAST_DRBD_PORT:
914
        raise errors.ConfigurationError("The highest used port is greater"
915
                                        " than %s. Aborting." %
916
                                        constants.LAST_DRBD_PORT)
917
      self._config_data.cluster.highest_used_port = port
918

    
919
    self._WriteConfig()
920
    return port
921

    
922
  def _UnlockedComputeDRBDMap(self):
923
    """Compute the used DRBD minor/nodes.
924

925
    @rtype: (dict, list)
926
    @return: dictionary of node_name: dict of minor: instance_name;
927
        the returned dict will have all the nodes in it (even if with
928
        an empty list), and a list of duplicates; if the duplicates
929
        list is not empty, the configuration is corrupted and its caller
930
        should raise an exception
931

932
    """
933
    def _AppendUsedPorts(instance_name, disk, used):
934
      duplicates = []
935
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
936
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
937
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
938
          assert node in used, ("Node '%s' of instance '%s' not found"
939
                                " in node list" % (node, instance_name))
940
          if port in used[node]:
941
            duplicates.append((node, port, instance_name, used[node][port]))
942
          else:
943
            used[node][port] = instance_name
944
      if disk.children:
945
        for child in disk.children:
946
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
947
      return duplicates
948

    
949
    duplicates = []
950
    my_dict = dict((node, {}) for node in self._config_data.nodes)
951
    for instance in self._config_data.instances.itervalues():
952
      for disk in instance.disks:
953
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
954
    for (node, minor), instance in self._temporary_drbds.iteritems():
955
      if minor in my_dict[node] and my_dict[node][minor] != instance:
956
        duplicates.append((node, minor, instance, my_dict[node][minor]))
957
      else:
958
        my_dict[node][minor] = instance
959
    return my_dict, duplicates
960

    
961
  @locking.ssynchronized(_config_lock)
962
  def ComputeDRBDMap(self):
963
    """Compute the used DRBD minor/nodes.
964

965
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
966

967
    @return: dictionary of node_name: dict of minor: instance_name;
968
        the returned dict will have all the nodes in it (even if with
969
        an empty list).
970

971
    """
972
    d_map, duplicates = self._UnlockedComputeDRBDMap()
973
    if duplicates:
974
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
975
                                      str(duplicates))
976
    return d_map
977

    
978
  @locking.ssynchronized(_config_lock)
979
  def AllocateDRBDMinor(self, nodes, instance):
980
    """Allocate a drbd minor.
981

982
    The free minor will be automatically computed from the existing
983
    devices. A node can be given multiple times in order to allocate
984
    multiple minors. The result is the list of minors, in the same
985
    order as the passed nodes.
986

987
    @type instance: string
988
    @param instance: the instance for which we allocate minors
989

990
    """
991
    assert isinstance(instance, basestring), \
992
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
993

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

    
1034
  def _UnlockedReleaseDRBDMinors(self, instance):
1035
    """Release temporary drbd minors allocated for a given instance.
1036

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

1041
    """
1042
    assert isinstance(instance, basestring), \
1043
           "Invalid argument passed to ReleaseDRBDMinors"
1044
    for key, name in self._temporary_drbds.items():
1045
      if name == instance:
1046
        del self._temporary_drbds[key]
1047

    
1048
  @locking.ssynchronized(_config_lock)
1049
  def ReleaseDRBDMinors(self, instance):
1050
    """Release temporary drbd minors allocated for a given instance.
1051

1052
    This should be called on the error paths, on the success paths
1053
    it's automatically called by the ConfigWriter add and update
1054
    functions.
1055

1056
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1057

1058
    @type instance: string
1059
    @param instance: the instance for which temporary minors should be
1060
                     released
1061

1062
    """
1063
    self._UnlockedReleaseDRBDMinors(instance)
1064

    
1065
  @locking.ssynchronized(_config_lock, shared=1)
1066
  def GetConfigVersion(self):
1067
    """Get the configuration version.
1068

1069
    @return: Config version
1070

1071
    """
1072
    return self._config_data.version
1073

    
1074
  @locking.ssynchronized(_config_lock, shared=1)
1075
  def GetClusterName(self):
1076
    """Get cluster name.
1077

1078
    @return: Cluster name
1079

1080
    """
1081
    return self._config_data.cluster.cluster_name
1082

    
1083
  @locking.ssynchronized(_config_lock, shared=1)
1084
  def GetMasterNode(self):
1085
    """Get the hostname of the master node for this cluster.
1086

1087
    @return: Master hostname
1088

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

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

1096
    @return: Master IP
1097

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

    
1101
  @locking.ssynchronized(_config_lock, shared=1)
1102
  def GetMasterNetdev(self):
1103
    """Get the master network device for this cluster.
1104

1105
    """
1106
    return self._config_data.cluster.master_netdev
1107

    
1108
  @locking.ssynchronized(_config_lock, shared=1)
1109
  def GetMasterNetmask(self):
1110
    """Get the netmask of the master node for this cluster.
1111

1112
    """
1113
    return self._config_data.cluster.master_netmask
1114

    
1115
  @locking.ssynchronized(_config_lock, shared=1)
1116
  def GetUseExternalMipScript(self):
1117
    """Get flag representing whether to use the external master IP setup script.
1118

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

    
1122
  @locking.ssynchronized(_config_lock, shared=1)
1123
  def GetFileStorageDir(self):
1124
    """Get the file storage dir for this cluster.
1125

1126
    """
1127
    return self._config_data.cluster.file_storage_dir
1128

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

1133
    """
1134
    return self._config_data.cluster.shared_file_storage_dir
1135

    
1136
  @locking.ssynchronized(_config_lock, shared=1)
1137
  def GetHypervisorType(self):
1138
    """Get the hypervisor type for this cluster.
1139

1140
    """
1141
    return self._config_data.cluster.enabled_hypervisors[0]
1142

    
1143
  @locking.ssynchronized(_config_lock, shared=1)
1144
  def GetHostKey(self):
1145
    """Return the rsa hostkey from the config.
1146

1147
    @rtype: string
1148
    @return: the rsa hostkey
1149

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

    
1153
  @locking.ssynchronized(_config_lock, shared=1)
1154
  def GetDefaultIAllocator(self):
1155
    """Get the default instance allocator for this cluster.
1156

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

    
1160
  @locking.ssynchronized(_config_lock, shared=1)
1161
  def GetPrimaryIPFamily(self):
1162
    """Get cluster primary ip family.
1163

1164
    @return: primary ip family
1165

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

    
1169
  @locking.ssynchronized(_config_lock, shared=1)
1170
  def GetMasterNetworkParameters(self):
1171
    """Get network parameters of the master node.
1172

1173
    @rtype: L{object.MasterNetworkParameters}
1174
    @return: network parameters of the master node
1175

1176
    """
1177
    cluster = self._config_data.cluster
1178
    result = objects.MasterNetworkParameters(
1179
      name=cluster.master_node, ip=cluster.master_ip,
1180
      netmask=cluster.master_netmask, netdev=cluster.master_netdev,
1181
      ip_family=cluster.primary_ip_family)
1182

    
1183
    return result
1184

    
1185
  @locking.ssynchronized(_config_lock)
1186
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1187
    """Add a node group to the configuration.
1188

1189
    This method calls group.UpgradeConfig() to fill any missing attributes
1190
    according to their default values.
1191

1192
    @type group: L{objects.NodeGroup}
1193
    @param group: the NodeGroup object to add
1194
    @type ec_id: string
1195
    @param ec_id: unique id for the job to use when creating a missing UUID
1196
    @type check_uuid: bool
1197
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1198
                       it does, ensure that it does not exist in the
1199
                       configuration already
1200

1201
    """
1202
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1203
    self._WriteConfig()
1204

    
1205
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1206
    """Add a node group to the configuration.
1207

1208
    """
1209
    logging.info("Adding node group %s to configuration", group.name)
1210

    
1211
    # Some code might need to add a node group with a pre-populated UUID
1212
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1213
    # the "does this UUID" exist already check.
1214
    if check_uuid:
1215
      self._EnsureUUID(group, ec_id)
1216

    
1217
    try:
1218
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1219
    except errors.OpPrereqError:
1220
      pass
1221
    else:
1222
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1223
                                 " node group (UUID: %s)" %
1224
                                 (group.name, existing_uuid),
1225
                                 errors.ECODE_EXISTS)
1226

    
1227
    group.serial_no = 1
1228
    group.ctime = group.mtime = time.time()
1229
    group.UpgradeConfig()
1230

    
1231
    self._config_data.nodegroups[group.uuid] = group
1232
    self._config_data.cluster.serial_no += 1
1233

    
1234
  @locking.ssynchronized(_config_lock)
1235
  def RemoveNodeGroup(self, group_uuid):
1236
    """Remove a node group from the configuration.
1237

1238
    @type group_uuid: string
1239
    @param group_uuid: the UUID of the node group to remove
1240

1241
    """
1242
    logging.info("Removing node group %s from configuration", group_uuid)
1243

    
1244
    if group_uuid not in self._config_data.nodegroups:
1245
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1246

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

    
1250
    del self._config_data.nodegroups[group_uuid]
1251
    self._config_data.cluster.serial_no += 1
1252
    self._WriteConfig()
1253

    
1254
  def _UnlockedLookupNodeGroup(self, target):
1255
    """Lookup a node group's UUID.
1256

1257
    @type target: string or None
1258
    @param target: group name or UUID or None to look for the default
1259
    @rtype: string
1260
    @return: nodegroup UUID
1261
    @raises errors.OpPrereqError: when the target group cannot be found
1262

1263
    """
1264
    if target is None:
1265
      if len(self._config_data.nodegroups) != 1:
1266
        raise errors.OpPrereqError("More than one node group exists. Target"
1267
                                   " group must be specified explicitly.")
1268
      else:
1269
        return self._config_data.nodegroups.keys()[0]
1270
    if target in self._config_data.nodegroups:
1271
      return target
1272
    for nodegroup in self._config_data.nodegroups.values():
1273
      if nodegroup.name == target:
1274
        return nodegroup.uuid
1275
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1276
                               errors.ECODE_NOENT)
1277

    
1278
  @locking.ssynchronized(_config_lock, shared=1)
1279
  def LookupNodeGroup(self, target):
1280
    """Lookup a node group's UUID.
1281

1282
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1283

1284
    @type target: string or None
1285
    @param target: group name or UUID or None to look for the default
1286
    @rtype: string
1287
    @return: nodegroup UUID
1288

1289
    """
1290
    return self._UnlockedLookupNodeGroup(target)
1291

    
1292
  def _UnlockedGetNodeGroup(self, uuid):
1293
    """Lookup a node group.
1294

1295
    @type uuid: string
1296
    @param uuid: group UUID
1297
    @rtype: L{objects.NodeGroup} or None
1298
    @return: nodegroup object, or None if not found
1299

1300
    """
1301
    if uuid not in self._config_data.nodegroups:
1302
      return None
1303

    
1304
    return self._config_data.nodegroups[uuid]
1305

    
1306
  @locking.ssynchronized(_config_lock, shared=1)
1307
  def GetNodeGroup(self, uuid):
1308
    """Lookup a node group.
1309

1310
    @type uuid: string
1311
    @param uuid: group UUID
1312
    @rtype: L{objects.NodeGroup} or None
1313
    @return: nodegroup object, or None if not found
1314

1315
    """
1316
    return self._UnlockedGetNodeGroup(uuid)
1317

    
1318
  @locking.ssynchronized(_config_lock, shared=1)
1319
  def GetAllNodeGroupsInfo(self):
1320
    """Get the configuration of all node groups.
1321

1322
    """
1323
    return dict(self._config_data.nodegroups)
1324

    
1325
  @locking.ssynchronized(_config_lock, shared=1)
1326
  def GetNodeGroupList(self):
1327
    """Get a list of node groups.
1328

1329
    """
1330
    return self._config_data.nodegroups.keys()
1331

    
1332
  @locking.ssynchronized(_config_lock, shared=1)
1333
  def GetNodeGroupMembersByNodes(self, nodes):
1334
    """Get nodes which are member in the same nodegroups as the given nodes.
1335

1336
    """
1337
    ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1338
    return frozenset(member_name
1339
                     for node_name in nodes
1340
                     for member_name in
1341
                       self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1342

    
1343
  @locking.ssynchronized(_config_lock, shared=1)
1344
  def GetMultiNodeGroupInfo(self, group_uuids):
1345
    """Get the configuration of multiple node groups.
1346

1347
    @param group_uuids: List of node group UUIDs
1348
    @rtype: list
1349
    @return: List of tuples of (group_uuid, group_info)
1350

1351
    """
1352
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1353

    
1354
  @locking.ssynchronized(_config_lock)
1355
  def AddInstance(self, instance, ec_id):
1356
    """Add an instance to the config.
1357

1358
    This should be used after creating a new instance.
1359

1360
    @type instance: L{objects.Instance}
1361
    @param instance: the instance object
1362

1363
    """
1364
    if not isinstance(instance, objects.Instance):
1365
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1366

    
1367
    if instance.disk_template != constants.DT_DISKLESS:
1368
      all_lvs = instance.MapLVsByNode()
1369
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1370

    
1371
    all_macs = self._AllMACs()
1372
    for nic in instance.nics:
1373
      if nic.mac in all_macs:
1374
        raise errors.ConfigurationError("Cannot add instance %s:"
1375
                                        " MAC address '%s' already in use." %
1376
                                        (instance.name, nic.mac))
1377

    
1378
    self._EnsureUUID(instance, ec_id)
1379

    
1380
    instance.serial_no = 1
1381
    instance.ctime = instance.mtime = time.time()
1382
    self._config_data.instances[instance.name] = instance
1383
    self._config_data.cluster.serial_no += 1
1384
    self._UnlockedReleaseDRBDMinors(instance.name)
1385
    self._UnlockedCommitTemporaryIps(ec_id)
1386
    self._WriteConfig()
1387

    
1388
  def _EnsureUUID(self, item, ec_id):
1389
    """Ensures a given object has a valid UUID.
1390

1391
    @param item: the instance or node to be checked
1392
    @param ec_id: the execution context id for the uuid reservation
1393

1394
    """
1395
    if not item.uuid:
1396
      item.uuid = self._GenerateUniqueID(ec_id)
1397
    elif item.uuid in self._AllIDs(include_temporary=True):
1398
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1399
                                      " in use" % (item.name, item.uuid))
1400

    
1401
  def _SetInstanceStatus(self, instance_name, status):
1402
    """Set the instance's status to a given value.
1403

1404
    """
1405
    assert status in constants.ADMINST_ALL, \
1406
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1407

    
1408
    if instance_name not in self._config_data.instances:
1409
      raise errors.ConfigurationError("Unknown instance '%s'" %
1410
                                      instance_name)
1411
    instance = self._config_data.instances[instance_name]
1412
    if instance.admin_state != status:
1413
      instance.admin_state = status
1414
      instance.serial_no += 1
1415
      instance.mtime = time.time()
1416
      self._WriteConfig()
1417

    
1418
  @locking.ssynchronized(_config_lock)
1419
  def MarkInstanceUp(self, instance_name):
1420
    """Mark the instance status to up in the config.
1421

1422
    """
1423
    self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1424

    
1425
  @locking.ssynchronized(_config_lock)
1426
  def MarkInstanceOffline(self, instance_name):
1427
    """Mark the instance status to down in the config.
1428

1429
    """
1430
    self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1431

    
1432
  @locking.ssynchronized(_config_lock)
1433
  def RemoveInstance(self, instance_name):
1434
    """Remove the instance from the configuration.
1435

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

    
1440
    # If a network port has been allocated to the instance,
1441
    # return it to the pool of free ports.
1442
    inst = self._config_data.instances[instance_name]
1443
    network_port = getattr(inst, "network_port", None)
1444
    if network_port is not None:
1445
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1446

    
1447
    instance = self._UnlockedGetInstanceInfo(instance_name)
1448

    
1449
    for nic in instance.nics:
1450
      if nic.network is not None and nic.ip is not None:
1451
        net_uuid = self._UnlockedLookupNetwork(nic.network)
1452
        # Return all IP addresses to the respective address pools
1453
        self._UnlockedCommitIp(constants.RELEASE_ACTION, net_uuid, nic.ip)
1454

    
1455
    del self._config_data.instances[instance_name]
1456
    self._config_data.cluster.serial_no += 1
1457
    self._WriteConfig()
1458

    
1459
  @locking.ssynchronized(_config_lock)
1460
  def RenameInstance(self, old_name, new_name):
1461
    """Rename an instance.
1462

1463
    This needs to be done in ConfigWriter and not by RemoveInstance
1464
    combined with AddInstance as only we can guarantee an atomic
1465
    rename.
1466

1467
    """
1468
    if old_name not in self._config_data.instances:
1469
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1470

    
1471
    # Operate on a copy to not loose instance object in case of a failure
1472
    inst = self._config_data.instances[old_name].Copy()
1473
    inst.name = new_name
1474

    
1475
    for (idx, disk) in enumerate(inst.disks):
1476
      if disk.dev_type == constants.LD_FILE:
1477
        # rename the file paths in logical and physical id
1478
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1479
        disk.logical_id = (disk.logical_id[0],
1480
                           utils.PathJoin(file_storage_dir, inst.name,
1481
                                          "disk%s" % idx))
1482
        disk.physical_id = disk.logical_id
1483

    
1484
    # Actually replace instance object
1485
    del self._config_data.instances[old_name]
1486
    self._config_data.instances[inst.name] = inst
1487

    
1488
    # Force update of ssconf files
1489
    self._config_data.cluster.serial_no += 1
1490

    
1491
    self._WriteConfig()
1492

    
1493
  @locking.ssynchronized(_config_lock)
1494
  def MarkInstanceDown(self, instance_name):
1495
    """Mark the status of an instance to down in the configuration.
1496

1497
    """
1498
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1499

    
1500
  def _UnlockedGetInstanceList(self):
1501
    """Get the list of instances.
1502

1503
    This function is for internal use, when the config lock is already held.
1504

1505
    """
1506
    return self._config_data.instances.keys()
1507

    
1508
  @locking.ssynchronized(_config_lock, shared=1)
1509
  def GetInstanceList(self):
1510
    """Get the list of instances.
1511

1512
    @return: array of instances, ex. ['instance2.example.com',
1513
        'instance1.example.com']
1514

1515
    """
1516
    return self._UnlockedGetInstanceList()
1517

    
1518
  def ExpandInstanceName(self, short_name):
1519
    """Attempt to expand an incomplete instance name.
1520

1521
    """
1522
    # Locking is done in L{ConfigWriter.GetInstanceList}
1523
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1524

    
1525
  def _UnlockedGetInstanceInfo(self, instance_name):
1526
    """Returns information about an instance.
1527

1528
    This function is for internal use, when the config lock is already held.
1529

1530
    """
1531
    if instance_name not in self._config_data.instances:
1532
      return None
1533

    
1534
    return self._config_data.instances[instance_name]
1535

    
1536
  @locking.ssynchronized(_config_lock, shared=1)
1537
  def GetInstanceInfo(self, instance_name):
1538
    """Returns information about an instance.
1539

1540
    It takes the information from the configuration file. Other information of
1541
    an instance are taken from the live systems.
1542

1543
    @param instance_name: name of the instance, e.g.
1544
        I{instance1.example.com}
1545

1546
    @rtype: L{objects.Instance}
1547
    @return: the instance object
1548

1549
    """
1550
    return self._UnlockedGetInstanceInfo(instance_name)
1551

    
1552
  @locking.ssynchronized(_config_lock, shared=1)
1553
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1554
    """Returns set of node group UUIDs for instance's nodes.
1555

1556
    @rtype: frozenset
1557

1558
    """
1559
    instance = self._UnlockedGetInstanceInfo(instance_name)
1560
    if not instance:
1561
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1562

    
1563
    if primary_only:
1564
      nodes = [instance.primary_node]
1565
    else:
1566
      nodes = instance.all_nodes
1567

    
1568
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1569
                     for node_name in nodes)
1570

    
1571
  @locking.ssynchronized(_config_lock, shared=1)
1572
  def GetMultiInstanceInfo(self, instances):
1573
    """Get the configuration of multiple instances.
1574

1575
    @param instances: list of instance names
1576
    @rtype: list
1577
    @return: list of tuples (instance, instance_info), where
1578
        instance_info is what would GetInstanceInfo return for the
1579
        node, while keeping the original order
1580

1581
    """
1582
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1583

    
1584
  @locking.ssynchronized(_config_lock, shared=1)
1585
  def GetAllInstancesInfo(self):
1586
    """Get the configuration of all instances.
1587

1588
    @rtype: dict
1589
    @return: dict of (instance, instance_info), where instance_info is what
1590
              would GetInstanceInfo return for the node
1591

1592
    """
1593
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1594
                    for instance in self._UnlockedGetInstanceList()])
1595
    return my_dict
1596

    
1597
  @locking.ssynchronized(_config_lock, shared=1)
1598
  def GetInstancesInfoByFilter(self, filter_fn):
1599
    """Get instance configuration with a filter.
1600

1601
    @type filter_fn: callable
1602
    @param filter_fn: Filter function receiving instance object as parameter,
1603
      returning boolean. Important: this function is called while the
1604
      configuration locks is held. It must not do any complex work or call
1605
      functions potentially leading to a deadlock. Ideally it doesn't call any
1606
      other functions and just compares instance attributes.
1607

1608
    """
1609
    return dict((name, inst)
1610
                for (name, inst) in self._config_data.instances.items()
1611
                if filter_fn(inst))
1612

    
1613
  @locking.ssynchronized(_config_lock)
1614
  def AddNode(self, node, ec_id):
1615
    """Add a node to the configuration.
1616

1617
    @type node: L{objects.Node}
1618
    @param node: a Node instance
1619

1620
    """
1621
    logging.info("Adding node %s to configuration", node.name)
1622

    
1623
    self._EnsureUUID(node, ec_id)
1624

    
1625
    node.serial_no = 1
1626
    node.ctime = node.mtime = time.time()
1627
    self._UnlockedAddNodeToGroup(node.name, node.group)
1628
    self._config_data.nodes[node.name] = node
1629
    self._config_data.cluster.serial_no += 1
1630
    self._WriteConfig()
1631

    
1632
  @locking.ssynchronized(_config_lock)
1633
  def RemoveNode(self, node_name):
1634
    """Remove a node from the configuration.
1635

1636
    """
1637
    logging.info("Removing node %s from configuration", node_name)
1638

    
1639
    if node_name not in self._config_data.nodes:
1640
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1641

    
1642
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1643
    del self._config_data.nodes[node_name]
1644
    self._config_data.cluster.serial_no += 1
1645
    self._WriteConfig()
1646

    
1647
  def ExpandNodeName(self, short_name):
1648
    """Attempt to expand an incomplete node name.
1649

1650
    """
1651
    # Locking is done in L{ConfigWriter.GetNodeList}
1652
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1653

    
1654
  def _UnlockedGetNodeInfo(self, node_name):
1655
    """Get the configuration of a node, as stored in the config.
1656

1657
    This function is for internal use, when the config lock is already
1658
    held.
1659

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

1662
    @rtype: L{objects.Node}
1663
    @return: the node object
1664

1665
    """
1666
    if node_name not in self._config_data.nodes:
1667
      return None
1668

    
1669
    return self._config_data.nodes[node_name]
1670

    
1671
  @locking.ssynchronized(_config_lock, shared=1)
1672
  def GetNodeInfo(self, node_name):
1673
    """Get the configuration of a node, as stored in the config.
1674

1675
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1676

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

1679
    @rtype: L{objects.Node}
1680
    @return: the node object
1681

1682
    """
1683
    return self._UnlockedGetNodeInfo(node_name)
1684

    
1685
  @locking.ssynchronized(_config_lock, shared=1)
1686
  def GetNodeInstances(self, node_name):
1687
    """Get the instances of a node, as stored in the config.
1688

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

1691
    @rtype: (list, list)
1692
    @return: a tuple with two lists: the primary and the secondary instances
1693

1694
    """
1695
    pri = []
1696
    sec = []
1697
    for inst in self._config_data.instances.values():
1698
      if inst.primary_node == node_name:
1699
        pri.append(inst.name)
1700
      if node_name in inst.secondary_nodes:
1701
        sec.append(inst.name)
1702
    return (pri, sec)
1703

    
1704
  @locking.ssynchronized(_config_lock, shared=1)
1705
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1706
    """Get the instances of a node group.
1707

1708
    @param uuid: Node group UUID
1709
    @param primary_only: Whether to only consider primary nodes
1710
    @rtype: frozenset
1711
    @return: List of instance names in node group
1712

1713
    """
1714
    if primary_only:
1715
      nodes_fn = lambda inst: [inst.primary_node]
1716
    else:
1717
      nodes_fn = lambda inst: inst.all_nodes
1718

    
1719
    return frozenset(inst.name
1720
                     for inst in self._config_data.instances.values()
1721
                     for node_name in nodes_fn(inst)
1722
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1723

    
1724
  def _UnlockedGetNodeList(self):
1725
    """Return the list of nodes which are in the configuration.
1726

1727
    This function is for internal use, when the config lock is already
1728
    held.
1729

1730
    @rtype: list
1731

1732
    """
1733
    return self._config_data.nodes.keys()
1734

    
1735
  @locking.ssynchronized(_config_lock, shared=1)
1736
  def GetNodeList(self):
1737
    """Return the list of nodes which are in the configuration.
1738

1739
    """
1740
    return self._UnlockedGetNodeList()
1741

    
1742
  def _UnlockedGetOnlineNodeList(self):
1743
    """Return the list of nodes which are online.
1744

1745
    """
1746
    all_nodes = [self._UnlockedGetNodeInfo(node)
1747
                 for node in self._UnlockedGetNodeList()]
1748
    return [node.name for node in all_nodes if not node.offline]
1749

    
1750
  @locking.ssynchronized(_config_lock, shared=1)
1751
  def GetOnlineNodeList(self):
1752
    """Return the list of nodes which are online.
1753

1754
    """
1755
    return self._UnlockedGetOnlineNodeList()
1756

    
1757
  @locking.ssynchronized(_config_lock, shared=1)
1758
  def GetVmCapableNodeList(self):
1759
    """Return the list of nodes which are not vm capable.
1760

1761
    """
1762
    all_nodes = [self._UnlockedGetNodeInfo(node)
1763
                 for node in self._UnlockedGetNodeList()]
1764
    return [node.name for node in all_nodes if node.vm_capable]
1765

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

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

    
1775
  @locking.ssynchronized(_config_lock, shared=1)
1776
  def GetMultiNodeInfo(self, nodes):
1777
    """Get the configuration of multiple nodes.
1778

1779
    @param nodes: list of node names
1780
    @rtype: list
1781
    @return: list of tuples of (node, node_info), where node_info is
1782
        what would GetNodeInfo return for the node, in the original
1783
        order
1784

1785
    """
1786
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1787

    
1788
  @locking.ssynchronized(_config_lock, shared=1)
1789
  def GetAllNodesInfo(self):
1790
    """Get the configuration of all nodes.
1791

1792
    @rtype: dict
1793
    @return: dict of (node, node_info), where node_info is what
1794
              would GetNodeInfo return for the node
1795

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

    
1799
  def _UnlockedGetAllNodesInfo(self):
1800
    """Gets configuration of all nodes.
1801

1802
    @note: See L{GetAllNodesInfo}
1803

1804
    """
1805
    return dict([(node, self._UnlockedGetNodeInfo(node))
1806
                 for node in self._UnlockedGetNodeList()])
1807

    
1808
  @locking.ssynchronized(_config_lock, shared=1)
1809
  def GetNodeGroupsFromNodes(self, nodes):
1810
    """Returns groups for a list of nodes.
1811

1812
    @type nodes: list of string
1813
    @param nodes: List of node names
1814
    @rtype: frozenset
1815

1816
    """
1817
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1818

    
1819
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1820
    """Get the number of current and maximum desired and possible candidates.
1821

1822
    @type exceptions: list
1823
    @param exceptions: if passed, list of nodes that should be ignored
1824
    @rtype: tuple
1825
    @return: tuple of (current, desired and possible, possible)
1826

1827
    """
1828
    mc_now = mc_should = mc_max = 0
1829
    for node in self._config_data.nodes.values():
1830
      if exceptions and node.name in exceptions:
1831
        continue
1832
      if not (node.offline or node.drained) and node.master_capable:
1833
        mc_max += 1
1834
      if node.master_candidate:
1835
        mc_now += 1
1836
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1837
    return (mc_now, mc_should, mc_max)
1838

    
1839
  @locking.ssynchronized(_config_lock, shared=1)
1840
  def GetMasterCandidateStats(self, exceptions=None):
1841
    """Get the number of current and maximum possible candidates.
1842

1843
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1844

1845
    @type exceptions: list
1846
    @param exceptions: if passed, list of nodes that should be ignored
1847
    @rtype: tuple
1848
    @return: tuple of (current, max)
1849

1850
    """
1851
    return self._UnlockedGetMasterCandidateStats(exceptions)
1852

    
1853
  @locking.ssynchronized(_config_lock)
1854
  def MaintainCandidatePool(self, exceptions):
1855
    """Try to grow the candidate pool to the desired size.
1856

1857
    @type exceptions: list
1858
    @param exceptions: if passed, list of nodes that should be ignored
1859
    @rtype: list
1860
    @return: list with the adjusted nodes (L{objects.Node} instances)
1861

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

    
1887
    return mod_list
1888

    
1889
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1890
    """Add a given node to the specified group.
1891

1892
    """
1893
    if nodegroup_uuid not in self._config_data.nodegroups:
1894
      # This can happen if a node group gets deleted between its lookup and
1895
      # when we're adding the first node to it, since we don't keep a lock in
1896
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1897
      # is not found anymore.
1898
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1899
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1900
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1901

    
1902
  def _UnlockedRemoveNodeFromGroup(self, node):
1903
    """Remove a given node from its group.
1904

1905
    """
1906
    nodegroup = node.group
1907
    if nodegroup not in self._config_data.nodegroups:
1908
      logging.warning("Warning: node '%s' has unknown node group '%s'"
1909
                      " (while being removed from it)", node.name, nodegroup)
1910
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1911
    if node.name not in nodegroup_obj.members:
1912
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
1913
                      " (while being removed from it)", node.name, nodegroup)
1914
    else:
1915
      nodegroup_obj.members.remove(node.name)
1916

    
1917
  @locking.ssynchronized(_config_lock)
1918
  def AssignGroupNodes(self, mods):
1919
    """Changes the group of a number of nodes.
1920

1921
    @type mods: list of tuples; (node name, new group UUID)
1922
    @param mods: Node membership modifications
1923

1924
    """
1925
    groups = self._config_data.nodegroups
1926
    nodes = self._config_data.nodes
1927

    
1928
    resmod = []
1929

    
1930
    # Try to resolve names/UUIDs first
1931
    for (node_name, new_group_uuid) in mods:
1932
      try:
1933
        node = nodes[node_name]
1934
      except KeyError:
1935
        raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1936

    
1937
      if node.group == new_group_uuid:
1938
        # Node is being assigned to its current group
1939
        logging.debug("Node '%s' was assigned to its current group (%s)",
1940
                      node_name, node.group)
1941
        continue
1942

    
1943
      # Try to find current group of node
1944
      try:
1945
        old_group = groups[node.group]
1946
      except KeyError:
1947
        raise errors.ConfigurationError("Unable to find old group '%s'" %
1948
                                        node.group)
1949

    
1950
      # Try to find new group for node
1951
      try:
1952
        new_group = groups[new_group_uuid]
1953
      except KeyError:
1954
        raise errors.ConfigurationError("Unable to find new group '%s'" %
1955
                                        new_group_uuid)
1956

    
1957
      assert node.name in old_group.members, \
1958
        ("Inconsistent configuration: node '%s' not listed in members for its"
1959
         " old group '%s'" % (node.name, old_group.uuid))
1960
      assert node.name not in new_group.members, \
1961
        ("Inconsistent configuration: node '%s' already listed in members for"
1962
         " its new group '%s'" % (node.name, new_group.uuid))
1963

    
1964
      resmod.append((node, old_group, new_group))
1965

    
1966
    # Apply changes
1967
    for (node, old_group, new_group) in resmod:
1968
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
1969
        "Assigning to current group is not possible"
1970

    
1971
      node.group = new_group.uuid
1972

    
1973
      # Update members of involved groups
1974
      if node.name in old_group.members:
1975
        old_group.members.remove(node.name)
1976
      if node.name not in new_group.members:
1977
        new_group.members.append(node.name)
1978

    
1979
    # Update timestamps and serials (only once per node/group object)
1980
    now = time.time()
1981
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
1982
      obj.serial_no += 1
1983
      obj.mtime = now
1984

    
1985
    # Force ssconf update
1986
    self._config_data.cluster.serial_no += 1
1987

    
1988
    self._WriteConfig()
1989

    
1990
  def _BumpSerialNo(self):
1991
    """Bump up the serial number of the config.
1992

1993
    """
1994
    self._config_data.serial_no += 1
1995
    self._config_data.mtime = time.time()
1996

    
1997
  def _AllUUIDObjects(self):
1998
    """Returns all objects with uuid attributes.
1999

2000
    """
2001
    return (self._config_data.instances.values() +
2002
            self._config_data.nodes.values() +
2003
            self._config_data.nodegroups.values() +
2004
            [self._config_data.cluster])
2005

    
2006
  def _OpenConfig(self, accept_foreign):
2007
    """Read the config data from disk.
2008

2009
    """
2010
    raw_data = utils.ReadFile(self._cfg_file)
2011

    
2012
    try:
2013
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
2014
    except Exception, err:
2015
      raise errors.ConfigurationError(err)
2016

    
2017
    # Make sure the configuration has the right version
2018
    _ValidateConfig(data)
2019

    
2020
    if (not hasattr(data, "cluster") or
2021
        not hasattr(data.cluster, "rsahostkeypub")):
2022
      raise errors.ConfigurationError("Incomplete configuration"
2023
                                      " (missing cluster.rsahostkeypub)")
2024

    
2025
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
2026
      msg = ("The configuration denotes node %s as master, while my"
2027
             " hostname is %s; opening a foreign configuration is only"
2028
             " possible in accept_foreign mode" %
2029
             (data.cluster.master_node, self._my_hostname))
2030
      raise errors.ConfigurationError(msg)
2031

    
2032
    # Upgrade configuration if needed
2033
    data.UpgradeConfig()
2034

    
2035
    self._config_data = data
2036
    # reset the last serial as -1 so that the next write will cause
2037
    # ssconf update
2038
    self._last_cluster_serial = -1
2039

    
2040
    # And finally run our (custom) config upgrade sequence
2041
    self._UpgradeConfig()
2042

    
2043
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2044

    
2045
  def _UpgradeConfig(self):
2046
    """Run upgrade steps that cannot be done purely in the objects.
2047

2048
    This is because some data elements need uniqueness across the
2049
    whole configuration, etc.
2050

2051
    @warning: this function will call L{_WriteConfig()}, but also
2052
        L{DropECReservations} so it needs to be called only from a
2053
        "safe" place (the constructor). If one wanted to call it with
2054
        the lock held, a DropECReservationUnlocked would need to be
2055
        created first, to avoid causing deadlock.
2056

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

    
2084
  def _DistributeConfig(self, feedback_fn):
2085
    """Distribute the configuration to the other nodes.
2086

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

2090
    """
2091
    if self._offline:
2092
      return True
2093

    
2094
    bad = False
2095

    
2096
    node_list = []
2097
    addr_list = []
2098
    myhostname = self._my_hostname
2099
    # we can skip checking whether _UnlockedGetNodeInfo returns None
2100
    # since the node list comes from _UnlocketGetNodeList, and we are
2101
    # called with the lock held, so no modifications should take place
2102
    # in between
2103
    for node_name in self._UnlockedGetNodeList():
2104
      if node_name == myhostname:
2105
        continue
2106
      node_info = self._UnlockedGetNodeInfo(node_name)
2107
      if not node_info.master_candidate:
2108
        continue
2109
      node_list.append(node_info.name)
2110
      addr_list.append(node_info.primary_ip)
2111

    
2112
    # TODO: Use dedicated resolver talking to config writer for name resolution
2113
    result = \
2114
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2115
    for to_node, to_result in result.items():
2116
      msg = to_result.fail_msg
2117
      if msg:
2118
        msg = ("Copy of file %s to node %s failed: %s" %
2119
               (self._cfg_file, to_node, msg))
2120
        logging.error(msg)
2121

    
2122
        if feedback_fn:
2123
          feedback_fn(msg)
2124

    
2125
        bad = True
2126

    
2127
    return not bad
2128

    
2129
  def _WriteConfig(self, destination=None, feedback_fn=None):
2130
    """Write the configuration data to persistent storage.
2131

2132
    """
2133
    assert feedback_fn is None or callable(feedback_fn)
2134

    
2135
    # Warn on config errors, but don't abort the save - the
2136
    # configuration has already been modified, and we can't revert;
2137
    # the best we can do is to warn the user and save as is, leaving
2138
    # recovery to the user
2139
    config_errors = self._UnlockedVerifyConfig()
2140
    if config_errors:
2141
      errmsg = ("Configuration data is not consistent: %s" %
2142
                (utils.CommaJoin(config_errors)))
2143
      logging.critical(errmsg)
2144
      if feedback_fn:
2145
        feedback_fn(errmsg)
2146

    
2147
    if destination is None:
2148
      destination = self._cfg_file
2149
    self._BumpSerialNo()
2150
    txt = serializer.Dump(self._config_data.ToDict())
2151

    
2152
    getents = self._getents()
2153
    try:
2154
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2155
                               close=False, gid=getents.confd_gid, mode=0640)
2156
    except errors.LockError:
2157
      raise errors.ConfigurationError("The configuration file has been"
2158
                                      " modified since the last write, cannot"
2159
                                      " update")
2160
    try:
2161
      self._cfg_id = utils.GetFileID(fd=fd)
2162
    finally:
2163
      os.close(fd)
2164

    
2165
    self.write_count += 1
2166

    
2167
    # and redistribute the config file to master candidates
2168
    self._DistributeConfig(feedback_fn)
2169

    
2170
    # Write ssconf files on all nodes (including locally)
2171
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2172
      if not self._offline:
2173
        result = self._GetRpc(None).call_write_ssconf_files(
2174
          self._UnlockedGetOnlineNodeList(),
2175
          self._UnlockedGetSsconfValues())
2176

    
2177
        for nname, nresu in result.items():
2178
          msg = nresu.fail_msg
2179
          if msg:
2180
            errmsg = ("Error while uploading ssconf files to"
2181
                      " node %s: %s" % (nname, msg))
2182
            logging.warning(errmsg)
2183

    
2184
            if feedback_fn:
2185
              feedback_fn(errmsg)
2186

    
2187
      self._last_cluster_serial = self._config_data.cluster.serial_no
2188

    
2189
  def _UnlockedGetSsconfValues(self):
2190
    """Return the values needed by ssconf.
2191

2192
    @rtype: dict
2193
    @return: a dictionary with keys the ssconf names and values their
2194
        associated value
2195

2196
    """
2197
    fn = "\n".join
2198
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
2199
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
2200
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
2201
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2202
                    for ninfo in node_info]
2203
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2204
                    for ninfo in node_info]
2205

    
2206
    instance_data = fn(instance_names)
2207
    off_data = fn(node.name for node in node_info if node.offline)
2208
    on_data = fn(node.name for node in node_info if not node.offline)
2209
    mc_data = fn(node.name for node in node_info if node.master_candidate)
2210
    mc_ips_data = fn(node.primary_ip for node in node_info
2211
                     if node.master_candidate)
2212
    node_data = fn(node_names)
2213
    node_pri_ips_data = fn(node_pri_ips)
2214
    node_snd_ips_data = fn(node_snd_ips)
2215

    
2216
    cluster = self._config_data.cluster
2217
    cluster_tags = fn(cluster.GetTags())
2218

    
2219
    hypervisor_list = fn(cluster.enabled_hypervisors)
2220

    
2221
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2222

    
2223
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2224
                  self._config_data.nodegroups.values()]
2225
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2226
    networks = ["%s %s" % (net.uuid, net.name) for net in
2227
                self._config_data.networks.values()]
2228
    networks_data = fn(utils.NiceSort(networks))
2229

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

    
2263
  @locking.ssynchronized(_config_lock, shared=1)
2264
  def GetSsconfValues(self):
2265
    """Wrapper using lock around _UnlockedGetSsconf().
2266

2267
    """
2268
    return self._UnlockedGetSsconfValues()
2269

    
2270
  @locking.ssynchronized(_config_lock, shared=1)
2271
  def GetVGName(self):
2272
    """Return the volume group name.
2273

2274
    """
2275
    return self._config_data.cluster.volume_group_name
2276

    
2277
  @locking.ssynchronized(_config_lock)
2278
  def SetVGName(self, vg_name):
2279
    """Set the volume group name.
2280

2281
    """
2282
    self._config_data.cluster.volume_group_name = vg_name
2283
    self._config_data.cluster.serial_no += 1
2284
    self._WriteConfig()
2285

    
2286
  @locking.ssynchronized(_config_lock, shared=1)
2287
  def GetDRBDHelper(self):
2288
    """Return DRBD usermode helper.
2289

2290
    """
2291
    return self._config_data.cluster.drbd_usermode_helper
2292

    
2293
  @locking.ssynchronized(_config_lock)
2294
  def SetDRBDHelper(self, drbd_helper):
2295
    """Set DRBD usermode helper.
2296

2297
    """
2298
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2299
    self._config_data.cluster.serial_no += 1
2300
    self._WriteConfig()
2301

    
2302
  @locking.ssynchronized(_config_lock, shared=1)
2303
  def GetMACPrefix(self):
2304
    """Return the mac prefix.
2305

2306
    """
2307
    return self._config_data.cluster.mac_prefix
2308

    
2309
  @locking.ssynchronized(_config_lock, shared=1)
2310
  def GetClusterInfo(self):
2311
    """Returns information about the cluster
2312

2313
    @rtype: L{objects.Cluster}
2314
    @return: the cluster object
2315

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

    
2319
  @locking.ssynchronized(_config_lock, shared=1)
2320
  def HasAnyDiskOfType(self, dev_type):
2321
    """Check if in there is at disk of the given type in the configuration.
2322

2323
    """
2324
    return self._config_data.HasAnyDiskOfType(dev_type)
2325

    
2326
  @locking.ssynchronized(_config_lock)
2327
  def Update(self, target, feedback_fn, ec_id=None):
2328
    """Notify function to be called after updates.
2329

2330
    This function must be called when an object (as returned by
2331
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2332
    caller wants the modifications saved to the backing store. Note
2333
    that all modified objects will be saved, but the target argument
2334
    is the one the caller wants to ensure that it's saved.
2335

2336
    @param target: an instance of either L{objects.Cluster},
2337
        L{objects.Node} or L{objects.Instance} which is existing in
2338
        the cluster
2339
    @param feedback_fn: Callable feedback function
2340

2341
    """
2342
    if self._config_data is None:
2343
      raise errors.ProgrammerError("Configuration file not read,"
2344
                                   " cannot save.")
2345
    update_serial = False
2346
    if isinstance(target, objects.Cluster):
2347
      test = target == self._config_data.cluster
2348
    elif isinstance(target, objects.Node):
2349
      test = target in self._config_data.nodes.values()
2350
      update_serial = True
2351
    elif isinstance(target, objects.Instance):
2352
      test = target in self._config_data.instances.values()
2353
    elif isinstance(target, objects.NodeGroup):
2354
      test = target in self._config_data.nodegroups.values()
2355
    elif isinstance(target, objects.Network):
2356
      test = target in self._config_data.networks.values()
2357
    else:
2358
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2359
                                   " ConfigWriter.Update" % type(target))
2360
    if not test:
2361
      raise errors.ConfigurationError("Configuration updated since object"
2362
                                      " has been read or unknown object")
2363
    target.serial_no += 1
2364
    target.mtime = now = time.time()
2365

    
2366
    if update_serial:
2367
      # for node updates, we need to increase the cluster serial too
2368
      self._config_data.cluster.serial_no += 1
2369
      self._config_data.cluster.mtime = now
2370

    
2371
    if isinstance(target, objects.Instance):
2372
      self._UnlockedReleaseDRBDMinors(target.name)
2373

    
2374
    if ec_id is not None:
2375
      # Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
2376
      self._UnlockedCommitTemporaryIps(ec_id)
2377

    
2378
    self._WriteConfig(feedback_fn=feedback_fn)
2379

    
2380
  @locking.ssynchronized(_config_lock)
2381
  def DropECReservations(self, ec_id):
2382
    """Drop per-execution-context reservations
2383

2384
    """
2385
    for rm in self._all_rms:
2386
      rm.DropECReservations(ec_id)
2387

    
2388
  @locking.ssynchronized(_config_lock, shared=1)
2389
  def GetAllNetworksInfo(self):
2390
    """Get configuration info of all the networks.
2391

2392
    """
2393
    return dict(self._config_data.networks)
2394

    
2395
  def _UnlockedGetNetworkList(self):
2396
    """Get the list of networks.
2397

2398
    This function is for internal use, when the config lock is already held.
2399

2400
    """
2401
    return self._config_data.networks.keys()
2402

    
2403
  @locking.ssynchronized(_config_lock, shared=1)
2404
  def GetNetworkList(self):
2405
    """Get the list of networks.
2406

2407
    @return: array of networks, ex. ["main", "vlan100", "200]
2408

2409
    """
2410
    return self._UnlockedGetNetworkList()
2411

    
2412
  @locking.ssynchronized(_config_lock, shared=1)
2413
  def GetNetworkNames(self):
2414
    """Get a list of network names
2415

2416
    """
2417
    names = [net.name
2418
             for net in self._config_data.networks.values()]
2419
    return names
2420

    
2421
  def _UnlockedGetNetwork(self, uuid):
2422
    """Returns information about a network.
2423

2424
    This function is for internal use, when the config lock is already held.
2425

2426
    """
2427
    if uuid not in self._config_data.networks:
2428
      return None
2429

    
2430
    return self._config_data.networks[uuid]
2431

    
2432
  @locking.ssynchronized(_config_lock, shared=1)
2433
  def GetNetwork(self, uuid):
2434
    """Returns information about a network.
2435

2436
    It takes the information from the configuration file.
2437

2438
    @param uuid: UUID of the network
2439

2440
    @rtype: L{objects.Network}
2441
    @return: the network object
2442

2443
    """
2444
    return self._UnlockedGetNetwork(uuid)
2445

    
2446
  @locking.ssynchronized(_config_lock)
2447
  def AddNetwork(self, net, ec_id, check_uuid=True):
2448
    """Add a network to the configuration.
2449

2450
    @type net: L{objects.Network}
2451
    @param net: the Network object to add
2452
    @type ec_id: string
2453
    @param ec_id: unique id for the job to use when creating a missing UUID
2454

2455
    """
2456
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2457
    self._WriteConfig()
2458

    
2459
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2460
    """Add a network to the configuration.
2461

2462
    """
2463
    logging.info("Adding network %s to configuration", net.name)
2464

    
2465
    if check_uuid:
2466
      self._EnsureUUID(net, ec_id)
2467

    
2468
    net.serial_no = 1
2469
    self._config_data.networks[net.uuid] = net
2470
    self._config_data.cluster.serial_no += 1
2471

    
2472
  def _UnlockedLookupNetwork(self, target):
2473
    """Lookup a network's UUID.
2474

2475
    @type target: string
2476
    @param target: network name or UUID
2477
    @rtype: string
2478
    @return: network UUID
2479
    @raises errors.OpPrereqError: when the target network cannot be found
2480

2481
    """
2482
    if target in self._config_data.networks:
2483
      return target
2484
    for net in self._config_data.networks.values():
2485
      if net.name == target:
2486
        return net.uuid
2487
    raise errors.OpPrereqError("Network '%s' not found" % target,
2488
                               errors.ECODE_NOENT)
2489

    
2490
  @locking.ssynchronized(_config_lock, shared=1)
2491
  def LookupNetwork(self, target):
2492
    """Lookup a network's UUID.
2493

2494
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2495

2496
    @type target: string
2497
    @param target: network name or UUID
2498
    @rtype: string
2499
    @return: network UUID
2500

2501
    """
2502
    return self._UnlockedLookupNetwork(target)
2503

    
2504
  @locking.ssynchronized(_config_lock)
2505
  def RemoveNetwork(self, network_uuid):
2506
    """Remove a network from the configuration.
2507

2508
    @type network_uuid: string
2509
    @param network_uuid: the UUID of the network to remove
2510

2511
    """
2512
    logging.info("Removing network %s from configuration", network_uuid)
2513

    
2514
    if network_uuid not in self._config_data.networks:
2515
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2516

    
2517
    del self._config_data.networks[network_uuid]
2518
    self._config_data.cluster.serial_no += 1
2519
    self._WriteConfig()
2520

    
2521
  def _UnlockedGetGroupNetParams(self, net, node):
2522
    """Get the netparams (mode, link) of a network.
2523

2524
    Get a network's netparams for a given node.
2525

2526
    @type net: string
2527
    @param net: network name
2528
    @type node: string
2529
    @param node: node name
2530
    @rtype: dict or None
2531
    @return: netparams
2532

2533
    """
2534
    net_uuid = self._UnlockedLookupNetwork(net)
2535
    node_info = self._UnlockedGetNodeInfo(node)
2536
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2537
    netparams = nodegroup_info.networks.get(net_uuid, None)
2538

    
2539
    return netparams
2540

    
2541
  @locking.ssynchronized(_config_lock, shared=1)
2542
  def GetGroupNetParams(self, net, node):
2543
    """Locking wrapper of _UnlockedGetGroupNetParams()
2544

2545
    """
2546
    return self._UnlockedGetGroupNetParams(net, node)
2547

    
2548
  @locking.ssynchronized(_config_lock, shared=1)
2549
  def CheckIPInNodeGroup(self, ip, node):
2550
    """Check IP uniqueness in nodegroup.
2551

2552
    Check networks that are connected in the node's node group
2553
    if ip is contained in any of them. Used when creating/adding
2554
    a NIC to ensure uniqueness among nodegroups.
2555

2556
    @type ip: string
2557
    @param ip: ip address
2558
    @type node: string
2559
    @param node: node name
2560
    @rtype: (string, dict) or (None, None)
2561
    @return: (network name, netparams)
2562

2563
    """
2564
    if ip is None:
2565
      return (None, None)
2566
    node_info = self._UnlockedGetNodeInfo(node)
2567
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2568
    for net_uuid in nodegroup_info.networks.keys():
2569
      net_info = self._UnlockedGetNetwork(net_uuid)
2570
      pool = network.AddressPool(net_info)
2571
      if pool.Contains(ip):
2572
        return (net_info.name, nodegroup_info.networks[net_uuid])
2573

    
2574
    return (None, None)