Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 1b68f268

History | View | Annotate | Download (84.9 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 copy
38
import os
39
import random
40
import logging
41
import time
42
import itertools
43

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

    
57

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

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

    
63

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

67
  This only verifies the version of the configuration.
68

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

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

    
76

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

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

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

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

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

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

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

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

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

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

126
    """
127
    assert callable(generate_one_fn)
128

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

    
142

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

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

    
149

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

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

159
  """
160
  result = []
161

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

    
167
  return result
168

    
169

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

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

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

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

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

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

216
    """
217
    self._context = context
218

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
284
    return prefix
285

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

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

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

    
302
    return GenMac
303

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

308
    This should check the current instances for duplicates.
309

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

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

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

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

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

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

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

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

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

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

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

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

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

364
    This is just a wrapper around _UnlockedReleaseIp.
365

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

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

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

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

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

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

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

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

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

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

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

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

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

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

432
    This checks the current disks for duplicates.
433

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
505
    return result
506

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

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

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

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

    
527
    return result
528

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
779
    # IP checks
780
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
781
    ips = {}
782

    
783
    def _AddIpAddress(ip, name):
784
      ips.setdefault(ip, []).append(name)
785

    
786
    _AddIpAddress(cluster.master_ip, "cluster_ip")
787

    
788
    for node in data.nodes.values():
789
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
790
      if node.secondary_ip != node.primary_ip:
791
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
792

    
793
    for instance in data.instances.values():
794
      for idx, nic in enumerate(instance.nics):
795
        if nic.ip is None:
796
          continue
797

    
798
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
799
        nic_mode = nicparams[constants.NIC_MODE]
800
        nic_link = nicparams[constants.NIC_LINK]
801

    
802
        if nic_mode == constants.NIC_MODE_BRIDGED:
803
          link = "bridge:%s" % nic_link
804
        elif nic_mode == constants.NIC_MODE_ROUTED:
805
          link = "route:%s" % nic_link
806
        else:
807
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
808

    
809
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
810
                      "instance:%s/nic:%d" % (instance.name, idx))
811

    
812
    for ip, owners in ips.items():
813
      if len(owners) > 1:
814
        result.append("IP address %s is used by multiple owners: %s" %
815
                      (ip, utils.CommaJoin(owners)))
816

    
817
    return result
818

    
819
  @locking.ssynchronized(_config_lock, shared=1)
820
  def VerifyConfig(self):
821
    """Verify function.
822

823
    This is just a wrapper over L{_UnlockedVerifyConfig}.
824

825
    @rtype: list
826
    @return: a list of error messages; a non-empty list signifies
827
        configuration errors
828

829
    """
830
    return self._UnlockedVerifyConfig()
831

    
832
  def _UnlockedSetDiskID(self, disk, node_name):
833
    """Convert the unique ID to the ID needed on the target nodes.
834

835
    This is used only for drbd, which needs ip/port configuration.
836

837
    The routine descends down and updates its children also, because
838
    this helps when the only the top device is passed to the remote
839
    node.
840

841
    This function is for internal use, when the config lock is already held.
842

843
    """
844
    if disk.children:
845
      for child in disk.children:
846
        self._UnlockedSetDiskID(child, node_name)
847

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

    
870
  @locking.ssynchronized(_config_lock)
871
  def SetDiskID(self, disk, node_name):
872
    """Convert the unique ID to the ID needed on the target nodes.
873

874
    This is used only for drbd, which needs ip/port configuration.
875

876
    The routine descends down and updates its children also, because
877
    this helps when the only the top device is passed to the remote
878
    node.
879

880
    """
881
    return self._UnlockedSetDiskID(disk, node_name)
882

    
883
  @locking.ssynchronized(_config_lock)
884
  def AddTcpUdpPort(self, port):
885
    """Adds a new port to the available port pool.
886

887
    @warning: this method does not "flush" the configuration (via
888
        L{_WriteConfig}); callers should do that themselves once the
889
        configuration is stable
890

891
    """
892
    if not isinstance(port, int):
893
      raise errors.ProgrammerError("Invalid type passed for port")
894

    
895
    self._config_data.cluster.tcpudp_port_pool.add(port)
896

    
897
  @locking.ssynchronized(_config_lock, shared=1)
898
  def GetPortList(self):
899
    """Returns a copy of the current port list.
900

901
    """
902
    return self._config_data.cluster.tcpudp_port_pool.copy()
903

    
904
  @locking.ssynchronized(_config_lock)
905
  def AllocatePort(self):
906
    """Allocate a port.
907

908
    The port will be taken from the available port pool or from the
909
    default port range (and in this case we increase
910
    highest_used_port).
911

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

    
924
    self._WriteConfig()
925
    return port
926

    
927
  def _UnlockedComputeDRBDMap(self):
928
    """Compute the used DRBD minor/nodes.
929

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

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

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

    
966
  @locking.ssynchronized(_config_lock)
967
  def ComputeDRBDMap(self):
968
    """Compute the used DRBD minor/nodes.
969

970
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
971

972
    @return: dictionary of node_name: dict of minor: instance_name;
973
        the returned dict will have all the nodes in it (even if with
974
        an empty list).
975

976
    """
977
    d_map, duplicates = self._UnlockedComputeDRBDMap()
978
    if duplicates:
979
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
980
                                      str(duplicates))
981
    return d_map
982

    
983
  @locking.ssynchronized(_config_lock)
984
  def AllocateDRBDMinor(self, nodes, instance):
985
    """Allocate a drbd minor.
986

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

992
    @type instance: string
993
    @param instance: the instance for which we allocate minors
994

995
    """
996
    assert isinstance(instance, basestring), \
997
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
998

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

    
1039
  def _UnlockedReleaseDRBDMinors(self, instance):
1040
    """Release temporary drbd minors allocated for a given instance.
1041

1042
    @type instance: string
1043
    @param instance: the instance for which temporary minors should be
1044
                     released
1045

1046
    """
1047
    assert isinstance(instance, basestring), \
1048
           "Invalid argument passed to ReleaseDRBDMinors"
1049
    for key, name in self._temporary_drbds.items():
1050
      if name == instance:
1051
        del self._temporary_drbds[key]
1052

    
1053
  @locking.ssynchronized(_config_lock)
1054
  def ReleaseDRBDMinors(self, instance):
1055
    """Release temporary drbd minors allocated for a given instance.
1056

1057
    This should be called on the error paths, on the success paths
1058
    it's automatically called by the ConfigWriter add and update
1059
    functions.
1060

1061
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1062

1063
    @type instance: string
1064
    @param instance: the instance for which temporary minors should be
1065
                     released
1066

1067
    """
1068
    self._UnlockedReleaseDRBDMinors(instance)
1069

    
1070
  @locking.ssynchronized(_config_lock, shared=1)
1071
  def GetConfigVersion(self):
1072
    """Get the configuration version.
1073

1074
    @return: Config version
1075

1076
    """
1077
    return self._config_data.version
1078

    
1079
  @locking.ssynchronized(_config_lock, shared=1)
1080
  def GetClusterName(self):
1081
    """Get cluster name.
1082

1083
    @return: Cluster name
1084

1085
    """
1086
    return self._config_data.cluster.cluster_name
1087

    
1088
  @locking.ssynchronized(_config_lock, shared=1)
1089
  def GetMasterNode(self):
1090
    """Get the hostname of the master node for this cluster.
1091

1092
    @return: Master hostname
1093

1094
    """
1095
    return self._config_data.cluster.master_node
1096

    
1097
  @locking.ssynchronized(_config_lock, shared=1)
1098
  def GetMasterIP(self):
1099
    """Get the IP of the master node for this cluster.
1100

1101
    @return: Master IP
1102

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

    
1106
  @locking.ssynchronized(_config_lock, shared=1)
1107
  def GetMasterNetdev(self):
1108
    """Get the master network device for this cluster.
1109

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

    
1113
  @locking.ssynchronized(_config_lock, shared=1)
1114
  def GetMasterNetmask(self):
1115
    """Get the netmask of the master node for this cluster.
1116

1117
    """
1118
    return self._config_data.cluster.master_netmask
1119

    
1120
  @locking.ssynchronized(_config_lock, shared=1)
1121
  def GetUseExternalMipScript(self):
1122
    """Get flag representing whether to use the external master IP setup script.
1123

1124
    """
1125
    return self._config_data.cluster.use_external_mip_script
1126

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

1131
    """
1132
    return self._config_data.cluster.file_storage_dir
1133

    
1134
  @locking.ssynchronized(_config_lock, shared=1)
1135
  def GetSharedFileStorageDir(self):
1136
    """Get the shared file storage dir for this cluster.
1137

1138
    """
1139
    return self._config_data.cluster.shared_file_storage_dir
1140

    
1141
  @locking.ssynchronized(_config_lock, shared=1)
1142
  def GetHypervisorType(self):
1143
    """Get the hypervisor type for this cluster.
1144

1145
    """
1146
    return self._config_data.cluster.enabled_hypervisors[0]
1147

    
1148
  @locking.ssynchronized(_config_lock, shared=1)
1149
  def GetHostKey(self):
1150
    """Return the rsa hostkey from the config.
1151

1152
    @rtype: string
1153
    @return: the rsa hostkey
1154

1155
    """
1156
    return self._config_data.cluster.rsahostkeypub
1157

    
1158
  @locking.ssynchronized(_config_lock, shared=1)
1159
  def GetDefaultIAllocator(self):
1160
    """Get the default instance allocator for this cluster.
1161

1162
    """
1163
    return self._config_data.cluster.default_iallocator
1164

    
1165
  @locking.ssynchronized(_config_lock, shared=1)
1166
  def GetPrimaryIPFamily(self):
1167
    """Get cluster primary ip family.
1168

1169
    @return: primary ip family
1170

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

    
1174
  @locking.ssynchronized(_config_lock, shared=1)
1175
  def GetMasterNetworkParameters(self):
1176
    """Get network parameters of the master node.
1177

1178
    @rtype: L{object.MasterNetworkParameters}
1179
    @return: network parameters of the master node
1180

1181
    """
1182
    cluster = self._config_data.cluster
1183
    result = objects.MasterNetworkParameters(
1184
      name=cluster.master_node, ip=cluster.master_ip,
1185
      netmask=cluster.master_netmask, netdev=cluster.master_netdev,
1186
      ip_family=cluster.primary_ip_family)
1187

    
1188
    return result
1189

    
1190
  @locking.ssynchronized(_config_lock)
1191
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1192
    """Add a node group to the configuration.
1193

1194
    This method calls group.UpgradeConfig() to fill any missing attributes
1195
    according to their default values.
1196

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

1206
    """
1207
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1208
    self._WriteConfig()
1209

    
1210
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1211
    """Add a node group to the configuration.
1212

1213
    """
1214
    logging.info("Adding node group %s to configuration", group.name)
1215

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

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

    
1232
    group.serial_no = 1
1233
    group.ctime = group.mtime = time.time()
1234
    group.UpgradeConfig()
1235

    
1236
    self._config_data.nodegroups[group.uuid] = group
1237
    self._config_data.cluster.serial_no += 1
1238

    
1239
  @locking.ssynchronized(_config_lock)
1240
  def RemoveNodeGroup(self, group_uuid):
1241
    """Remove a node group from the configuration.
1242

1243
    @type group_uuid: string
1244
    @param group_uuid: the UUID of the node group to remove
1245

1246
    """
1247
    logging.info("Removing node group %s from configuration", group_uuid)
1248

    
1249
    if group_uuid not in self._config_data.nodegroups:
1250
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1251

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

    
1255
    del self._config_data.nodegroups[group_uuid]
1256
    self._config_data.cluster.serial_no += 1
1257
    self._WriteConfig()
1258

    
1259
  def _UnlockedLookupNodeGroup(self, target):
1260
    """Lookup a node group's UUID.
1261

1262
    @type target: string or None
1263
    @param target: group name or UUID or None to look for the default
1264
    @rtype: string
1265
    @return: nodegroup UUID
1266
    @raises errors.OpPrereqError: when the target group cannot be found
1267

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

    
1283
  @locking.ssynchronized(_config_lock, shared=1)
1284
  def LookupNodeGroup(self, target):
1285
    """Lookup a node group's UUID.
1286

1287
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1288

1289
    @type target: string or None
1290
    @param target: group name or UUID or None to look for the default
1291
    @rtype: string
1292
    @return: nodegroup UUID
1293

1294
    """
1295
    return self._UnlockedLookupNodeGroup(target)
1296

    
1297
  def _UnlockedGetNodeGroup(self, uuid):
1298
    """Lookup a node group.
1299

1300
    @type uuid: string
1301
    @param uuid: group UUID
1302
    @rtype: L{objects.NodeGroup} or None
1303
    @return: nodegroup object, or None if not found
1304

1305
    """
1306
    if uuid not in self._config_data.nodegroups:
1307
      return None
1308

    
1309
    return self._config_data.nodegroups[uuid]
1310

    
1311
  @locking.ssynchronized(_config_lock, shared=1)
1312
  def GetNodeGroup(self, uuid):
1313
    """Lookup a node group.
1314

1315
    @type uuid: string
1316
    @param uuid: group UUID
1317
    @rtype: L{objects.NodeGroup} or None
1318
    @return: nodegroup object, or None if not found
1319

1320
    """
1321
    return self._UnlockedGetNodeGroup(uuid)
1322

    
1323
  @locking.ssynchronized(_config_lock, shared=1)
1324
  def GetAllNodeGroupsInfo(self):
1325
    """Get the configuration of all node groups.
1326

1327
    """
1328
    return dict(self._config_data.nodegroups)
1329

    
1330
  @locking.ssynchronized(_config_lock, shared=1)
1331
  def GetNodeGroupList(self):
1332
    """Get a list of node groups.
1333

1334
    """
1335
    return self._config_data.nodegroups.keys()
1336

    
1337
  @locking.ssynchronized(_config_lock, shared=1)
1338
  def GetNodeGroupMembersByNodes(self, nodes):
1339
    """Get nodes which are member in the same nodegroups as the given nodes.
1340

1341
    """
1342
    ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1343
    return frozenset(member_name
1344
                     for node_name in nodes
1345
                     for member_name in
1346
                       self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1347

    
1348
  @locking.ssynchronized(_config_lock, shared=1)
1349
  def GetMultiNodeGroupInfo(self, group_uuids):
1350
    """Get the configuration of multiple node groups.
1351

1352
    @param group_uuids: List of node group UUIDs
1353
    @rtype: list
1354
    @return: List of tuples of (group_uuid, group_info)
1355

1356
    """
1357
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1358

    
1359
  @locking.ssynchronized(_config_lock)
1360
  def AddInstance(self, instance, ec_id):
1361
    """Add an instance to the config.
1362

1363
    This should be used after creating a new instance.
1364

1365
    @type instance: L{objects.Instance}
1366
    @param instance: the instance object
1367

1368
    """
1369
    if not isinstance(instance, objects.Instance):
1370
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1371

    
1372
    if instance.disk_template != constants.DT_DISKLESS:
1373
      all_lvs = instance.MapLVsByNode()
1374
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1375

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

    
1383
    self._EnsureUUID(instance, ec_id)
1384

    
1385
    instance.serial_no = 1
1386
    instance.ctime = instance.mtime = time.time()
1387
    self._config_data.instances[instance.name] = instance
1388
    self._config_data.cluster.serial_no += 1
1389
    self._UnlockedReleaseDRBDMinors(instance.name)
1390
    self._UnlockedCommitTemporaryIps(ec_id)
1391
    self._WriteConfig()
1392

    
1393
  def _EnsureUUID(self, item, ec_id):
1394
    """Ensures a given object has a valid UUID.
1395

1396
    @param item: the instance or node to be checked
1397
    @param ec_id: the execution context id for the uuid reservation
1398

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

    
1406
  def _SetInstanceStatus(self, instance_name, status):
1407
    """Set the instance's status to a given value.
1408

1409
    """
1410
    assert status in constants.ADMINST_ALL, \
1411
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1412

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

    
1423
  @locking.ssynchronized(_config_lock)
1424
  def MarkInstanceUp(self, instance_name):
1425
    """Mark the instance status to up in the config.
1426

1427
    """
1428
    self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1429

    
1430
  @locking.ssynchronized(_config_lock)
1431
  def MarkInstanceOffline(self, instance_name):
1432
    """Mark the instance status to down in the config.
1433

1434
    """
1435
    self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1436

    
1437
  @locking.ssynchronized(_config_lock)
1438
  def RemoveInstance(self, instance_name):
1439
    """Remove the instance from the configuration.
1440

1441
    """
1442
    if instance_name not in self._config_data.instances:
1443
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1444

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

    
1452
    instance = self._UnlockedGetInstanceInfo(instance_name)
1453

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

    
1460
    del self._config_data.instances[instance_name]
1461
    self._config_data.cluster.serial_no += 1
1462
    self._WriteConfig()
1463

    
1464
  @locking.ssynchronized(_config_lock)
1465
  def RenameInstance(self, old_name, new_name):
1466
    """Rename an instance.
1467

1468
    This needs to be done in ConfigWriter and not by RemoveInstance
1469
    combined with AddInstance as only we can guarantee an atomic
1470
    rename.
1471

1472
    """
1473
    if old_name not in self._config_data.instances:
1474
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1475

    
1476
    # Operate on a copy to not loose instance object in case of a failure
1477
    inst = self._config_data.instances[old_name].Copy()
1478
    inst.name = new_name
1479

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

    
1489
    # Actually replace instance object
1490
    del self._config_data.instances[old_name]
1491
    self._config_data.instances[inst.name] = inst
1492

    
1493
    # Force update of ssconf files
1494
    self._config_data.cluster.serial_no += 1
1495

    
1496
    self._WriteConfig()
1497

    
1498
  @locking.ssynchronized(_config_lock)
1499
  def MarkInstanceDown(self, instance_name):
1500
    """Mark the status of an instance to down in the configuration.
1501

1502
    """
1503
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1504

    
1505
  def _UnlockedGetInstanceList(self):
1506
    """Get the list of instances.
1507

1508
    This function is for internal use, when the config lock is already held.
1509

1510
    """
1511
    return self._config_data.instances.keys()
1512

    
1513
  @locking.ssynchronized(_config_lock, shared=1)
1514
  def GetInstanceList(self):
1515
    """Get the list of instances.
1516

1517
    @return: array of instances, ex. ['instance2.example.com',
1518
        'instance1.example.com']
1519

1520
    """
1521
    return self._UnlockedGetInstanceList()
1522

    
1523
  def ExpandInstanceName(self, short_name):
1524
    """Attempt to expand an incomplete instance name.
1525

1526
    """
1527
    # Locking is done in L{ConfigWriter.GetInstanceList}
1528
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1529

    
1530
  def _UnlockedGetInstanceInfo(self, instance_name):
1531
    """Returns information about an instance.
1532

1533
    This function is for internal use, when the config lock is already held.
1534

1535
    """
1536
    if instance_name not in self._config_data.instances:
1537
      return None
1538

    
1539
    return self._config_data.instances[instance_name]
1540

    
1541
  @locking.ssynchronized(_config_lock, shared=1)
1542
  def GetInstanceInfo(self, instance_name):
1543
    """Returns information about an instance.
1544

1545
    It takes the information from the configuration file. Other information of
1546
    an instance are taken from the live systems.
1547

1548
    @param instance_name: name of the instance, e.g.
1549
        I{instance1.example.com}
1550

1551
    @rtype: L{objects.Instance}
1552
    @return: the instance object
1553

1554
    """
1555
    return self._UnlockedGetInstanceInfo(instance_name)
1556

    
1557
  @locking.ssynchronized(_config_lock, shared=1)
1558
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1559
    """Returns set of node group UUIDs for instance's nodes.
1560

1561
    @rtype: frozenset
1562

1563
    """
1564
    instance = self._UnlockedGetInstanceInfo(instance_name)
1565
    if not instance:
1566
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1567

    
1568
    if primary_only:
1569
      nodes = [instance.primary_node]
1570
    else:
1571
      nodes = instance.all_nodes
1572

    
1573
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1574
                     for node_name in nodes)
1575

    
1576
  @locking.ssynchronized(_config_lock, shared=1)
1577
  def GetMultiInstanceInfo(self, instances):
1578
    """Get the configuration of multiple instances.
1579

1580
    @param instances: list of instance names
1581
    @rtype: list
1582
    @return: list of tuples (instance, instance_info), where
1583
        instance_info is what would GetInstanceInfo return for the
1584
        node, while keeping the original order
1585

1586
    """
1587
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1588

    
1589
  @locking.ssynchronized(_config_lock, shared=1)
1590
  def GetAllInstancesInfo(self):
1591
    """Get the configuration of all instances.
1592

1593
    @rtype: dict
1594
    @return: dict of (instance, instance_info), where instance_info is what
1595
              would GetInstanceInfo return for the node
1596

1597
    """
1598
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1599
                    for instance in self._UnlockedGetInstanceList()])
1600
    return my_dict
1601

    
1602
  @locking.ssynchronized(_config_lock, shared=1)
1603
  def GetInstancesInfoByFilter(self, filter_fn):
1604
    """Get instance configuration with a filter.
1605

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

1613
    """
1614
    return dict((name, inst)
1615
                for (name, inst) in self._config_data.instances.items()
1616
                if filter_fn(inst))
1617

    
1618
  @locking.ssynchronized(_config_lock)
1619
  def AddNode(self, node, ec_id):
1620
    """Add a node to the configuration.
1621

1622
    @type node: L{objects.Node}
1623
    @param node: a Node instance
1624

1625
    """
1626
    logging.info("Adding node %s to configuration", node.name)
1627

    
1628
    self._EnsureUUID(node, ec_id)
1629

    
1630
    node.serial_no = 1
1631
    node.ctime = node.mtime = time.time()
1632
    self._UnlockedAddNodeToGroup(node.name, node.group)
1633
    self._config_data.nodes[node.name] = node
1634
    self._config_data.cluster.serial_no += 1
1635
    self._WriteConfig()
1636

    
1637
  @locking.ssynchronized(_config_lock)
1638
  def RemoveNode(self, node_name):
1639
    """Remove a node from the configuration.
1640

1641
    """
1642
    logging.info("Removing node %s from configuration", node_name)
1643

    
1644
    if node_name not in self._config_data.nodes:
1645
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1646

    
1647
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1648
    del self._config_data.nodes[node_name]
1649
    self._config_data.cluster.serial_no += 1
1650
    self._WriteConfig()
1651

    
1652
  def ExpandNodeName(self, short_name):
1653
    """Attempt to expand an incomplete node name.
1654

1655
    """
1656
    # Locking is done in L{ConfigWriter.GetNodeList}
1657
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1658

    
1659
  def _UnlockedGetNodeInfo(self, node_name):
1660
    """Get the configuration of a node, as stored in the config.
1661

1662
    This function is for internal use, when the config lock is already
1663
    held.
1664

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

1667
    @rtype: L{objects.Node}
1668
    @return: the node object
1669

1670
    """
1671
    if node_name not in self._config_data.nodes:
1672
      return None
1673

    
1674
    return self._config_data.nodes[node_name]
1675

    
1676
  @locking.ssynchronized(_config_lock, shared=1)
1677
  def GetNodeInfo(self, node_name):
1678
    """Get the configuration of a node, as stored in the config.
1679

1680
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1681

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

1684
    @rtype: L{objects.Node}
1685
    @return: the node object
1686

1687
    """
1688
    return self._UnlockedGetNodeInfo(node_name)
1689

    
1690
  @locking.ssynchronized(_config_lock, shared=1)
1691
  def GetNodeInstances(self, node_name):
1692
    """Get the instances of a node, as stored in the config.
1693

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

1696
    @rtype: (list, list)
1697
    @return: a tuple with two lists: the primary and the secondary instances
1698

1699
    """
1700
    pri = []
1701
    sec = []
1702
    for inst in self._config_data.instances.values():
1703
      if inst.primary_node == node_name:
1704
        pri.append(inst.name)
1705
      if node_name in inst.secondary_nodes:
1706
        sec.append(inst.name)
1707
    return (pri, sec)
1708

    
1709
  @locking.ssynchronized(_config_lock, shared=1)
1710
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1711
    """Get the instances of a node group.
1712

1713
    @param uuid: Node group UUID
1714
    @param primary_only: Whether to only consider primary nodes
1715
    @rtype: frozenset
1716
    @return: List of instance names in node group
1717

1718
    """
1719
    if primary_only:
1720
      nodes_fn = lambda inst: [inst.primary_node]
1721
    else:
1722
      nodes_fn = lambda inst: inst.all_nodes
1723

    
1724
    return frozenset(inst.name
1725
                     for inst in self._config_data.instances.values()
1726
                     for node_name in nodes_fn(inst)
1727
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1728

    
1729
  def _UnlockedGetNodeList(self):
1730
    """Return the list of nodes which are in the configuration.
1731

1732
    This function is for internal use, when the config lock is already
1733
    held.
1734

1735
    @rtype: list
1736

1737
    """
1738
    return self._config_data.nodes.keys()
1739

    
1740
  @locking.ssynchronized(_config_lock, shared=1)
1741
  def GetNodeList(self):
1742
    """Return the list of nodes which are in the configuration.
1743

1744
    """
1745
    return self._UnlockedGetNodeList()
1746

    
1747
  def _UnlockedGetOnlineNodeList(self):
1748
    """Return the list of nodes which are online.
1749

1750
    """
1751
    all_nodes = [self._UnlockedGetNodeInfo(node)
1752
                 for node in self._UnlockedGetNodeList()]
1753
    return [node.name for node in all_nodes if not node.offline]
1754

    
1755
  @locking.ssynchronized(_config_lock, shared=1)
1756
  def GetOnlineNodeList(self):
1757
    """Return the list of nodes which are online.
1758

1759
    """
1760
    return self._UnlockedGetOnlineNodeList()
1761

    
1762
  @locking.ssynchronized(_config_lock, shared=1)
1763
  def GetVmCapableNodeList(self):
1764
    """Return the list of nodes which are not vm capable.
1765

1766
    """
1767
    all_nodes = [self._UnlockedGetNodeInfo(node)
1768
                 for node in self._UnlockedGetNodeList()]
1769
    return [node.name for node in all_nodes if node.vm_capable]
1770

    
1771
  @locking.ssynchronized(_config_lock, shared=1)
1772
  def GetNonVmCapableNodeList(self):
1773
    """Return the list of nodes which are not vm capable.
1774

1775
    """
1776
    all_nodes = [self._UnlockedGetNodeInfo(node)
1777
                 for node in self._UnlockedGetNodeList()]
1778
    return [node.name for node in all_nodes if not node.vm_capable]
1779

    
1780
  @locking.ssynchronized(_config_lock, shared=1)
1781
  def GetMultiNodeInfo(self, nodes):
1782
    """Get the configuration of multiple nodes.
1783

1784
    @param nodes: list of node names
1785
    @rtype: list
1786
    @return: list of tuples of (node, node_info), where node_info is
1787
        what would GetNodeInfo return for the node, in the original
1788
        order
1789

1790
    """
1791
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1792

    
1793
  @locking.ssynchronized(_config_lock, shared=1)
1794
  def GetAllNodesInfo(self):
1795
    """Get the configuration of all nodes.
1796

1797
    @rtype: dict
1798
    @return: dict of (node, node_info), where node_info is what
1799
              would GetNodeInfo return for the node
1800

1801
    """
1802
    return self._UnlockedGetAllNodesInfo()
1803

    
1804
  def _UnlockedGetAllNodesInfo(self):
1805
    """Gets configuration of all nodes.
1806

1807
    @note: See L{GetAllNodesInfo}
1808

1809
    """
1810
    return dict([(node, self._UnlockedGetNodeInfo(node))
1811
                 for node in self._UnlockedGetNodeList()])
1812

    
1813
  @locking.ssynchronized(_config_lock, shared=1)
1814
  def GetNodeGroupsFromNodes(self, nodes):
1815
    """Returns groups for a list of nodes.
1816

1817
    @type nodes: list of string
1818
    @param nodes: List of node names
1819
    @rtype: frozenset
1820

1821
    """
1822
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1823

    
1824
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1825
    """Get the number of current and maximum desired and possible candidates.
1826

1827
    @type exceptions: list
1828
    @param exceptions: if passed, list of nodes that should be ignored
1829
    @rtype: tuple
1830
    @return: tuple of (current, desired and possible, possible)
1831

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

    
1844
  @locking.ssynchronized(_config_lock, shared=1)
1845
  def GetMasterCandidateStats(self, exceptions=None):
1846
    """Get the number of current and maximum possible candidates.
1847

1848
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1849

1850
    @type exceptions: list
1851
    @param exceptions: if passed, list of nodes that should be ignored
1852
    @rtype: tuple
1853
    @return: tuple of (current, max)
1854

1855
    """
1856
    return self._UnlockedGetMasterCandidateStats(exceptions)
1857

    
1858
  @locking.ssynchronized(_config_lock)
1859
  def MaintainCandidatePool(self, exceptions):
1860
    """Try to grow the candidate pool to the desired size.
1861

1862
    @type exceptions: list
1863
    @param exceptions: if passed, list of nodes that should be ignored
1864
    @rtype: list
1865
    @return: list with the adjusted nodes (L{objects.Node} instances)
1866

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

    
1892
    return mod_list
1893

    
1894
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1895
    """Add a given node to the specified group.
1896

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

    
1907
  def _UnlockedRemoveNodeFromGroup(self, node):
1908
    """Remove a given node from its group.
1909

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

    
1922
  @locking.ssynchronized(_config_lock)
1923
  def AssignGroupNodes(self, mods):
1924
    """Changes the group of a number of nodes.
1925

1926
    @type mods: list of tuples; (node name, new group UUID)
1927
    @param mods: Node membership modifications
1928

1929
    """
1930
    groups = self._config_data.nodegroups
1931
    nodes = self._config_data.nodes
1932

    
1933
    resmod = []
1934

    
1935
    # Try to resolve names/UUIDs first
1936
    for (node_name, new_group_uuid) in mods:
1937
      try:
1938
        node = nodes[node_name]
1939
      except KeyError:
1940
        raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1941

    
1942
      if node.group == new_group_uuid:
1943
        # Node is being assigned to its current group
1944
        logging.debug("Node '%s' was assigned to its current group (%s)",
1945
                      node_name, node.group)
1946
        continue
1947

    
1948
      # Try to find current group of node
1949
      try:
1950
        old_group = groups[node.group]
1951
      except KeyError:
1952
        raise errors.ConfigurationError("Unable to find old group '%s'" %
1953
                                        node.group)
1954

    
1955
      # Try to find new group for node
1956
      try:
1957
        new_group = groups[new_group_uuid]
1958
      except KeyError:
1959
        raise errors.ConfigurationError("Unable to find new group '%s'" %
1960
                                        new_group_uuid)
1961

    
1962
      assert node.name in old_group.members, \
1963
        ("Inconsistent configuration: node '%s' not listed in members for its"
1964
         " old group '%s'" % (node.name, old_group.uuid))
1965
      assert node.name not in new_group.members, \
1966
        ("Inconsistent configuration: node '%s' already listed in members for"
1967
         " its new group '%s'" % (node.name, new_group.uuid))
1968

    
1969
      resmod.append((node, old_group, new_group))
1970

    
1971
    # Apply changes
1972
    for (node, old_group, new_group) in resmod:
1973
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
1974
        "Assigning to current group is not possible"
1975

    
1976
      node.group = new_group.uuid
1977

    
1978
      # Update members of involved groups
1979
      if node.name in old_group.members:
1980
        old_group.members.remove(node.name)
1981
      if node.name not in new_group.members:
1982
        new_group.members.append(node.name)
1983

    
1984
    # Update timestamps and serials (only once per node/group object)
1985
    now = time.time()
1986
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
1987
      obj.serial_no += 1
1988
      obj.mtime = now
1989

    
1990
    # Force ssconf update
1991
    self._config_data.cluster.serial_no += 1
1992

    
1993
    self._WriteConfig()
1994

    
1995
  def _BumpSerialNo(self):
1996
    """Bump up the serial number of the config.
1997

1998
    """
1999
    self._config_data.serial_no += 1
2000
    self._config_data.mtime = time.time()
2001

    
2002
  def _AllUUIDObjects(self):
2003
    """Returns all objects with uuid attributes.
2004

2005
    """
2006
    return (self._config_data.instances.values() +
2007
            self._config_data.nodes.values() +
2008
            self._config_data.nodegroups.values() +
2009
            [self._config_data.cluster])
2010

    
2011
  def _OpenConfig(self, accept_foreign):
2012
    """Read the config data from disk.
2013

2014
    """
2015
    raw_data = utils.ReadFile(self._cfg_file)
2016

    
2017
    try:
2018
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
2019
    except Exception, err:
2020
      raise errors.ConfigurationError(err)
2021

    
2022
    # Make sure the configuration has the right version
2023
    _ValidateConfig(data)
2024

    
2025
    if (not hasattr(data, "cluster") or
2026
        not hasattr(data.cluster, "rsahostkeypub")):
2027
      raise errors.ConfigurationError("Incomplete configuration"
2028
                                      " (missing cluster.rsahostkeypub)")
2029

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

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

    
2042
    # Upgrade configuration if needed
2043
    self._UpgradeConfig()
2044

    
2045
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2046

    
2047
  def _UpgradeConfig(self):
2048
    """Run any upgrade steps.
2049

2050
    This method performs both in-object upgrades and also update some data
2051
    elements that need uniqueness across the whole configuration or interact
2052
    with other objects.
2053

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

2060
    """
2061
    # Keep a copy of the persistent part of _config_data to check for changes
2062
    # Serialization doesn't guarantee order in dictionaries
2063
    oldconf = copy.deepcopy(self._config_data.ToDict())
2064

    
2065
    # In-object upgrades
2066
    self._config_data.UpgradeConfig()
2067

    
2068
    for item in self._AllUUIDObjects():
2069
      if item.uuid is None:
2070
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
2071
    if not self._config_data.nodegroups:
2072
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
2073
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
2074
                                            members=[])
2075
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
2076
    for node in self._config_data.nodes.values():
2077
      if not node.group:
2078
        node.group = self.LookupNodeGroup(None)
2079
      # This is technically *not* an upgrade, but needs to be done both when
2080
      # nodegroups are being added, and upon normally loading the config,
2081
      # because the members list of a node group is discarded upon
2082
      # serializing/deserializing the object.
2083
      self._UnlockedAddNodeToGroup(node.name, node.group)
2084

    
2085
    modified = (oldconf != self._config_data.ToDict())
2086
    if modified:
2087
      self._WriteConfig()
2088
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
2089
      # only called at config init time, without the lock held
2090
      self.DropECReservations(_UPGRADE_CONFIG_JID)
2091

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

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

2098
    """
2099
    if self._offline:
2100
      return True
2101

    
2102
    bad = False
2103

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

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

    
2130
        if feedback_fn:
2131
          feedback_fn(msg)
2132

    
2133
        bad = True
2134

    
2135
    return not bad
2136

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

2140
    """
2141
    assert feedback_fn is None or callable(feedback_fn)
2142

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

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

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

    
2173
    self.write_count += 1
2174

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

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

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

    
2192
            if feedback_fn:
2193
              feedback_fn(errmsg)
2194

    
2195
      self._last_cluster_serial = self._config_data.cluster.serial_no
2196

    
2197
  def _UnlockedGetSsconfValues(self):
2198
    """Return the values needed by ssconf.
2199

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

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

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

    
2224
    cluster = self._config_data.cluster
2225
    cluster_tags = fn(cluster.GetTags())
2226

    
2227
    hypervisor_list = fn(cluster.enabled_hypervisors)
2228

    
2229
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2230

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

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

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

2275
    """
2276
    return self._UnlockedGetSsconfValues()
2277

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

2282
    """
2283
    return self._config_data.cluster.volume_group_name
2284

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

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

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

2298
    """
2299
    return self._config_data.cluster.drbd_usermode_helper
2300

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

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

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

2314
    """
2315
    return self._config_data.cluster.mac_prefix
2316

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

2321
    @rtype: L{objects.Cluster}
2322
    @return: the cluster object
2323

2324
    """
2325
    return self._config_data.cluster
2326

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

2331
    """
2332
    return self._config_data.HasAnyDiskOfType(dev_type)
2333

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

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

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

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

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

    
2379
    if isinstance(target, objects.Instance):
2380
      self._UnlockedReleaseDRBDMinors(target.name)
2381

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

    
2386
    self._WriteConfig(feedback_fn=feedback_fn)
2387

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

2392
    """
2393
    for rm in self._all_rms:
2394
      rm.DropECReservations(ec_id)
2395

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

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

    
2403
  def _UnlockedGetNetworkList(self):
2404
    """Get the list of networks.
2405

2406
    This function is for internal use, when the config lock is already held.
2407

2408
    """
2409
    return self._config_data.networks.keys()
2410

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

2415
    @return: array of networks, ex. ["main", "vlan100", "200]
2416

2417
    """
2418
    return self._UnlockedGetNetworkList()
2419

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

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

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

2432
    This function is for internal use, when the config lock is already held.
2433

2434
    """
2435
    if uuid not in self._config_data.networks:
2436
      return None
2437

    
2438
    return self._config_data.networks[uuid]
2439

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

2444
    It takes the information from the configuration file.
2445

2446
    @param uuid: UUID of the network
2447

2448
    @rtype: L{objects.Network}
2449
    @return: the network object
2450

2451
    """
2452
    return self._UnlockedGetNetwork(uuid)
2453

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

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

2463
    """
2464
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2465
    self._WriteConfig()
2466

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

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

    
2473
    if check_uuid:
2474
      self._EnsureUUID(net, ec_id)
2475

    
2476
    net.serial_no = 1
2477
    self._config_data.networks[net.uuid] = net
2478
    self._config_data.cluster.serial_no += 1
2479

    
2480
  def _UnlockedLookupNetwork(self, target):
2481
    """Lookup a network's UUID.
2482

2483
    @type target: string
2484
    @param target: network name or UUID
2485
    @rtype: string
2486
    @return: network UUID
2487
    @raises errors.OpPrereqError: when the target network cannot be found
2488

2489
    """
2490
    if target in self._config_data.networks:
2491
      return target
2492
    for net in self._config_data.networks.values():
2493
      if net.name == target:
2494
        return net.uuid
2495
    raise errors.OpPrereqError("Network '%s' not found" % target,
2496
                               errors.ECODE_NOENT)
2497

    
2498
  @locking.ssynchronized(_config_lock, shared=1)
2499
  def LookupNetwork(self, target):
2500
    """Lookup a network's UUID.
2501

2502
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2503

2504
    @type target: string
2505
    @param target: network name or UUID
2506
    @rtype: string
2507
    @return: network UUID
2508

2509
    """
2510
    return self._UnlockedLookupNetwork(target)
2511

    
2512
  @locking.ssynchronized(_config_lock)
2513
  def RemoveNetwork(self, network_uuid):
2514
    """Remove a network from the configuration.
2515

2516
    @type network_uuid: string
2517
    @param network_uuid: the UUID of the network to remove
2518

2519
    """
2520
    logging.info("Removing network %s from configuration", network_uuid)
2521

    
2522
    if network_uuid not in self._config_data.networks:
2523
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2524

    
2525
    del self._config_data.networks[network_uuid]
2526
    self._config_data.cluster.serial_no += 1
2527
    self._WriteConfig()
2528

    
2529
  def _UnlockedGetGroupNetParams(self, net, node):
2530
    """Get the netparams (mode, link) of a network.
2531

2532
    Get a network's netparams for a given node.
2533

2534
    @type net: string
2535
    @param net: network name
2536
    @type node: string
2537
    @param node: node name
2538
    @rtype: dict or None
2539
    @return: netparams
2540

2541
    """
2542
    net_uuid = self._UnlockedLookupNetwork(net)
2543
    node_info = self._UnlockedGetNodeInfo(node)
2544
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2545
    netparams = nodegroup_info.networks.get(net_uuid, None)
2546

    
2547
    return netparams
2548

    
2549
  @locking.ssynchronized(_config_lock, shared=1)
2550
  def GetGroupNetParams(self, net, node):
2551
    """Locking wrapper of _UnlockedGetGroupNetParams()
2552

2553
    """
2554
    return self._UnlockedGetGroupNetParams(net, node)
2555

    
2556
  @locking.ssynchronized(_config_lock, shared=1)
2557
  def CheckIPInNodeGroup(self, ip, node):
2558
    """Check IP uniqueness in nodegroup.
2559

2560
    Check networks that are connected in the node's node group
2561
    if ip is contained in any of them. Used when creating/adding
2562
    a NIC to ensure uniqueness among nodegroups.
2563

2564
    @type ip: string
2565
    @param ip: ip address
2566
    @type node: string
2567
    @param node: node name
2568
    @rtype: (string, dict) or (None, None)
2569
    @return: (network name, netparams)
2570

2571
    """
2572
    if ip is None:
2573
      return (None, None)
2574
    node_info = self._UnlockedGetNodeInfo(node)
2575
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2576
    for net_uuid in nodegroup_info.networks.keys():
2577
      net_info = self._UnlockedGetNetwork(net_uuid)
2578
      pool = network.AddressPool(net_info)
2579
      if pool.Contains(ip):
2580
        return (net_info.name, nodegroup_info.networks[net_uuid])
2581

    
2582
    return (None, None)