Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 3d736ac9

History | View | Annotate | Download (86 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_uuid):
274
    """Return the network mac prefix if it exists or the cluster level default.
275

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

    
283
    return prefix
284

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

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

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

    
301
    return GenMac
302

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

307
    This should check the current instances for duplicates.
308

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

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

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

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

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

332
    """
333
    for act, addr, uuid, ext in self._temporary_ips.GetECReserved(ec_id):
334
      self._UnlockedCommitIp(act, uuid, addr, ext)
335

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

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

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

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

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

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

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

363
    This is just a wrapper around _UnlockedReleaseIp.
364

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

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

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

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

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

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

391
    """
392
    nobj = self._UnlockedGetNetwork(net_uuid)
393
    pool = network.AddressPool(nobj)
394
    try:
395
      isreserved = pool.IsReserved(address)
396
    except errors.AddressPoolError:
397
      raise errors.OpPrereqError("IP address '%s' not in network '%s'" %
398
                                 (address, nobj.name),
399
                                 errors.ECODE_INVAL)
400
    if isreserved:
401
      raise errors.OpPrereqError("IP address '%s' already in use" % address,
402
                                 errors.ECODE_INVAL)
403

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

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

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

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

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

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

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

433
    This checks the current disks for duplicates.
434

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

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

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

    
451
  def _AllDisks(self):
452
    """Compute the list of all Disks.
453

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

    
460
  def _AllNICs(self):
461
    """Compute the list of all NICs.
462

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

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

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

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

    
487
  def _GenerateUniqueID(self, ec_id):
488
    """Generate an unique UUID.
489

490
    This checks the current node, instances and disk names for
491
    duplicates.
492

493
    @rtype: string
494
    @return: the unique id
495

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

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

504
    This is just a wrapper over the unlocked version.
505

506
    @type ec_id: string
507
    @param ec_id: unique id for the job to reserve the id to
508

509
    """
510
    return self._GenerateUniqueID(ec_id)
511

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

515
    @rtype: list
516
    @return: the list of all MACs
517

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

    
524
    return result
525

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

529
    @rtype: list
530
    @return: the list of all DRBD secrets
531

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

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

    
546
    return result
547

    
548
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
549
    """Compute duplicate disk IDs
550

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

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

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

    
578
  def _UnlockedVerifyConfig(self):
579
    """Verify function.
580

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

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

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

    
608
    if cluster.master_node not in data.nodes:
609
      result.append("cluster has invalid primary node '%s'" %
610
                    cluster.master_node)
611

    
612
    def _helper(owner, attr, value, template):
613
      try:
614
        utils.ForceDictType(value, template)
615
      except errors.GenericError, err:
616
        result.append("%s has invalid %s: %s" % (owner, attr, err))
617

    
618
    def _helper_nic(owner, params):
619
      try:
620
        objects.NIC.CheckParameterSyntax(params)
621
      except errors.ConfigurationError, err:
622
        result.append("%s has invalid nicparams: %s" % (owner, err))
623

    
624
    def _helper_ipolicy(owner, params, check_std):
625
      try:
626
        objects.InstancePolicy.CheckParameterSyntax(params, check_std)
627
      except errors.ConfigurationError, err:
628
        result.append("%s has invalid instance policy: %s" % (owner, err))
629

    
630
    def _helper_ispecs(owner, params):
631
      for key, value in params.items():
632
        if key in constants.IPOLICY_ISPECS:
633
          fullkey = "ipolicy/" + key
634
          _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
635
        else:
636
          # FIXME: assuming list type
637
          if key in constants.IPOLICY_PARAMETERS:
638
            exp_type = float
639
          else:
640
            exp_type = list
641
          if not isinstance(value, exp_type):
642
            result.append("%s has invalid instance policy: for %s,"
643
                          " expecting %s, got %s" %
644
                          (owner, key, exp_type.__name__, type(value)))
645

    
646
    # check cluster parameters
647
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
648
            constants.BES_PARAMETER_TYPES)
649
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
650
            constants.NICS_PARAMETER_TYPES)
651
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
652
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
653
            constants.NDS_PARAMETER_TYPES)
654
    _helper_ipolicy("cluster", cluster.SimpleFillIPolicy({}), True)
655
    _helper_ispecs("cluster", cluster.SimpleFillIPolicy({}))
656

    
657
    # per-instance checks
658
    for instance_name in data.instances:
659
      instance = data.instances[instance_name]
660
      if instance.name != instance_name:
661
        result.append("instance '%s' is indexed by wrong name '%s'" %
662
                      (instance.name, instance_name))
663
      if instance.primary_node not in data.nodes:
664
        result.append("instance '%s' has invalid primary node '%s'" %
665
                      (instance_name, instance.primary_node))
666
      for snode in instance.secondary_nodes:
667
        if snode not in data.nodes:
668
          result.append("instance '%s' has invalid secondary node '%s'" %
669
                        (instance_name, snode))
670
      for idx, nic in enumerate(instance.nics):
671
        if nic.mac in seen_macs:
672
          result.append("instance '%s' has NIC %d mac %s duplicate" %
673
                        (instance_name, idx, nic.mac))
674
        else:
675
          seen_macs.append(nic.mac)
676
        if nic.nicparams:
677
          filled = cluster.SimpleFillNIC(nic.nicparams)
678
          owner = "instance %s nic %d" % (instance.name, idx)
679
          _helper(owner, "nicparams",
680
                  filled, constants.NICS_PARAMETER_TYPES)
681
          _helper_nic(owner, filled)
682

    
683
      # parameter checks
684
      if instance.beparams:
685
        _helper("instance %s" % instance.name, "beparams",
686
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
687

    
688
      # gather the drbd ports for duplicate checks
689
      for (idx, dsk) in enumerate(instance.disks):
690
        if dsk.dev_type in constants.LDS_DRBD:
691
          tcp_port = dsk.logical_id[2]
692
          if tcp_port not in ports:
693
            ports[tcp_port] = []
694
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
695
      # gather network port reservation
696
      net_port = getattr(instance, "network_port", None)
697
      if net_port is not None:
698
        if net_port not in ports:
699
          ports[net_port] = []
700
        ports[net_port].append((instance.name, "network port"))
701

    
702
      # instance disk verify
703
      for idx, disk in enumerate(instance.disks):
704
        result.extend(["instance '%s' disk %d error: %s" %
705
                       (instance.name, idx, msg) for msg in disk.Verify()])
706
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
707

    
708
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
709
      if wrong_names:
710
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
711
                         (idx, exp_name, actual_name))
712
                        for (idx, exp_name, actual_name) in wrong_names)
713

    
714
        result.append("Instance '%s' has wrongly named disks: %s" %
715
                      (instance.name, tmp))
716

    
717
    # cluster-wide pool of free ports
718
    for free_port in cluster.tcpudp_port_pool:
719
      if free_port not in ports:
720
        ports[free_port] = []
721
      ports[free_port].append(("cluster", "port marked as free"))
722

    
723
    # compute tcp/udp duplicate ports
724
    keys = ports.keys()
725
    keys.sort()
726
    for pnum in keys:
727
      pdata = ports[pnum]
728
      if len(pdata) > 1:
729
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
730
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
731

    
732
    # highest used tcp port check
733
    if keys:
734
      if keys[-1] > cluster.highest_used_port:
735
        result.append("Highest used port mismatch, saved %s, computed %s" %
736
                      (cluster.highest_used_port, keys[-1]))
737

    
738
    if not data.nodes[cluster.master_node].master_candidate:
739
      result.append("Master node is not a master candidate")
740

    
741
    # master candidate checks
742
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
743
    if mc_now < mc_max:
744
      result.append("Not enough master candidates: actual %d, target %d" %
745
                    (mc_now, mc_max))
746

    
747
    # node checks
748
    for node_name, node in data.nodes.items():
749
      if node.name != node_name:
750
        result.append("Node '%s' is indexed by wrong name '%s'" %
751
                      (node.name, node_name))
752
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
753
        result.append("Node %s state is invalid: master_candidate=%s,"
754
                      " drain=%s, offline=%s" %
755
                      (node.name, node.master_candidate, node.drained,
756
                       node.offline))
757
      if node.group not in data.nodegroups:
758
        result.append("Node '%s' has invalid group '%s'" %
759
                      (node.name, node.group))
760
      else:
761
        _helper("node %s" % node.name, "ndparams",
762
                cluster.FillND(node, data.nodegroups[node.group]),
763
                constants.NDS_PARAMETER_TYPES)
764
      used_globals = constants.NDC_GLOBALS.intersection(node.ndparams)
765
      if used_globals:
766
        result.append("Node '%s' has some global parameters set: %s" %
767
                      (node.name, utils.CommaJoin(used_globals)))
768

    
769
    # nodegroups checks
770
    nodegroups_names = set()
771
    for nodegroup_uuid in data.nodegroups:
772
      nodegroup = data.nodegroups[nodegroup_uuid]
773
      if nodegroup.uuid != nodegroup_uuid:
774
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
775
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
776
      if utils.UUID_RE.match(nodegroup.name.lower()):
777
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
778
                      (nodegroup.name, nodegroup.uuid))
779
      if nodegroup.name in nodegroups_names:
780
        result.append("duplicate node group name '%s'" % nodegroup.name)
781
      else:
782
        nodegroups_names.add(nodegroup.name)
783
      group_name = "group %s" % nodegroup.name
784
      _helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy),
785
                      False)
786
      _helper_ispecs(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy))
787
      if nodegroup.ndparams:
788
        _helper(group_name, "ndparams",
789
                cluster.SimpleFillND(nodegroup.ndparams),
790
                constants.NDS_PARAMETER_TYPES)
791

    
792
    # drbd minors check
793
    _, duplicates = self._UnlockedComputeDRBDMap()
794
    for node, minor, instance_a, instance_b in duplicates:
795
      result.append("DRBD minor %d on node %s is assigned twice to instances"
796
                    " %s and %s" % (minor, node, instance_a, instance_b))
797

    
798
    # IP checks
799
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
800
    ips = {}
801

    
802
    def _AddIpAddress(ip, name):
803
      ips.setdefault(ip, []).append(name)
804

    
805
    _AddIpAddress(cluster.master_ip, "cluster_ip")
806

    
807
    for node in data.nodes.values():
808
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
809
      if node.secondary_ip != node.primary_ip:
810
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
811

    
812
    for instance in data.instances.values():
813
      for idx, nic in enumerate(instance.nics):
814
        if nic.ip is None:
815
          continue
816

    
817
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
818
        nic_mode = nicparams[constants.NIC_MODE]
819
        nic_link = nicparams[constants.NIC_LINK]
820

    
821
        if nic_mode == constants.NIC_MODE_BRIDGED:
822
          link = "bridge:%s" % nic_link
823
        elif nic_mode == constants.NIC_MODE_ROUTED:
824
          link = "route:%s" % nic_link
825
        else:
826
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
827

    
828
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
829
                      "instance:%s/nic:%d" % (instance.name, idx))
830

    
831
    for ip, owners in ips.items():
832
      if len(owners) > 1:
833
        result.append("IP address %s is used by multiple owners: %s" %
834
                      (ip, utils.CommaJoin(owners)))
835

    
836
    return result
837

    
838
  @locking.ssynchronized(_config_lock, shared=1)
839
  def VerifyConfig(self):
840
    """Verify function.
841

842
    This is just a wrapper over L{_UnlockedVerifyConfig}.
843

844
    @rtype: list
845
    @return: a list of error messages; a non-empty list signifies
846
        configuration errors
847

848
    """
849
    return self._UnlockedVerifyConfig()
850

    
851
  def _UnlockedSetDiskID(self, disk, node_name):
852
    """Convert the unique ID to the ID needed on the target nodes.
853

854
    This is used only for drbd, which needs ip/port configuration.
855

856
    The routine descends down and updates its children also, because
857
    this helps when the only the top device is passed to the remote
858
    node.
859

860
    This function is for internal use, when the config lock is already held.
861

862
    """
863
    if disk.children:
864
      for child in disk.children:
865
        self._UnlockedSetDiskID(child, node_name)
866

    
867
    if disk.logical_id is None and disk.physical_id is not None:
868
      return
869
    if disk.dev_type == constants.LD_DRBD8:
870
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
871
      if node_name not in (pnode, snode):
872
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
873
                                        node_name)
874
      pnode_info = self._UnlockedGetNodeInfo(pnode)
875
      snode_info = self._UnlockedGetNodeInfo(snode)
876
      if pnode_info is None or snode_info is None:
877
        raise errors.ConfigurationError("Can't find primary or secondary node"
878
                                        " for %s" % str(disk))
879
      p_data = (pnode_info.secondary_ip, port)
880
      s_data = (snode_info.secondary_ip, port)
881
      if pnode == node_name:
882
        disk.physical_id = p_data + s_data + (pminor, secret)
883
      else: # it must be secondary, we tested above
884
        disk.physical_id = s_data + p_data + (sminor, secret)
885
    else:
886
      disk.physical_id = disk.logical_id
887
    return
888

    
889
  @locking.ssynchronized(_config_lock)
890
  def SetDiskID(self, disk, node_name):
891
    """Convert the unique ID to the ID needed on the target nodes.
892

893
    This is used only for drbd, which needs ip/port configuration.
894

895
    The routine descends down and updates its children also, because
896
    this helps when the only the top device is passed to the remote
897
    node.
898

899
    """
900
    return self._UnlockedSetDiskID(disk, node_name)
901

    
902
  @locking.ssynchronized(_config_lock)
903
  def AddTcpUdpPort(self, port):
904
    """Adds a new port to the available port pool.
905

906
    @warning: this method does not "flush" the configuration (via
907
        L{_WriteConfig}); callers should do that themselves once the
908
        configuration is stable
909

910
    """
911
    if not isinstance(port, int):
912
      raise errors.ProgrammerError("Invalid type passed for port")
913

    
914
    self._config_data.cluster.tcpudp_port_pool.add(port)
915

    
916
  @locking.ssynchronized(_config_lock, shared=1)
917
  def GetPortList(self):
918
    """Returns a copy of the current port list.
919

920
    """
921
    return self._config_data.cluster.tcpudp_port_pool.copy()
922

    
923
  @locking.ssynchronized(_config_lock)
924
  def AllocatePort(self):
925
    """Allocate a port.
926

927
    The port will be taken from the available port pool or from the
928
    default port range (and in this case we increase
929
    highest_used_port).
930

931
    """
932
    # If there are TCP/IP ports configured, we use them first.
933
    if self._config_data.cluster.tcpudp_port_pool:
934
      port = self._config_data.cluster.tcpudp_port_pool.pop()
935
    else:
936
      port = self._config_data.cluster.highest_used_port + 1
937
      if port >= constants.LAST_DRBD_PORT:
938
        raise errors.ConfigurationError("The highest used port is greater"
939
                                        " than %s. Aborting." %
940
                                        constants.LAST_DRBD_PORT)
941
      self._config_data.cluster.highest_used_port = port
942

    
943
    self._WriteConfig()
944
    return port
945

    
946
  def _UnlockedComputeDRBDMap(self):
947
    """Compute the used DRBD minor/nodes.
948

949
    @rtype: (dict, list)
950
    @return: dictionary of node_name: dict of minor: instance_name;
951
        the returned dict will have all the nodes in it (even if with
952
        an empty list), and a list of duplicates; if the duplicates
953
        list is not empty, the configuration is corrupted and its caller
954
        should raise an exception
955

956
    """
957
    def _AppendUsedPorts(instance_name, disk, used):
958
      duplicates = []
959
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
960
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
961
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
962
          assert node in used, ("Node '%s' of instance '%s' not found"
963
                                " in node list" % (node, instance_name))
964
          if port in used[node]:
965
            duplicates.append((node, port, instance_name, used[node][port]))
966
          else:
967
            used[node][port] = instance_name
968
      if disk.children:
969
        for child in disk.children:
970
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
971
      return duplicates
972

    
973
    duplicates = []
974
    my_dict = dict((node, {}) for node in self._config_data.nodes)
975
    for instance in self._config_data.instances.itervalues():
976
      for disk in instance.disks:
977
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
978
    for (node, minor), instance in self._temporary_drbds.iteritems():
979
      if minor in my_dict[node] and my_dict[node][minor] != instance:
980
        duplicates.append((node, minor, instance, my_dict[node][minor]))
981
      else:
982
        my_dict[node][minor] = instance
983
    return my_dict, duplicates
984

    
985
  @locking.ssynchronized(_config_lock)
986
  def ComputeDRBDMap(self):
987
    """Compute the used DRBD minor/nodes.
988

989
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
990

991
    @return: dictionary of node_name: dict of minor: instance_name;
992
        the returned dict will have all the nodes in it (even if with
993
        an empty list).
994

995
    """
996
    d_map, duplicates = self._UnlockedComputeDRBDMap()
997
    if duplicates:
998
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
999
                                      str(duplicates))
1000
    return d_map
1001

    
1002
  @locking.ssynchronized(_config_lock)
1003
  def AllocateDRBDMinor(self, nodes, instance):
1004
    """Allocate a drbd minor.
1005

1006
    The free minor will be automatically computed from the existing
1007
    devices. A node can be given multiple times in order to allocate
1008
    multiple minors. The result is the list of minors, in the same
1009
    order as the passed nodes.
1010

1011
    @type instance: string
1012
    @param instance: the instance for which we allocate minors
1013

1014
    """
1015
    assert isinstance(instance, basestring), \
1016
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
1017

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

    
1058
  def _UnlockedReleaseDRBDMinors(self, instance):
1059
    """Release temporary drbd minors allocated for a given instance.
1060

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

1065
    """
1066
    assert isinstance(instance, basestring), \
1067
           "Invalid argument passed to ReleaseDRBDMinors"
1068
    for key, name in self._temporary_drbds.items():
1069
      if name == instance:
1070
        del self._temporary_drbds[key]
1071

    
1072
  @locking.ssynchronized(_config_lock)
1073
  def ReleaseDRBDMinors(self, instance):
1074
    """Release temporary drbd minors allocated for a given instance.
1075

1076
    This should be called on the error paths, on the success paths
1077
    it's automatically called by the ConfigWriter add and update
1078
    functions.
1079

1080
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1081

1082
    @type instance: string
1083
    @param instance: the instance for which temporary minors should be
1084
                     released
1085

1086
    """
1087
    self._UnlockedReleaseDRBDMinors(instance)
1088

    
1089
  @locking.ssynchronized(_config_lock, shared=1)
1090
  def GetConfigVersion(self):
1091
    """Get the configuration version.
1092

1093
    @return: Config version
1094

1095
    """
1096
    return self._config_data.version
1097

    
1098
  @locking.ssynchronized(_config_lock, shared=1)
1099
  def GetClusterName(self):
1100
    """Get cluster name.
1101

1102
    @return: Cluster name
1103

1104
    """
1105
    return self._config_data.cluster.cluster_name
1106

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

1111
    @return: Master hostname
1112

1113
    """
1114
    return self._config_data.cluster.master_node
1115

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

1120
    @return: Master IP
1121

1122
    """
1123
    return self._config_data.cluster.master_ip
1124

    
1125
  @locking.ssynchronized(_config_lock, shared=1)
1126
  def GetMasterNetdev(self):
1127
    """Get the master network device for this cluster.
1128

1129
    """
1130
    return self._config_data.cluster.master_netdev
1131

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

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

    
1139
  @locking.ssynchronized(_config_lock, shared=1)
1140
  def GetUseExternalMipScript(self):
1141
    """Get flag representing whether to use the external master IP setup script.
1142

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

    
1146
  @locking.ssynchronized(_config_lock, shared=1)
1147
  def GetFileStorageDir(self):
1148
    """Get the file storage dir for this cluster.
1149

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

    
1153
  @locking.ssynchronized(_config_lock, shared=1)
1154
  def GetSharedFileStorageDir(self):
1155
    """Get the shared file storage dir for this cluster.
1156

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

    
1160
  @locking.ssynchronized(_config_lock, shared=1)
1161
  def GetHypervisorType(self):
1162
    """Get the hypervisor type for this cluster.
1163

1164
    """
1165
    return self._config_data.cluster.enabled_hypervisors[0]
1166

    
1167
  @locking.ssynchronized(_config_lock, shared=1)
1168
  def GetHostKey(self):
1169
    """Return the rsa hostkey from the config.
1170

1171
    @rtype: string
1172
    @return: the rsa hostkey
1173

1174
    """
1175
    return self._config_data.cluster.rsahostkeypub
1176

    
1177
  @locking.ssynchronized(_config_lock, shared=1)
1178
  def GetDefaultIAllocator(self):
1179
    """Get the default instance allocator for this cluster.
1180

1181
    """
1182
    return self._config_data.cluster.default_iallocator
1183

    
1184
  @locking.ssynchronized(_config_lock, shared=1)
1185
  def GetPrimaryIPFamily(self):
1186
    """Get cluster primary ip family.
1187

1188
    @return: primary ip family
1189

1190
    """
1191
    return self._config_data.cluster.primary_ip_family
1192

    
1193
  @locking.ssynchronized(_config_lock, shared=1)
1194
  def GetMasterNetworkParameters(self):
1195
    """Get network parameters of the master node.
1196

1197
    @rtype: L{object.MasterNetworkParameters}
1198
    @return: network parameters of the master node
1199

1200
    """
1201
    cluster = self._config_data.cluster
1202
    result = objects.MasterNetworkParameters(
1203
      name=cluster.master_node, ip=cluster.master_ip,
1204
      netmask=cluster.master_netmask, netdev=cluster.master_netdev,
1205
      ip_family=cluster.primary_ip_family)
1206

    
1207
    return result
1208

    
1209
  @locking.ssynchronized(_config_lock)
1210
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1211
    """Add a node group to the configuration.
1212

1213
    This method calls group.UpgradeConfig() to fill any missing attributes
1214
    according to their default values.
1215

1216
    @type group: L{objects.NodeGroup}
1217
    @param group: the NodeGroup object to add
1218
    @type ec_id: string
1219
    @param ec_id: unique id for the job to use when creating a missing UUID
1220
    @type check_uuid: bool
1221
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1222
                       it does, ensure that it does not exist in the
1223
                       configuration already
1224

1225
    """
1226
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1227
    self._WriteConfig()
1228

    
1229
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1230
    """Add a node group to the configuration.
1231

1232
    """
1233
    logging.info("Adding node group %s to configuration", group.name)
1234

    
1235
    # Some code might need to add a node group with a pre-populated UUID
1236
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1237
    # the "does this UUID" exist already check.
1238
    if check_uuid:
1239
      self._EnsureUUID(group, ec_id)
1240

    
1241
    try:
1242
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1243
    except errors.OpPrereqError:
1244
      pass
1245
    else:
1246
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1247
                                 " node group (UUID: %s)" %
1248
                                 (group.name, existing_uuid),
1249
                                 errors.ECODE_EXISTS)
1250

    
1251
    group.serial_no = 1
1252
    group.ctime = group.mtime = time.time()
1253
    group.UpgradeConfig()
1254

    
1255
    self._config_data.nodegroups[group.uuid] = group
1256
    self._config_data.cluster.serial_no += 1
1257

    
1258
  @locking.ssynchronized(_config_lock)
1259
  def RemoveNodeGroup(self, group_uuid):
1260
    """Remove a node group from the configuration.
1261

1262
    @type group_uuid: string
1263
    @param group_uuid: the UUID of the node group to remove
1264

1265
    """
1266
    logging.info("Removing node group %s from configuration", group_uuid)
1267

    
1268
    if group_uuid not in self._config_data.nodegroups:
1269
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1270

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

    
1274
    del self._config_data.nodegroups[group_uuid]
1275
    self._config_data.cluster.serial_no += 1
1276
    self._WriteConfig()
1277

    
1278
  def _UnlockedLookupNodeGroup(self, target):
1279
    """Lookup a node group's UUID.
1280

1281
    @type target: string or None
1282
    @param target: group name or UUID or None to look for the default
1283
    @rtype: string
1284
    @return: nodegroup UUID
1285
    @raises errors.OpPrereqError: when the target group cannot be found
1286

1287
    """
1288
    if target is None:
1289
      if len(self._config_data.nodegroups) != 1:
1290
        raise errors.OpPrereqError("More than one node group exists. Target"
1291
                                   " group must be specified explicitly.")
1292
      else:
1293
        return self._config_data.nodegroups.keys()[0]
1294
    if target in self._config_data.nodegroups:
1295
      return target
1296
    for nodegroup in self._config_data.nodegroups.values():
1297
      if nodegroup.name == target:
1298
        return nodegroup.uuid
1299
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1300
                               errors.ECODE_NOENT)
1301

    
1302
  @locking.ssynchronized(_config_lock, shared=1)
1303
  def LookupNodeGroup(self, target):
1304
    """Lookup a node group's UUID.
1305

1306
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1307

1308
    @type target: string or None
1309
    @param target: group name or UUID or None to look for the default
1310
    @rtype: string
1311
    @return: nodegroup UUID
1312

1313
    """
1314
    return self._UnlockedLookupNodeGroup(target)
1315

    
1316
  def _UnlockedGetNodeGroup(self, uuid):
1317
    """Lookup a node group.
1318

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

1324
    """
1325
    if uuid not in self._config_data.nodegroups:
1326
      return None
1327

    
1328
    return self._config_data.nodegroups[uuid]
1329

    
1330
  @locking.ssynchronized(_config_lock, shared=1)
1331
  def GetNodeGroup(self, uuid):
1332
    """Lookup a node group.
1333

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

1339
    """
1340
    return self._UnlockedGetNodeGroup(uuid)
1341

    
1342
  @locking.ssynchronized(_config_lock, shared=1)
1343
  def GetAllNodeGroupsInfo(self):
1344
    """Get the configuration of all node groups.
1345

1346
    """
1347
    return dict(self._config_data.nodegroups)
1348

    
1349
  @locking.ssynchronized(_config_lock, shared=1)
1350
  def GetNodeGroupList(self):
1351
    """Get a list of node groups.
1352

1353
    """
1354
    return self._config_data.nodegroups.keys()
1355

    
1356
  @locking.ssynchronized(_config_lock, shared=1)
1357
  def GetNodeGroupMembersByNodes(self, nodes):
1358
    """Get nodes which are member in the same nodegroups as the given nodes.
1359

1360
    """
1361
    ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1362
    return frozenset(member_name
1363
                     for node_name in nodes
1364
                     for member_name in
1365
                       self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1366

    
1367
  @locking.ssynchronized(_config_lock, shared=1)
1368
  def GetMultiNodeGroupInfo(self, group_uuids):
1369
    """Get the configuration of multiple node groups.
1370

1371
    @param group_uuids: List of node group UUIDs
1372
    @rtype: list
1373
    @return: List of tuples of (group_uuid, group_info)
1374

1375
    """
1376
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1377

    
1378
  @locking.ssynchronized(_config_lock)
1379
  def AddInstance(self, instance, ec_id):
1380
    """Add an instance to the config.
1381

1382
    This should be used after creating a new instance.
1383

1384
    @type instance: L{objects.Instance}
1385
    @param instance: the instance object
1386

1387
    """
1388
    if not isinstance(instance, objects.Instance):
1389
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1390

    
1391
    if instance.disk_template != constants.DT_DISKLESS:
1392
      all_lvs = instance.MapLVsByNode()
1393
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1394

    
1395
    all_macs = self._AllMACs()
1396
    for nic in instance.nics:
1397
      if nic.mac in all_macs:
1398
        raise errors.ConfigurationError("Cannot add instance %s:"
1399
                                        " MAC address '%s' already in use." %
1400
                                        (instance.name, nic.mac))
1401

    
1402
    self._EnsureUUID(instance, ec_id)
1403

    
1404
    instance.serial_no = 1
1405
    instance.ctime = instance.mtime = time.time()
1406
    self._config_data.instances[instance.name] = instance
1407
    self._config_data.cluster.serial_no += 1
1408
    self._UnlockedReleaseDRBDMinors(instance.name)
1409
    self._UnlockedCommitTemporaryIps(ec_id)
1410
    self._WriteConfig()
1411

    
1412
  def _EnsureUUID(self, item, ec_id):
1413
    """Ensures a given object has a valid UUID.
1414

1415
    @param item: the instance or node to be checked
1416
    @param ec_id: the execution context id for the uuid reservation
1417

1418
    """
1419
    if not item.uuid:
1420
      item.uuid = self._GenerateUniqueID(ec_id)
1421
    elif item.uuid in self._AllIDs(include_temporary=True):
1422
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1423
                                      " in use" % (item.name, item.uuid))
1424

    
1425
  def _SetInstanceStatus(self, instance_name, status):
1426
    """Set the instance's status to a given value.
1427

1428
    """
1429
    assert status in constants.ADMINST_ALL, \
1430
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1431

    
1432
    if instance_name not in self._config_data.instances:
1433
      raise errors.ConfigurationError("Unknown instance '%s'" %
1434
                                      instance_name)
1435
    instance = self._config_data.instances[instance_name]
1436
    if instance.admin_state != status:
1437
      instance.admin_state = status
1438
      instance.serial_no += 1
1439
      instance.mtime = time.time()
1440
      self._WriteConfig()
1441

    
1442
  @locking.ssynchronized(_config_lock)
1443
  def MarkInstanceUp(self, instance_name):
1444
    """Mark the instance status to up in the config.
1445

1446
    """
1447
    self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1448

    
1449
  @locking.ssynchronized(_config_lock)
1450
  def MarkInstanceOffline(self, instance_name):
1451
    """Mark the instance status to down in the config.
1452

1453
    """
1454
    self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1455

    
1456
  @locking.ssynchronized(_config_lock)
1457
  def RemoveInstance(self, instance_name):
1458
    """Remove the instance from the configuration.
1459

1460
    """
1461
    if instance_name not in self._config_data.instances:
1462
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1463

    
1464
    # If a network port has been allocated to the instance,
1465
    # return it to the pool of free ports.
1466
    inst = self._config_data.instances[instance_name]
1467
    network_port = getattr(inst, "network_port", None)
1468
    if network_port is not None:
1469
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1470

    
1471
    instance = self._UnlockedGetInstanceInfo(instance_name)
1472

    
1473
    for nic in instance.nics:
1474
      if nic.network and nic.ip:
1475
        # Return all IP addresses to the respective address pools
1476
        self._UnlockedCommitIp(constants.RELEASE_ACTION,
1477
                               nic.network, nic.ip, False)
1478

    
1479
    del self._config_data.instances[instance_name]
1480
    self._config_data.cluster.serial_no += 1
1481
    self._WriteConfig()
1482

    
1483
  @locking.ssynchronized(_config_lock)
1484
  def RenameInstance(self, old_name, new_name):
1485
    """Rename an instance.
1486

1487
    This needs to be done in ConfigWriter and not by RemoveInstance
1488
    combined with AddInstance as only we can guarantee an atomic
1489
    rename.
1490

1491
    """
1492
    if old_name not in self._config_data.instances:
1493
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1494

    
1495
    # Operate on a copy to not loose instance object in case of a failure
1496
    inst = self._config_data.instances[old_name].Copy()
1497
    inst.name = new_name
1498

    
1499
    for (idx, disk) in enumerate(inst.disks):
1500
      if disk.dev_type == constants.LD_FILE:
1501
        # rename the file paths in logical and physical id
1502
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1503
        disk.logical_id = (disk.logical_id[0],
1504
                           utils.PathJoin(file_storage_dir, inst.name,
1505
                                          "disk%s" % idx))
1506
        disk.physical_id = disk.logical_id
1507

    
1508
    # Actually replace instance object
1509
    del self._config_data.instances[old_name]
1510
    self._config_data.instances[inst.name] = inst
1511

    
1512
    # Force update of ssconf files
1513
    self._config_data.cluster.serial_no += 1
1514

    
1515
    self._WriteConfig()
1516

    
1517
  @locking.ssynchronized(_config_lock)
1518
  def MarkInstanceDown(self, instance_name):
1519
    """Mark the status of an instance to down in the configuration.
1520

1521
    """
1522
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1523

    
1524
  def _UnlockedGetInstanceList(self):
1525
    """Get the list of instances.
1526

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

1529
    """
1530
    return self._config_data.instances.keys()
1531

    
1532
  @locking.ssynchronized(_config_lock, shared=1)
1533
  def GetInstanceList(self):
1534
    """Get the list of instances.
1535

1536
    @return: array of instances, ex. ['instance2.example.com',
1537
        'instance1.example.com']
1538

1539
    """
1540
    return self._UnlockedGetInstanceList()
1541

    
1542
  def ExpandInstanceName(self, short_name):
1543
    """Attempt to expand an incomplete instance name.
1544

1545
    """
1546
    # Locking is done in L{ConfigWriter.GetInstanceList}
1547
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1548

    
1549
  def _UnlockedGetInstanceInfo(self, instance_name):
1550
    """Returns information about an instance.
1551

1552
    This function is for internal use, when the config lock is already held.
1553

1554
    """
1555
    if instance_name not in self._config_data.instances:
1556
      return None
1557

    
1558
    return self._config_data.instances[instance_name]
1559

    
1560
  @locking.ssynchronized(_config_lock, shared=1)
1561
  def GetInstanceInfo(self, instance_name):
1562
    """Returns information about an instance.
1563

1564
    It takes the information from the configuration file. Other information of
1565
    an instance are taken from the live systems.
1566

1567
    @param instance_name: name of the instance, e.g.
1568
        I{instance1.example.com}
1569

1570
    @rtype: L{objects.Instance}
1571
    @return: the instance object
1572

1573
    """
1574
    return self._UnlockedGetInstanceInfo(instance_name)
1575

    
1576
  @locking.ssynchronized(_config_lock, shared=1)
1577
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1578
    """Returns set of node group UUIDs for instance's nodes.
1579

1580
    @rtype: frozenset
1581

1582
    """
1583
    instance = self._UnlockedGetInstanceInfo(instance_name)
1584
    if not instance:
1585
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1586

    
1587
    if primary_only:
1588
      nodes = [instance.primary_node]
1589
    else:
1590
      nodes = instance.all_nodes
1591

    
1592
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1593
                     for node_name in nodes)
1594

    
1595
  @locking.ssynchronized(_config_lock, shared=1)
1596
  def GetInstanceNetworks(self, instance_name):
1597
    """Returns set of network UUIDs for instance's nics.
1598

1599
    @rtype: frozenset
1600

1601
    """
1602
    instance = self._UnlockedGetInstanceInfo(instance_name)
1603
    if not instance:
1604
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1605

    
1606
    networks = set()
1607
    for nic in instance.nics:
1608
      if nic.network:
1609
        networks.add(nic.network)
1610

    
1611
    return frozenset(networks)
1612

    
1613
  @locking.ssynchronized(_config_lock, shared=1)
1614
  def GetMultiInstanceInfo(self, instances):
1615
    """Get the configuration of multiple instances.
1616

1617
    @param instances: list of instance names
1618
    @rtype: list
1619
    @return: list of tuples (instance, instance_info), where
1620
        instance_info is what would GetInstanceInfo return for the
1621
        node, while keeping the original order
1622

1623
    """
1624
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1625

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

1630
    @rtype: dict
1631
    @return: dict of (instance, instance_info), where instance_info is what
1632
              would GetInstanceInfo return for the node
1633

1634
    """
1635
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1636
                    for instance in self._UnlockedGetInstanceList()])
1637
    return my_dict
1638

    
1639
  @locking.ssynchronized(_config_lock, shared=1)
1640
  def GetInstancesInfoByFilter(self, filter_fn):
1641
    """Get instance configuration with a filter.
1642

1643
    @type filter_fn: callable
1644
    @param filter_fn: Filter function receiving instance object as parameter,
1645
      returning boolean. Important: this function is called while the
1646
      configuration locks is held. It must not do any complex work or call
1647
      functions potentially leading to a deadlock. Ideally it doesn't call any
1648
      other functions and just compares instance attributes.
1649

1650
    """
1651
    return dict((name, inst)
1652
                for (name, inst) in self._config_data.instances.items()
1653
                if filter_fn(inst))
1654

    
1655
  @locking.ssynchronized(_config_lock)
1656
  def AddNode(self, node, ec_id):
1657
    """Add a node to the configuration.
1658

1659
    @type node: L{objects.Node}
1660
    @param node: a Node instance
1661

1662
    """
1663
    logging.info("Adding node %s to configuration", node.name)
1664

    
1665
    self._EnsureUUID(node, ec_id)
1666

    
1667
    node.serial_no = 1
1668
    node.ctime = node.mtime = time.time()
1669
    self._UnlockedAddNodeToGroup(node.name, node.group)
1670
    self._config_data.nodes[node.name] = node
1671
    self._config_data.cluster.serial_no += 1
1672
    self._WriteConfig()
1673

    
1674
  @locking.ssynchronized(_config_lock)
1675
  def RemoveNode(self, node_name):
1676
    """Remove a node from the configuration.
1677

1678
    """
1679
    logging.info("Removing node %s from configuration", node_name)
1680

    
1681
    if node_name not in self._config_data.nodes:
1682
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1683

    
1684
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1685
    del self._config_data.nodes[node_name]
1686
    self._config_data.cluster.serial_no += 1
1687
    self._WriteConfig()
1688

    
1689
  def ExpandNodeName(self, short_name):
1690
    """Attempt to expand an incomplete node name.
1691

1692
    """
1693
    # Locking is done in L{ConfigWriter.GetNodeList}
1694
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1695

    
1696
  def _UnlockedGetNodeInfo(self, node_name):
1697
    """Get the configuration of a node, as stored in the config.
1698

1699
    This function is for internal use, when the config lock is already
1700
    held.
1701

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

1704
    @rtype: L{objects.Node}
1705
    @return: the node object
1706

1707
    """
1708
    if node_name not in self._config_data.nodes:
1709
      return None
1710

    
1711
    return self._config_data.nodes[node_name]
1712

    
1713
  @locking.ssynchronized(_config_lock, shared=1)
1714
  def GetNodeInfo(self, node_name):
1715
    """Get the configuration of a node, as stored in the config.
1716

1717
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1718

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

1721
    @rtype: L{objects.Node}
1722
    @return: the node object
1723

1724
    """
1725
    return self._UnlockedGetNodeInfo(node_name)
1726

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

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

1733
    @rtype: (list, list)
1734
    @return: a tuple with two lists: the primary and the secondary instances
1735

1736
    """
1737
    pri = []
1738
    sec = []
1739
    for inst in self._config_data.instances.values():
1740
      if inst.primary_node == node_name:
1741
        pri.append(inst.name)
1742
      if node_name in inst.secondary_nodes:
1743
        sec.append(inst.name)
1744
    return (pri, sec)
1745

    
1746
  @locking.ssynchronized(_config_lock, shared=1)
1747
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1748
    """Get the instances of a node group.
1749

1750
    @param uuid: Node group UUID
1751
    @param primary_only: Whether to only consider primary nodes
1752
    @rtype: frozenset
1753
    @return: List of instance names in node group
1754

1755
    """
1756
    if primary_only:
1757
      nodes_fn = lambda inst: [inst.primary_node]
1758
    else:
1759
      nodes_fn = lambda inst: inst.all_nodes
1760

    
1761
    return frozenset(inst.name
1762
                     for inst in self._config_data.instances.values()
1763
                     for node_name in nodes_fn(inst)
1764
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1765

    
1766
  def _UnlockedGetNodeList(self):
1767
    """Return the list of nodes which are in the configuration.
1768

1769
    This function is for internal use, when the config lock is already
1770
    held.
1771

1772
    @rtype: list
1773

1774
    """
1775
    return self._config_data.nodes.keys()
1776

    
1777
  @locking.ssynchronized(_config_lock, shared=1)
1778
  def GetNodeList(self):
1779
    """Return the list of nodes which are in the configuration.
1780

1781
    """
1782
    return self._UnlockedGetNodeList()
1783

    
1784
  def _UnlockedGetOnlineNodeList(self):
1785
    """Return the list of nodes which are online.
1786

1787
    """
1788
    all_nodes = [self._UnlockedGetNodeInfo(node)
1789
                 for node in self._UnlockedGetNodeList()]
1790
    return [node.name for node in all_nodes if not node.offline]
1791

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

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

    
1799
  @locking.ssynchronized(_config_lock, shared=1)
1800
  def GetVmCapableNodeList(self):
1801
    """Return the list of nodes which are not vm capable.
1802

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

    
1808
  @locking.ssynchronized(_config_lock, shared=1)
1809
  def GetNonVmCapableNodeList(self):
1810
    """Return the list of nodes which are not vm capable.
1811

1812
    """
1813
    all_nodes = [self._UnlockedGetNodeInfo(node)
1814
                 for node in self._UnlockedGetNodeList()]
1815
    return [node.name for node in all_nodes if not node.vm_capable]
1816

    
1817
  @locking.ssynchronized(_config_lock, shared=1)
1818
  def GetMultiNodeInfo(self, nodes):
1819
    """Get the configuration of multiple nodes.
1820

1821
    @param nodes: list of node names
1822
    @rtype: list
1823
    @return: list of tuples of (node, node_info), where node_info is
1824
        what would GetNodeInfo return for the node, in the original
1825
        order
1826

1827
    """
1828
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1829

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

1834
    @rtype: dict
1835
    @return: dict of (node, node_info), where node_info is what
1836
              would GetNodeInfo return for the node
1837

1838
    """
1839
    return self._UnlockedGetAllNodesInfo()
1840

    
1841
  def _UnlockedGetAllNodesInfo(self):
1842
    """Gets configuration of all nodes.
1843

1844
    @note: See L{GetAllNodesInfo}
1845

1846
    """
1847
    return dict([(node, self._UnlockedGetNodeInfo(node))
1848
                 for node in self._UnlockedGetNodeList()])
1849

    
1850
  @locking.ssynchronized(_config_lock, shared=1)
1851
  def GetNodeGroupsFromNodes(self, nodes):
1852
    """Returns groups for a list of nodes.
1853

1854
    @type nodes: list of string
1855
    @param nodes: List of node names
1856
    @rtype: frozenset
1857

1858
    """
1859
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1860

    
1861
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1862
    """Get the number of current and maximum desired and possible candidates.
1863

1864
    @type exceptions: list
1865
    @param exceptions: if passed, list of nodes that should be ignored
1866
    @rtype: tuple
1867
    @return: tuple of (current, desired and possible, possible)
1868

1869
    """
1870
    mc_now = mc_should = mc_max = 0
1871
    for node in self._config_data.nodes.values():
1872
      if exceptions and node.name in exceptions:
1873
        continue
1874
      if not (node.offline or node.drained) and node.master_capable:
1875
        mc_max += 1
1876
      if node.master_candidate:
1877
        mc_now += 1
1878
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1879
    return (mc_now, mc_should, mc_max)
1880

    
1881
  @locking.ssynchronized(_config_lock, shared=1)
1882
  def GetMasterCandidateStats(self, exceptions=None):
1883
    """Get the number of current and maximum possible candidates.
1884

1885
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1886

1887
    @type exceptions: list
1888
    @param exceptions: if passed, list of nodes that should be ignored
1889
    @rtype: tuple
1890
    @return: tuple of (current, max)
1891

1892
    """
1893
    return self._UnlockedGetMasterCandidateStats(exceptions)
1894

    
1895
  @locking.ssynchronized(_config_lock)
1896
  def MaintainCandidatePool(self, exceptions):
1897
    """Try to grow the candidate pool to the desired size.
1898

1899
    @type exceptions: list
1900
    @param exceptions: if passed, list of nodes that should be ignored
1901
    @rtype: list
1902
    @return: list with the adjusted nodes (L{objects.Node} instances)
1903

1904
    """
1905
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1906
    mod_list = []
1907
    if mc_now < mc_max:
1908
      node_list = self._config_data.nodes.keys()
1909
      random.shuffle(node_list)
1910
      for name in node_list:
1911
        if mc_now >= mc_max:
1912
          break
1913
        node = self._config_data.nodes[name]
1914
        if (node.master_candidate or node.offline or node.drained or
1915
            node.name in exceptions or not node.master_capable):
1916
          continue
1917
        mod_list.append(node)
1918
        node.master_candidate = True
1919
        node.serial_no += 1
1920
        mc_now += 1
1921
      if mc_now != mc_max:
1922
        # this should not happen
1923
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1924
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1925
      if mod_list:
1926
        self._config_data.cluster.serial_no += 1
1927
        self._WriteConfig()
1928

    
1929
    return mod_list
1930

    
1931
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1932
    """Add a given node to the specified group.
1933

1934
    """
1935
    if nodegroup_uuid not in self._config_data.nodegroups:
1936
      # This can happen if a node group gets deleted between its lookup and
1937
      # when we're adding the first node to it, since we don't keep a lock in
1938
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1939
      # is not found anymore.
1940
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1941
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1942
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1943

    
1944
  def _UnlockedRemoveNodeFromGroup(self, node):
1945
    """Remove a given node from its group.
1946

1947
    """
1948
    nodegroup = node.group
1949
    if nodegroup not in self._config_data.nodegroups:
1950
      logging.warning("Warning: node '%s' has unknown node group '%s'"
1951
                      " (while being removed from it)", node.name, nodegroup)
1952
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1953
    if node.name not in nodegroup_obj.members:
1954
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
1955
                      " (while being removed from it)", node.name, nodegroup)
1956
    else:
1957
      nodegroup_obj.members.remove(node.name)
1958

    
1959
  @locking.ssynchronized(_config_lock)
1960
  def AssignGroupNodes(self, mods):
1961
    """Changes the group of a number of nodes.
1962

1963
    @type mods: list of tuples; (node name, new group UUID)
1964
    @param mods: Node membership modifications
1965

1966
    """
1967
    groups = self._config_data.nodegroups
1968
    nodes = self._config_data.nodes
1969

    
1970
    resmod = []
1971

    
1972
    # Try to resolve names/UUIDs first
1973
    for (node_name, new_group_uuid) in mods:
1974
      try:
1975
        node = nodes[node_name]
1976
      except KeyError:
1977
        raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1978

    
1979
      if node.group == new_group_uuid:
1980
        # Node is being assigned to its current group
1981
        logging.debug("Node '%s' was assigned to its current group (%s)",
1982
                      node_name, node.group)
1983
        continue
1984

    
1985
      # Try to find current group of node
1986
      try:
1987
        old_group = groups[node.group]
1988
      except KeyError:
1989
        raise errors.ConfigurationError("Unable to find old group '%s'" %
1990
                                        node.group)
1991

    
1992
      # Try to find new group for node
1993
      try:
1994
        new_group = groups[new_group_uuid]
1995
      except KeyError:
1996
        raise errors.ConfigurationError("Unable to find new group '%s'" %
1997
                                        new_group_uuid)
1998

    
1999
      assert node.name in old_group.members, \
2000
        ("Inconsistent configuration: node '%s' not listed in members for its"
2001
         " old group '%s'" % (node.name, old_group.uuid))
2002
      assert node.name not in new_group.members, \
2003
        ("Inconsistent configuration: node '%s' already listed in members for"
2004
         " its new group '%s'" % (node.name, new_group.uuid))
2005

    
2006
      resmod.append((node, old_group, new_group))
2007

    
2008
    # Apply changes
2009
    for (node, old_group, new_group) in resmod:
2010
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
2011
        "Assigning to current group is not possible"
2012

    
2013
      node.group = new_group.uuid
2014

    
2015
      # Update members of involved groups
2016
      if node.name in old_group.members:
2017
        old_group.members.remove(node.name)
2018
      if node.name not in new_group.members:
2019
        new_group.members.append(node.name)
2020

    
2021
    # Update timestamps and serials (only once per node/group object)
2022
    now = time.time()
2023
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
2024
      obj.serial_no += 1
2025
      obj.mtime = now
2026

    
2027
    # Force ssconf update
2028
    self._config_data.cluster.serial_no += 1
2029

    
2030
    self._WriteConfig()
2031

    
2032
  def _BumpSerialNo(self):
2033
    """Bump up the serial number of the config.
2034

2035
    """
2036
    self._config_data.serial_no += 1
2037
    self._config_data.mtime = time.time()
2038

    
2039
  def _AllUUIDObjects(self):
2040
    """Returns all objects with uuid attributes.
2041

2042
    """
2043
    return (self._config_data.instances.values() +
2044
            self._config_data.nodes.values() +
2045
            self._config_data.nodegroups.values() +
2046
            self._config_data.networks.values() +
2047
            self._AllDisks() +
2048
            self._AllNICs() +
2049
            [self._config_data.cluster])
2050

    
2051
  def _OpenConfig(self, accept_foreign):
2052
    """Read the config data from disk.
2053

2054
    """
2055
    raw_data = utils.ReadFile(self._cfg_file)
2056

    
2057
    try:
2058
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
2059
    except Exception, err:
2060
      raise errors.ConfigurationError(err)
2061

    
2062
    # Make sure the configuration has the right version
2063
    _ValidateConfig(data)
2064

    
2065
    if (not hasattr(data, "cluster") or
2066
        not hasattr(data.cluster, "rsahostkeypub")):
2067
      raise errors.ConfigurationError("Incomplete configuration"
2068
                                      " (missing cluster.rsahostkeypub)")
2069

    
2070
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
2071
      msg = ("The configuration denotes node %s as master, while my"
2072
             " hostname is %s; opening a foreign configuration is only"
2073
             " possible in accept_foreign mode" %
2074
             (data.cluster.master_node, self._my_hostname))
2075
      raise errors.ConfigurationError(msg)
2076

    
2077
    self._config_data = data
2078
    # reset the last serial as -1 so that the next write will cause
2079
    # ssconf update
2080
    self._last_cluster_serial = -1
2081

    
2082
    # Upgrade configuration if needed
2083
    self._UpgradeConfig()
2084

    
2085
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2086

    
2087
  def _UpgradeConfig(self):
2088
    """Run any upgrade steps.
2089

2090
    This method performs both in-object upgrades and also update some data
2091
    elements that need uniqueness across the whole configuration or interact
2092
    with other objects.
2093

2094
    @warning: this function will call L{_WriteConfig()}, but also
2095
        L{DropECReservations} so it needs to be called only from a
2096
        "safe" place (the constructor). If one wanted to call it with
2097
        the lock held, a DropECReservationUnlocked would need to be
2098
        created first, to avoid causing deadlock.
2099

2100
    """
2101
    # Keep a copy of the persistent part of _config_data to check for changes
2102
    # Serialization doesn't guarantee order in dictionaries
2103
    oldconf = copy.deepcopy(self._config_data.ToDict())
2104

    
2105
    # In-object upgrades
2106
    self._config_data.UpgradeConfig()
2107

    
2108
    for item in self._AllUUIDObjects():
2109
      if item.uuid is None:
2110
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
2111
    if not self._config_data.nodegroups:
2112
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
2113
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
2114
                                            members=[])
2115
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
2116
    for node in self._config_data.nodes.values():
2117
      if not node.group:
2118
        node.group = self.LookupNodeGroup(None)
2119
      # This is technically *not* an upgrade, but needs to be done both when
2120
      # nodegroups are being added, and upon normally loading the config,
2121
      # because the members list of a node group is discarded upon
2122
      # serializing/deserializing the object.
2123
      self._UnlockedAddNodeToGroup(node.name, node.group)
2124

    
2125
    modified = (oldconf != self._config_data.ToDict())
2126
    if modified:
2127
      self._WriteConfig()
2128
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
2129
      # only called at config init time, without the lock held
2130
      self.DropECReservations(_UPGRADE_CONFIG_JID)
2131

    
2132
  def _DistributeConfig(self, feedback_fn):
2133
    """Distribute the configuration to the other nodes.
2134

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

2138
    """
2139
    if self._offline:
2140
      return True
2141

    
2142
    bad = False
2143

    
2144
    node_list = []
2145
    addr_list = []
2146
    myhostname = self._my_hostname
2147
    # we can skip checking whether _UnlockedGetNodeInfo returns None
2148
    # since the node list comes from _UnlocketGetNodeList, and we are
2149
    # called with the lock held, so no modifications should take place
2150
    # in between
2151
    for node_name in self._UnlockedGetNodeList():
2152
      if node_name == myhostname:
2153
        continue
2154
      node_info = self._UnlockedGetNodeInfo(node_name)
2155
      if not node_info.master_candidate:
2156
        continue
2157
      node_list.append(node_info.name)
2158
      addr_list.append(node_info.primary_ip)
2159

    
2160
    # TODO: Use dedicated resolver talking to config writer for name resolution
2161
    result = \
2162
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2163
    for to_node, to_result in result.items():
2164
      msg = to_result.fail_msg
2165
      if msg:
2166
        msg = ("Copy of file %s to node %s failed: %s" %
2167
               (self._cfg_file, to_node, msg))
2168
        logging.error(msg)
2169

    
2170
        if feedback_fn:
2171
          feedback_fn(msg)
2172

    
2173
        bad = True
2174

    
2175
    return not bad
2176

    
2177
  def _WriteConfig(self, destination=None, feedback_fn=None):
2178
    """Write the configuration data to persistent storage.
2179

2180
    """
2181
    assert feedback_fn is None or callable(feedback_fn)
2182

    
2183
    # Warn on config errors, but don't abort the save - the
2184
    # configuration has already been modified, and we can't revert;
2185
    # the best we can do is to warn the user and save as is, leaving
2186
    # recovery to the user
2187
    config_errors = self._UnlockedVerifyConfig()
2188
    if config_errors:
2189
      errmsg = ("Configuration data is not consistent: %s" %
2190
                (utils.CommaJoin(config_errors)))
2191
      logging.critical(errmsg)
2192
      if feedback_fn:
2193
        feedback_fn(errmsg)
2194

    
2195
    if destination is None:
2196
      destination = self._cfg_file
2197
    self._BumpSerialNo()
2198
    txt = serializer.Dump(self._config_data.ToDict())
2199

    
2200
    getents = self._getents()
2201
    try:
2202
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2203
                               close=False, gid=getents.confd_gid, mode=0640)
2204
    except errors.LockError:
2205
      raise errors.ConfigurationError("The configuration file has been"
2206
                                      " modified since the last write, cannot"
2207
                                      " update")
2208
    try:
2209
      self._cfg_id = utils.GetFileID(fd=fd)
2210
    finally:
2211
      os.close(fd)
2212

    
2213
    self.write_count += 1
2214

    
2215
    # and redistribute the config file to master candidates
2216
    self._DistributeConfig(feedback_fn)
2217

    
2218
    # Write ssconf files on all nodes (including locally)
2219
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2220
      if not self._offline:
2221
        result = self._GetRpc(None).call_write_ssconf_files(
2222
          self._UnlockedGetOnlineNodeList(),
2223
          self._UnlockedGetSsconfValues())
2224

    
2225
        for nname, nresu in result.items():
2226
          msg = nresu.fail_msg
2227
          if msg:
2228
            errmsg = ("Error while uploading ssconf files to"
2229
                      " node %s: %s" % (nname, msg))
2230
            logging.warning(errmsg)
2231

    
2232
            if feedback_fn:
2233
              feedback_fn(errmsg)
2234

    
2235
      self._last_cluster_serial = self._config_data.cluster.serial_no
2236

    
2237
  def _UnlockedGetSsconfValues(self):
2238
    """Return the values needed by ssconf.
2239

2240
    @rtype: dict
2241
    @return: a dictionary with keys the ssconf names and values their
2242
        associated value
2243

2244
    """
2245
    fn = "\n".join
2246
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
2247
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
2248
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
2249
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2250
                    for ninfo in node_info]
2251
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2252
                    for ninfo in node_info]
2253

    
2254
    instance_data = fn(instance_names)
2255
    off_data = fn(node.name for node in node_info if node.offline)
2256
    on_data = fn(node.name for node in node_info if not node.offline)
2257
    mc_data = fn(node.name for node in node_info if node.master_candidate)
2258
    mc_ips_data = fn(node.primary_ip for node in node_info
2259
                     if node.master_candidate)
2260
    node_data = fn(node_names)
2261
    node_pri_ips_data = fn(node_pri_ips)
2262
    node_snd_ips_data = fn(node_snd_ips)
2263

    
2264
    cluster = self._config_data.cluster
2265
    cluster_tags = fn(cluster.GetTags())
2266

    
2267
    hypervisor_list = fn(cluster.enabled_hypervisors)
2268

    
2269
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2270

    
2271
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2272
                  self._config_data.nodegroups.values()]
2273
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2274
    networks = ["%s %s" % (net.uuid, net.name) for net in
2275
                self._config_data.networks.values()]
2276
    networks_data = fn(utils.NiceSort(networks))
2277

    
2278
    ssconf_values = {
2279
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
2280
      constants.SS_CLUSTER_TAGS: cluster_tags,
2281
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2282
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2283
      constants.SS_MASTER_CANDIDATES: mc_data,
2284
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2285
      constants.SS_MASTER_IP: cluster.master_ip,
2286
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
2287
      constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2288
      constants.SS_MASTER_NODE: cluster.master_node,
2289
      constants.SS_NODE_LIST: node_data,
2290
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2291
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2292
      constants.SS_OFFLINE_NODES: off_data,
2293
      constants.SS_ONLINE_NODES: on_data,
2294
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2295
      constants.SS_INSTANCE_LIST: instance_data,
2296
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2297
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
2298
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2299
      constants.SS_UID_POOL: uid_pool,
2300
      constants.SS_NODEGROUPS: nodegroups_data,
2301
      constants.SS_NETWORKS: networks_data,
2302
      }
2303
    bad_values = [(k, v) for k, v in ssconf_values.items()
2304
                  if not isinstance(v, (str, basestring))]
2305
    if bad_values:
2306
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2307
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2308
                                      " values: %s" % err)
2309
    return ssconf_values
2310

    
2311
  @locking.ssynchronized(_config_lock, shared=1)
2312
  def GetSsconfValues(self):
2313
    """Wrapper using lock around _UnlockedGetSsconf().
2314

2315
    """
2316
    return self._UnlockedGetSsconfValues()
2317

    
2318
  @locking.ssynchronized(_config_lock, shared=1)
2319
  def GetVGName(self):
2320
    """Return the volume group name.
2321

2322
    """
2323
    return self._config_data.cluster.volume_group_name
2324

    
2325
  @locking.ssynchronized(_config_lock)
2326
  def SetVGName(self, vg_name):
2327
    """Set the volume group name.
2328

2329
    """
2330
    self._config_data.cluster.volume_group_name = vg_name
2331
    self._config_data.cluster.serial_no += 1
2332
    self._WriteConfig()
2333

    
2334
  @locking.ssynchronized(_config_lock, shared=1)
2335
  def GetDRBDHelper(self):
2336
    """Return DRBD usermode helper.
2337

2338
    """
2339
    return self._config_data.cluster.drbd_usermode_helper
2340

    
2341
  @locking.ssynchronized(_config_lock)
2342
  def SetDRBDHelper(self, drbd_helper):
2343
    """Set DRBD usermode helper.
2344

2345
    """
2346
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2347
    self._config_data.cluster.serial_no += 1
2348
    self._WriteConfig()
2349

    
2350
  @locking.ssynchronized(_config_lock, shared=1)
2351
  def GetMACPrefix(self):
2352
    """Return the mac prefix.
2353

2354
    """
2355
    return self._config_data.cluster.mac_prefix
2356

    
2357
  @locking.ssynchronized(_config_lock, shared=1)
2358
  def GetClusterInfo(self):
2359
    """Returns information about the cluster
2360

2361
    @rtype: L{objects.Cluster}
2362
    @return: the cluster object
2363

2364
    """
2365
    return self._config_data.cluster
2366

    
2367
  @locking.ssynchronized(_config_lock, shared=1)
2368
  def HasAnyDiskOfType(self, dev_type):
2369
    """Check if in there is at disk of the given type in the configuration.
2370

2371
    """
2372
    return self._config_data.HasAnyDiskOfType(dev_type)
2373

    
2374
  @locking.ssynchronized(_config_lock)
2375
  def Update(self, target, feedback_fn, ec_id=None):
2376
    """Notify function to be called after updates.
2377

2378
    This function must be called when an object (as returned by
2379
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2380
    caller wants the modifications saved to the backing store. Note
2381
    that all modified objects will be saved, but the target argument
2382
    is the one the caller wants to ensure that it's saved.
2383

2384
    @param target: an instance of either L{objects.Cluster},
2385
        L{objects.Node} or L{objects.Instance} which is existing in
2386
        the cluster
2387
    @param feedback_fn: Callable feedback function
2388

2389
    """
2390
    if self._config_data is None:
2391
      raise errors.ProgrammerError("Configuration file not read,"
2392
                                   " cannot save.")
2393
    update_serial = False
2394
    if isinstance(target, objects.Cluster):
2395
      test = target == self._config_data.cluster
2396
    elif isinstance(target, objects.Node):
2397
      test = target in self._config_data.nodes.values()
2398
      update_serial = True
2399
    elif isinstance(target, objects.Instance):
2400
      test = target in self._config_data.instances.values()
2401
    elif isinstance(target, objects.NodeGroup):
2402
      test = target in self._config_data.nodegroups.values()
2403
    elif isinstance(target, objects.Network):
2404
      test = target in self._config_data.networks.values()
2405
    else:
2406
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2407
                                   " ConfigWriter.Update" % type(target))
2408
    if not test:
2409
      raise errors.ConfigurationError("Configuration updated since object"
2410
                                      " has been read or unknown object")
2411
    target.serial_no += 1
2412
    target.mtime = now = time.time()
2413

    
2414
    if update_serial:
2415
      # for node updates, we need to increase the cluster serial too
2416
      self._config_data.cluster.serial_no += 1
2417
      self._config_data.cluster.mtime = now
2418

    
2419
    if isinstance(target, objects.Instance):
2420
      self._UnlockedReleaseDRBDMinors(target.name)
2421

    
2422
    # Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
2423
    self._UnlockedCommitTemporaryIps(ec_id)
2424

    
2425
    self._WriteConfig(feedback_fn=feedback_fn)
2426

    
2427
  @locking.ssynchronized(_config_lock)
2428
  def DropECReservations(self, ec_id):
2429
    """Drop per-execution-context reservations
2430

2431
    """
2432
    for rm in self._all_rms:
2433
      rm.DropECReservations(ec_id)
2434

    
2435
  @locking.ssynchronized(_config_lock, shared=1)
2436
  def GetAllNetworksInfo(self):
2437
    """Get configuration info of all the networks.
2438

2439
    """
2440
    return dict(self._config_data.networks)
2441

    
2442
  def _UnlockedGetNetworkList(self):
2443
    """Get the list of networks.
2444

2445
    This function is for internal use, when the config lock is already held.
2446

2447
    """
2448
    return self._config_data.networks.keys()
2449

    
2450
  @locking.ssynchronized(_config_lock, shared=1)
2451
  def GetNetworkList(self):
2452
    """Get the list of networks.
2453

2454
    @return: array of networks, ex. ["main", "vlan100", "200]
2455

2456
    """
2457
    return self._UnlockedGetNetworkList()
2458

    
2459
  @locking.ssynchronized(_config_lock, shared=1)
2460
  def GetNetworkNames(self):
2461
    """Get a list of network names
2462

2463
    """
2464
    names = [net.name
2465
             for net in self._config_data.networks.values()]
2466
    return names
2467

    
2468
  def _UnlockedGetNetwork(self, uuid):
2469
    """Returns information about a network.
2470

2471
    This function is for internal use, when the config lock is already held.
2472

2473
    """
2474
    if uuid not in self._config_data.networks:
2475
      return None
2476

    
2477
    return self._config_data.networks[uuid]
2478

    
2479
  @locking.ssynchronized(_config_lock, shared=1)
2480
  def GetNetwork(self, uuid):
2481
    """Returns information about a network.
2482

2483
    It takes the information from the configuration file.
2484

2485
    @param uuid: UUID of the network
2486

2487
    @rtype: L{objects.Network}
2488
    @return: the network object
2489

2490
    """
2491
    return self._UnlockedGetNetwork(uuid)
2492

    
2493
  @locking.ssynchronized(_config_lock)
2494
  def AddNetwork(self, net, ec_id, check_uuid=True):
2495
    """Add a network to the configuration.
2496

2497
    @type net: L{objects.Network}
2498
    @param net: the Network object to add
2499
    @type ec_id: string
2500
    @param ec_id: unique id for the job to use when creating a missing UUID
2501

2502
    """
2503
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2504
    self._WriteConfig()
2505

    
2506
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2507
    """Add a network to the configuration.
2508

2509
    """
2510
    logging.info("Adding network %s to configuration", net.name)
2511

    
2512
    if check_uuid:
2513
      self._EnsureUUID(net, ec_id)
2514

    
2515
    net.serial_no = 1
2516
    self._config_data.networks[net.uuid] = net
2517
    self._config_data.cluster.serial_no += 1
2518

    
2519
  def _UnlockedLookupNetwork(self, target):
2520
    """Lookup a network's UUID.
2521

2522
    @type target: string
2523
    @param target: network name or UUID
2524
    @rtype: string
2525
    @return: network UUID
2526
    @raises errors.OpPrereqError: when the target network cannot be found
2527

2528
    """
2529
    if target is None:
2530
      return None
2531
    if target in self._config_data.networks:
2532
      return target
2533
    for net in self._config_data.networks.values():
2534
      if net.name == target:
2535
        return net.uuid
2536
    raise errors.OpPrereqError("Network '%s' not found" % target,
2537
                               errors.ECODE_NOENT)
2538

    
2539
  @locking.ssynchronized(_config_lock, shared=1)
2540
  def LookupNetwork(self, target):
2541
    """Lookup a network's UUID.
2542

2543
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2544

2545
    @type target: string
2546
    @param target: network name or UUID
2547
    @rtype: string
2548
    @return: network UUID
2549

2550
    """
2551
    return self._UnlockedLookupNetwork(target)
2552

    
2553
  @locking.ssynchronized(_config_lock)
2554
  def RemoveNetwork(self, network_uuid):
2555
    """Remove a network from the configuration.
2556

2557
    @type network_uuid: string
2558
    @param network_uuid: the UUID of the network to remove
2559

2560
    """
2561
    logging.info("Removing network %s from configuration", network_uuid)
2562

    
2563
    if network_uuid not in self._config_data.networks:
2564
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2565

    
2566
    del self._config_data.networks[network_uuid]
2567
    self._config_data.cluster.serial_no += 1
2568
    self._WriteConfig()
2569

    
2570
  def _UnlockedGetGroupNetParams(self, net_uuid, node):
2571
    """Get the netparams (mode, link) of a network.
2572

2573
    Get a network's netparams for a given node.
2574

2575
    @type net_uuid: string
2576
    @param net_uuid: network uuid
2577
    @type node: string
2578
    @param node: node name
2579
    @rtype: dict or None
2580
    @return: netparams
2581

2582
    """
2583
    node_info = self._UnlockedGetNodeInfo(node)
2584
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2585
    netparams = nodegroup_info.networks.get(net_uuid, None)
2586

    
2587
    return netparams
2588

    
2589
  @locking.ssynchronized(_config_lock, shared=1)
2590
  def GetGroupNetParams(self, net_uuid, node):
2591
    """Locking wrapper of _UnlockedGetGroupNetParams()
2592

2593
    """
2594
    return self._UnlockedGetGroupNetParams(net_uuid, node)
2595

    
2596
  @locking.ssynchronized(_config_lock, shared=1)
2597
  def CheckIPInNodeGroup(self, ip, node):
2598
    """Check IP uniqueness in nodegroup.
2599

2600
    Check networks that are connected in the node's node group
2601
    if ip is contained in any of them. Used when creating/adding
2602
    a NIC to ensure uniqueness among nodegroups.
2603

2604
    @type ip: string
2605
    @param ip: ip address
2606
    @type node: string
2607
    @param node: node name
2608
    @rtype: (string, dict) or (None, None)
2609
    @return: (network name, netparams)
2610

2611
    """
2612
    if ip is None:
2613
      return (None, None)
2614
    node_info = self._UnlockedGetNodeInfo(node)
2615
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2616
    for net_uuid in nodegroup_info.networks.keys():
2617
      net_info = self._UnlockedGetNetwork(net_uuid)
2618
      pool = network.AddressPool(net_info)
2619
      if pool.Contains(ip):
2620
        return (net_info.name, nodegroup_info.networks[net_uuid])
2621

    
2622
    return (None, None)