Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 11e90588

History | View | Annotate | Download (88.5 kB)

1
#
2
#
3

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

    
21

    
22
"""Configuration management for Ganeti
23

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

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

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

32
"""
33

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

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

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

    
57

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

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

    
63

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

67
  This only verifies the version of the configuration.
68

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

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

    
76

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

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

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

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

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

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

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

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

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

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

126
    """
127
    assert callable(generate_one_fn)
128

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

    
142

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

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

    
149

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

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

159
  """
160
  result = []
161

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

    
167
  return result
168

    
169

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

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

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

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

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

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

216
    """
217
    self._context = context
218

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
283
    return prefix
284

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

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

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

    
301
    return GenMac
302

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

307
    This should check the current instances for duplicates.
308

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

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

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

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

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

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

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

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

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

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

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

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

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

363
    This is just a wrapper around _UnlockedReleaseIp.
364

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

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

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

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

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

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

390
    """
391
    nobj = self._UnlockedGetNetwork(net_uuid)
392
    pool = network.AddressPool(nobj)
393
    try:
394
      isreserved = pool.IsReserved(address)
395
      isextreserved = pool.IsReserved(address, external=True)
396
    except errors.AddressPoolError:
397
      raise errors.ReservationError("IP address not in network")
398
    if isreserved:
399
      raise errors.ReservationError("IP address already in use")
400
    if check and isextreserved:
401
      raise errors.ReservationError("IP is externally reserved")
402

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

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

411
    """
412
    if net_uuid:
413
      return self._UnlockedReserveIp(net_uuid, address, ec_id, check)
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 (recursively, including children).
453

454
    """
455
    def DiskAndAllChildren(disk):
456
      """Returns a list containing the given disk and all of his children.
457

458
      """
459
      disks = [disk]
460
      if disk.children:
461
        for child_disk in disk.children:
462
          disks.extend(DiskAndAllChildren(child_disk))
463
      return disks
464

    
465
    disks = []
466
    for instance in self._config_data.instances.values():
467
      for disk in instance.disks:
468
        disks.extend(DiskAndAllChildren(disk))
469
    return disks
470

    
471
  def _AllNICs(self):
472
    """Compute the list of all NICs.
473

474
    """
475
    nics = []
476
    for instance in self._config_data.instances.values():
477
      nics.extend(instance.nics)
478
    return nics
479

    
480
  def _AllIDs(self, include_temporary):
481
    """Compute the list of all UUIDs and names we have.
482

483
    @type include_temporary: boolean
484
    @param include_temporary: whether to include the _temporary_ids set
485
    @rtype: set
486
    @return: a set of IDs
487

488
    """
489
    existing = set()
490
    if include_temporary:
491
      existing.update(self._temporary_ids.GetReserved())
492
    existing.update(self._AllLVs())
493
    existing.update(self._config_data.instances.keys())
494
    existing.update(self._config_data.nodes.keys())
495
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
496
    return existing
497

    
498
  def _GenerateUniqueID(self, ec_id):
499
    """Generate an unique UUID.
500

501
    This checks the current node, instances and disk names for
502
    duplicates.
503

504
    @rtype: string
505
    @return: the unique id
506

507
    """
508
    existing = self._AllIDs(include_temporary=False)
509
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
510

    
511
  @locking.ssynchronized(_config_lock, shared=1)
512
  def GenerateUniqueID(self, ec_id):
513
    """Generate an unique ID.
514

515
    This is just a wrapper over the unlocked version.
516

517
    @type ec_id: string
518
    @param ec_id: unique id for the job to reserve the id to
519

520
    """
521
    return self._GenerateUniqueID(ec_id)
522

    
523
  def _AllMACs(self):
524
    """Return all MACs present in the config.
525

526
    @rtype: list
527
    @return: the list of all MACs
528

529
    """
530
    result = []
531
    for instance in self._config_data.instances.values():
532
      for nic in instance.nics:
533
        result.append(nic.mac)
534

    
535
    return result
536

    
537
  def _AllDRBDSecrets(self):
538
    """Return all DRBD secrets present in the config.
539

540
    @rtype: list
541
    @return: the list of all DRBD secrets
542

543
    """
544
    def helper(disk, result):
545
      """Recursively gather secrets from this disk."""
546
      if disk.dev_type == constants.DT_DRBD8:
547
        result.append(disk.logical_id[5])
548
      if disk.children:
549
        for child in disk.children:
550
          helper(child, result)
551

    
552
    result = []
553
    for instance in self._config_data.instances.values():
554
      for disk in instance.disks:
555
        helper(disk, result)
556

    
557
    return result
558

    
559
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
560
    """Compute duplicate disk IDs
561

562
    @type disk: L{objects.Disk}
563
    @param disk: the disk at which to start searching
564
    @type l_ids: list
565
    @param l_ids: list of current logical ids
566
    @type p_ids: list
567
    @param p_ids: list of current physical ids
568
    @rtype: list
569
    @return: a list of error messages
570

571
    """
572
    result = []
573
    if disk.logical_id is not None:
574
      if disk.logical_id in l_ids:
575
        result.append("duplicate logical id %s" % str(disk.logical_id))
576
      else:
577
        l_ids.append(disk.logical_id)
578
    if disk.physical_id is not None:
579
      if disk.physical_id in p_ids:
580
        result.append("duplicate physical id %s" % str(disk.physical_id))
581
      else:
582
        p_ids.append(disk.physical_id)
583

    
584
    if disk.children:
585
      for child in disk.children:
586
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
587
    return result
588

    
589
  def _UnlockedVerifyConfig(self):
590
    """Verify function.
591

592
    @rtype: list
593
    @return: a list of error messages; a non-empty list signifies
594
        configuration errors
595

596
    """
597
    # pylint: disable=R0914
598
    result = []
599
    seen_macs = []
600
    ports = {}
601
    data = self._config_data
602
    cluster = data.cluster
603
    seen_lids = []
604
    seen_pids = []
605

    
606
    # global cluster checks
607
    if not cluster.enabled_hypervisors:
608
      result.append("enabled hypervisors list doesn't have any entries")
609
    invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
610
    if invalid_hvs:
611
      result.append("enabled hypervisors contains invalid entries: %s" %
612
                    utils.CommaJoin(invalid_hvs))
613
    missing_hvp = (set(cluster.enabled_hypervisors) -
614
                   set(cluster.hvparams.keys()))
615
    if missing_hvp:
616
      result.append("hypervisor parameters missing for the enabled"
617
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
618

    
619
    if not cluster.enabled_disk_templates:
620
      result.append("enabled disk templates list doesn't have any entries")
621
    invalid_disk_templates = set(cluster.enabled_disk_templates) \
622
                               - constants.DISK_TEMPLATES
623
    if invalid_disk_templates:
624
      result.append("enabled disk templates list contains invalid entries:"
625
                    " %s" % utils.CommaJoin(invalid_disk_templates))
626

    
627
    if cluster.master_node not in data.nodes:
628
      result.append("cluster has invalid primary node '%s'" %
629
                    cluster.master_node)
630

    
631
    def _helper(owner, attr, value, template):
632
      try:
633
        utils.ForceDictType(value, template)
634
      except errors.GenericError, err:
635
        result.append("%s has invalid %s: %s" % (owner, attr, err))
636

    
637
    def _helper_nic(owner, params):
638
      try:
639
        objects.NIC.CheckParameterSyntax(params)
640
      except errors.ConfigurationError, err:
641
        result.append("%s has invalid nicparams: %s" % (owner, err))
642

    
643
    def _helper_ipolicy(owner, ipolicy, iscluster):
644
      try:
645
        objects.InstancePolicy.CheckParameterSyntax(ipolicy, iscluster)
646
      except errors.ConfigurationError, err:
647
        result.append("%s has invalid instance policy: %s" % (owner, err))
648
      for key, value in ipolicy.items():
649
        if key == constants.ISPECS_MINMAX:
650
          for k in range(len(value)):
651
            _helper_ispecs(owner, "ipolicy/%s[%s]" % (key, k), value[k])
652
        elif key == constants.ISPECS_STD:
653
          _helper(owner, "ipolicy/" + key, value,
654
                  constants.ISPECS_PARAMETER_TYPES)
655
        else:
656
          # FIXME: assuming list type
657
          if key in constants.IPOLICY_PARAMETERS:
658
            exp_type = float
659
          else:
660
            exp_type = list
661
          if not isinstance(value, exp_type):
662
            result.append("%s has invalid instance policy: for %s,"
663
                          " expecting %s, got %s" %
664
                          (owner, key, exp_type.__name__, type(value)))
665

    
666
    def _helper_ispecs(owner, parentkey, params):
667
      for (key, value) in params.items():
668
        fullkey = "/".join([parentkey, key])
669
        _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
670

    
671
    # check cluster parameters
672
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
673
            constants.BES_PARAMETER_TYPES)
674
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
675
            constants.NICS_PARAMETER_TYPES)
676
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
677
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
678
            constants.NDS_PARAMETER_TYPES)
679
    _helper_ipolicy("cluster", cluster.ipolicy, True)
680

    
681
    # per-instance checks
682
    for instance_name in data.instances:
683
      instance = data.instances[instance_name]
684
      if instance.name != instance_name:
685
        result.append("instance '%s' is indexed by wrong name '%s'" %
686
                      (instance.name, instance_name))
687
      if instance.primary_node not in data.nodes:
688
        result.append("instance '%s' has invalid primary node '%s'" %
689
                      (instance_name, instance.primary_node))
690
      for snode in instance.secondary_nodes:
691
        if snode not in data.nodes:
692
          result.append("instance '%s' has invalid secondary node '%s'" %
693
                        (instance_name, snode))
694
      for idx, nic in enumerate(instance.nics):
695
        if nic.mac in seen_macs:
696
          result.append("instance '%s' has NIC %d mac %s duplicate" %
697
                        (instance_name, idx, nic.mac))
698
        else:
699
          seen_macs.append(nic.mac)
700
        if nic.nicparams:
701
          filled = cluster.SimpleFillNIC(nic.nicparams)
702
          owner = "instance %s nic %d" % (instance.name, idx)
703
          _helper(owner, "nicparams",
704
                  filled, constants.NICS_PARAMETER_TYPES)
705
          _helper_nic(owner, filled)
706

    
707
      # disk template checks
708
      if not instance.disk_template in data.cluster.enabled_disk_templates:
709
        result.append("instance '%s' uses the disabled disk template '%s'." %
710
                      (instance_name, instance.disk_template))
711

    
712
      # parameter checks
713
      if instance.beparams:
714
        _helper("instance %s" % instance.name, "beparams",
715
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
716

    
717
      # gather the drbd ports for duplicate checks
718
      for (idx, dsk) in enumerate(instance.disks):
719
        if dsk.dev_type in constants.LDS_DRBD:
720
          tcp_port = dsk.logical_id[2]
721
          if tcp_port not in ports:
722
            ports[tcp_port] = []
723
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
724
      # gather network port reservation
725
      net_port = getattr(instance, "network_port", None)
726
      if net_port is not None:
727
        if net_port not in ports:
728
          ports[net_port] = []
729
        ports[net_port].append((instance.name, "network port"))
730

    
731
      # instance disk verify
732
      for idx, disk in enumerate(instance.disks):
733
        result.extend(["instance '%s' disk %d error: %s" %
734
                       (instance.name, idx, msg) for msg in disk.Verify()])
735
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
736

    
737
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
738
      if wrong_names:
739
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
740
                         (idx, exp_name, actual_name))
741
                        for (idx, exp_name, actual_name) in wrong_names)
742

    
743
        result.append("Instance '%s' has wrongly named disks: %s" %
744
                      (instance.name, tmp))
745

    
746
    # cluster-wide pool of free ports
747
    for free_port in cluster.tcpudp_port_pool:
748
      if free_port not in ports:
749
        ports[free_port] = []
750
      ports[free_port].append(("cluster", "port marked as free"))
751

    
752
    # compute tcp/udp duplicate ports
753
    keys = ports.keys()
754
    keys.sort()
755
    for pnum in keys:
756
      pdata = ports[pnum]
757
      if len(pdata) > 1:
758
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
759
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
760

    
761
    # highest used tcp port check
762
    if keys:
763
      if keys[-1] > cluster.highest_used_port:
764
        result.append("Highest used port mismatch, saved %s, computed %s" %
765
                      (cluster.highest_used_port, keys[-1]))
766

    
767
    if not data.nodes[cluster.master_node].master_candidate:
768
      result.append("Master node is not a master candidate")
769

    
770
    # master candidate checks
771
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
772
    if mc_now < mc_max:
773
      result.append("Not enough master candidates: actual %d, target %d" %
774
                    (mc_now, mc_max))
775

    
776
    # node checks
777
    for node_name, node in data.nodes.items():
778
      if node.name != node_name:
779
        result.append("Node '%s' is indexed by wrong name '%s'" %
780
                      (node.name, node_name))
781
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
782
        result.append("Node %s state is invalid: master_candidate=%s,"
783
                      " drain=%s, offline=%s" %
784
                      (node.name, node.master_candidate, node.drained,
785
                       node.offline))
786
      if node.group not in data.nodegroups:
787
        result.append("Node '%s' has invalid group '%s'" %
788
                      (node.name, node.group))
789
      else:
790
        _helper("node %s" % node.name, "ndparams",
791
                cluster.FillND(node, data.nodegroups[node.group]),
792
                constants.NDS_PARAMETER_TYPES)
793
      used_globals = constants.NDC_GLOBALS.intersection(node.ndparams)
794
      if used_globals:
795
        result.append("Node '%s' has some global parameters set: %s" %
796
                      (node.name, utils.CommaJoin(used_globals)))
797

    
798
    # nodegroups checks
799
    nodegroups_names = set()
800
    for nodegroup_uuid in data.nodegroups:
801
      nodegroup = data.nodegroups[nodegroup_uuid]
802
      if nodegroup.uuid != nodegroup_uuid:
803
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
804
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
805
      if utils.UUID_RE.match(nodegroup.name.lower()):
806
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
807
                      (nodegroup.name, nodegroup.uuid))
808
      if nodegroup.name in nodegroups_names:
809
        result.append("duplicate node group name '%s'" % nodegroup.name)
810
      else:
811
        nodegroups_names.add(nodegroup.name)
812
      group_name = "group %s" % nodegroup.name
813
      _helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy),
814
                      False)
815
      if nodegroup.ndparams:
816
        _helper(group_name, "ndparams",
817
                cluster.SimpleFillND(nodegroup.ndparams),
818
                constants.NDS_PARAMETER_TYPES)
819

    
820
    # drbd minors check
821
    _, duplicates = self._UnlockedComputeDRBDMap()
822
    for node, minor, instance_a, instance_b in duplicates:
823
      result.append("DRBD minor %d on node %s is assigned twice to instances"
824
                    " %s and %s" % (minor, node, instance_a, instance_b))
825

    
826
    # IP checks
827
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
828
    ips = {}
829

    
830
    def _AddIpAddress(ip, name):
831
      ips.setdefault(ip, []).append(name)
832

    
833
    _AddIpAddress(cluster.master_ip, "cluster_ip")
834

    
835
    for node in data.nodes.values():
836
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
837
      if node.secondary_ip != node.primary_ip:
838
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
839

    
840
    for instance in data.instances.values():
841
      for idx, nic in enumerate(instance.nics):
842
        if nic.ip is None:
843
          continue
844

    
845
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
846
        nic_mode = nicparams[constants.NIC_MODE]
847
        nic_link = nicparams[constants.NIC_LINK]
848

    
849
        if nic_mode == constants.NIC_MODE_BRIDGED:
850
          link = "bridge:%s" % nic_link
851
        elif nic_mode == constants.NIC_MODE_ROUTED:
852
          link = "route:%s" % nic_link
853
        else:
854
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
855

    
856
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
857
                      "instance:%s/nic:%d" % (instance.name, idx))
858

    
859
    for ip, owners in ips.items():
860
      if len(owners) > 1:
861
        result.append("IP address %s is used by multiple owners: %s" %
862
                      (ip, utils.CommaJoin(owners)))
863

    
864
    return result
865

    
866
  @locking.ssynchronized(_config_lock, shared=1)
867
  def VerifyConfig(self):
868
    """Verify function.
869

870
    This is just a wrapper over L{_UnlockedVerifyConfig}.
871

872
    @rtype: list
873
    @return: a list of error messages; a non-empty list signifies
874
        configuration errors
875

876
    """
877
    return self._UnlockedVerifyConfig()
878

    
879
  def _UnlockedSetDiskID(self, disk, node_name):
880
    """Convert the unique ID to the ID needed on the target nodes.
881

882
    This is used only for drbd, which needs ip/port configuration.
883

884
    The routine descends down and updates its children also, because
885
    this helps when the only the top device is passed to the remote
886
    node.
887

888
    This function is for internal use, when the config lock is already held.
889

890
    """
891
    if disk.children:
892
      for child in disk.children:
893
        self._UnlockedSetDiskID(child, node_name)
894

    
895
    if disk.logical_id is None and disk.physical_id is not None:
896
      return
897
    if disk.dev_type == constants.LD_DRBD8:
898
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
899
      if node_name not in (pnode, snode):
900
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
901
                                        node_name)
902
      pnode_info = self._UnlockedGetNodeInfo(pnode)
903
      snode_info = self._UnlockedGetNodeInfo(snode)
904
      if pnode_info is None or snode_info is None:
905
        raise errors.ConfigurationError("Can't find primary or secondary node"
906
                                        " for %s" % str(disk))
907
      p_data = (pnode_info.secondary_ip, port)
908
      s_data = (snode_info.secondary_ip, port)
909
      if pnode == node_name:
910
        disk.physical_id = p_data + s_data + (pminor, secret)
911
      else: # it must be secondary, we tested above
912
        disk.physical_id = s_data + p_data + (sminor, secret)
913
    else:
914
      disk.physical_id = disk.logical_id
915
    return
916

    
917
  @locking.ssynchronized(_config_lock)
918
  def SetDiskID(self, disk, node_name):
919
    """Convert the unique ID to the ID needed on the target nodes.
920

921
    This is used only for drbd, which needs ip/port configuration.
922

923
    The routine descends down and updates its children also, because
924
    this helps when the only the top device is passed to the remote
925
    node.
926

927
    """
928
    return self._UnlockedSetDiskID(disk, node_name)
929

    
930
  @locking.ssynchronized(_config_lock)
931
  def AddTcpUdpPort(self, port):
932
    """Adds a new port to the available port pool.
933

934
    @warning: this method does not "flush" the configuration (via
935
        L{_WriteConfig}); callers should do that themselves once the
936
        configuration is stable
937

938
    """
939
    if not isinstance(port, int):
940
      raise errors.ProgrammerError("Invalid type passed for port")
941

    
942
    self._config_data.cluster.tcpudp_port_pool.add(port)
943

    
944
  @locking.ssynchronized(_config_lock, shared=1)
945
  def GetPortList(self):
946
    """Returns a copy of the current port list.
947

948
    """
949
    return self._config_data.cluster.tcpudp_port_pool.copy()
950

    
951
  @locking.ssynchronized(_config_lock)
952
  def AllocatePort(self):
953
    """Allocate a port.
954

955
    The port will be taken from the available port pool or from the
956
    default port range (and in this case we increase
957
    highest_used_port).
958

959
    """
960
    # If there are TCP/IP ports configured, we use them first.
961
    if self._config_data.cluster.tcpudp_port_pool:
962
      port = self._config_data.cluster.tcpudp_port_pool.pop()
963
    else:
964
      port = self._config_data.cluster.highest_used_port + 1
965
      if port >= constants.LAST_DRBD_PORT:
966
        raise errors.ConfigurationError("The highest used port is greater"
967
                                        " than %s. Aborting." %
968
                                        constants.LAST_DRBD_PORT)
969
      self._config_data.cluster.highest_used_port = port
970

    
971
    self._WriteConfig()
972
    return port
973

    
974
  def _UnlockedComputeDRBDMap(self):
975
    """Compute the used DRBD minor/nodes.
976

977
    @rtype: (dict, list)
978
    @return: dictionary of node_name: dict of minor: instance_name;
979
        the returned dict will have all the nodes in it (even if with
980
        an empty list), and a list of duplicates; if the duplicates
981
        list is not empty, the configuration is corrupted and its caller
982
        should raise an exception
983

984
    """
985
    def _AppendUsedPorts(instance_name, disk, used):
986
      duplicates = []
987
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
988
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
989
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
990
          assert node in used, ("Node '%s' of instance '%s' not found"
991
                                " in node list" % (node, instance_name))
992
          if port in used[node]:
993
            duplicates.append((node, port, instance_name, used[node][port]))
994
          else:
995
            used[node][port] = instance_name
996
      if disk.children:
997
        for child in disk.children:
998
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
999
      return duplicates
1000

    
1001
    duplicates = []
1002
    my_dict = dict((node, {}) for node in self._config_data.nodes)
1003
    for instance in self._config_data.instances.itervalues():
1004
      for disk in instance.disks:
1005
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
1006
    for (node, minor), instance in self._temporary_drbds.iteritems():
1007
      if minor in my_dict[node] and my_dict[node][minor] != instance:
1008
        duplicates.append((node, minor, instance, my_dict[node][minor]))
1009
      else:
1010
        my_dict[node][minor] = instance
1011
    return my_dict, duplicates
1012

    
1013
  @locking.ssynchronized(_config_lock)
1014
  def ComputeDRBDMap(self):
1015
    """Compute the used DRBD minor/nodes.
1016

1017
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
1018

1019
    @return: dictionary of node_name: dict of minor: instance_name;
1020
        the returned dict will have all the nodes in it (even if with
1021
        an empty list).
1022

1023
    """
1024
    d_map, duplicates = self._UnlockedComputeDRBDMap()
1025
    if duplicates:
1026
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
1027
                                      str(duplicates))
1028
    return d_map
1029

    
1030
  @locking.ssynchronized(_config_lock)
1031
  def AllocateDRBDMinor(self, nodes, instance):
1032
    """Allocate a drbd minor.
1033

1034
    The free minor will be automatically computed from the existing
1035
    devices. A node can be given multiple times in order to allocate
1036
    multiple minors. The result is the list of minors, in the same
1037
    order as the passed nodes.
1038

1039
    @type instance: string
1040
    @param instance: the instance for which we allocate minors
1041

1042
    """
1043
    assert isinstance(instance, basestring), \
1044
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
1045

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

    
1086
  def _UnlockedReleaseDRBDMinors(self, instance):
1087
    """Release temporary drbd minors allocated for a given instance.
1088

1089
    @type instance: string
1090
    @param instance: the instance for which temporary minors should be
1091
                     released
1092

1093
    """
1094
    assert isinstance(instance, basestring), \
1095
           "Invalid argument passed to ReleaseDRBDMinors"
1096
    for key, name in self._temporary_drbds.items():
1097
      if name == instance:
1098
        del self._temporary_drbds[key]
1099

    
1100
  @locking.ssynchronized(_config_lock)
1101
  def ReleaseDRBDMinors(self, instance):
1102
    """Release temporary drbd minors allocated for a given instance.
1103

1104
    This should be called on the error paths, on the success paths
1105
    it's automatically called by the ConfigWriter add and update
1106
    functions.
1107

1108
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1109

1110
    @type instance: string
1111
    @param instance: the instance for which temporary minors should be
1112
                     released
1113

1114
    """
1115
    self._UnlockedReleaseDRBDMinors(instance)
1116

    
1117
  @locking.ssynchronized(_config_lock, shared=1)
1118
  def GetConfigVersion(self):
1119
    """Get the configuration version.
1120

1121
    @return: Config version
1122

1123
    """
1124
    return self._config_data.version
1125

    
1126
  @locking.ssynchronized(_config_lock, shared=1)
1127
  def GetClusterName(self):
1128
    """Get cluster name.
1129

1130
    @return: Cluster name
1131

1132
    """
1133
    return self._config_data.cluster.cluster_name
1134

    
1135
  @locking.ssynchronized(_config_lock, shared=1)
1136
  def GetMasterNode(self):
1137
    """Get the hostname of the master node for this cluster.
1138

1139
    @return: Master hostname
1140

1141
    """
1142
    return self._config_data.cluster.master_node
1143

    
1144
  @locking.ssynchronized(_config_lock, shared=1)
1145
  def GetMasterIP(self):
1146
    """Get the IP of the master node for this cluster.
1147

1148
    @return: Master IP
1149

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

    
1153
  @locking.ssynchronized(_config_lock, shared=1)
1154
  def GetMasterNetdev(self):
1155
    """Get the master network device for this cluster.
1156

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

    
1160
  @locking.ssynchronized(_config_lock, shared=1)
1161
  def GetMasterNetmask(self):
1162
    """Get the netmask of the master node for this cluster.
1163

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

    
1167
  @locking.ssynchronized(_config_lock, shared=1)
1168
  def GetUseExternalMipScript(self):
1169
    """Get flag representing whether to use the external master IP setup script.
1170

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

    
1174
  @locking.ssynchronized(_config_lock, shared=1)
1175
  def GetFileStorageDir(self):
1176
    """Get the file storage dir for this cluster.
1177

1178
    """
1179
    return self._config_data.cluster.file_storage_dir
1180

    
1181
  @locking.ssynchronized(_config_lock, shared=1)
1182
  def GetSharedFileStorageDir(self):
1183
    """Get the shared file storage dir for this cluster.
1184

1185
    """
1186
    return self._config_data.cluster.shared_file_storage_dir
1187

    
1188
  @locking.ssynchronized(_config_lock, shared=1)
1189
  def GetHypervisorType(self):
1190
    """Get the hypervisor type for this cluster.
1191

1192
    """
1193
    return self._config_data.cluster.enabled_hypervisors[0]
1194

    
1195
  @locking.ssynchronized(_config_lock, shared=1)
1196
  def GetRsaHostKey(self):
1197
    """Return the rsa hostkey from the config.
1198

1199
    @rtype: string
1200
    @return: the rsa hostkey
1201

1202
    """
1203
    return self._config_data.cluster.rsahostkeypub
1204

    
1205
  @locking.ssynchronized(_config_lock, shared=1)
1206
  def GetDsaHostKey(self):
1207
    """Return the dsa hostkey from the config.
1208

1209
    @rtype: string
1210
    @return: the dsa hostkey
1211

1212
    """
1213
    return self._config_data.cluster.dsahostkeypub
1214

    
1215
  @locking.ssynchronized(_config_lock, shared=1)
1216
  def GetDefaultIAllocator(self):
1217
    """Get the default instance allocator for this cluster.
1218

1219
    """
1220
    return self._config_data.cluster.default_iallocator
1221

    
1222
  @locking.ssynchronized(_config_lock, shared=1)
1223
  def GetPrimaryIPFamily(self):
1224
    """Get cluster primary ip family.
1225

1226
    @return: primary ip family
1227

1228
    """
1229
    return self._config_data.cluster.primary_ip_family
1230

    
1231
  @locking.ssynchronized(_config_lock, shared=1)
1232
  def GetMasterNetworkParameters(self):
1233
    """Get network parameters of the master node.
1234

1235
    @rtype: L{object.MasterNetworkParameters}
1236
    @return: network parameters of the master node
1237

1238
    """
1239
    cluster = self._config_data.cluster
1240
    result = objects.MasterNetworkParameters(
1241
      name=cluster.master_node, ip=cluster.master_ip,
1242
      netmask=cluster.master_netmask, netdev=cluster.master_netdev,
1243
      ip_family=cluster.primary_ip_family)
1244

    
1245
    return result
1246

    
1247
  @locking.ssynchronized(_config_lock)
1248
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1249
    """Add a node group to the configuration.
1250

1251
    This method calls group.UpgradeConfig() to fill any missing attributes
1252
    according to their default values.
1253

1254
    @type group: L{objects.NodeGroup}
1255
    @param group: the NodeGroup object to add
1256
    @type ec_id: string
1257
    @param ec_id: unique id for the job to use when creating a missing UUID
1258
    @type check_uuid: bool
1259
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1260
                       it does, ensure that it does not exist in the
1261
                       configuration already
1262

1263
    """
1264
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1265
    self._WriteConfig()
1266

    
1267
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1268
    """Add a node group to the configuration.
1269

1270
    """
1271
    logging.info("Adding node group %s to configuration", group.name)
1272

    
1273
    # Some code might need to add a node group with a pre-populated UUID
1274
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1275
    # the "does this UUID" exist already check.
1276
    if check_uuid:
1277
      self._EnsureUUID(group, ec_id)
1278

    
1279
    try:
1280
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1281
    except errors.OpPrereqError:
1282
      pass
1283
    else:
1284
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1285
                                 " node group (UUID: %s)" %
1286
                                 (group.name, existing_uuid),
1287
                                 errors.ECODE_EXISTS)
1288

    
1289
    group.serial_no = 1
1290
    group.ctime = group.mtime = time.time()
1291
    group.UpgradeConfig()
1292

    
1293
    self._config_data.nodegroups[group.uuid] = group
1294
    self._config_data.cluster.serial_no += 1
1295

    
1296
  @locking.ssynchronized(_config_lock)
1297
  def RemoveNodeGroup(self, group_uuid):
1298
    """Remove a node group from the configuration.
1299

1300
    @type group_uuid: string
1301
    @param group_uuid: the UUID of the node group to remove
1302

1303
    """
1304
    logging.info("Removing node group %s from configuration", group_uuid)
1305

    
1306
    if group_uuid not in self._config_data.nodegroups:
1307
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1308

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

    
1312
    del self._config_data.nodegroups[group_uuid]
1313
    self._config_data.cluster.serial_no += 1
1314
    self._WriteConfig()
1315

    
1316
  def _UnlockedLookupNodeGroup(self, target):
1317
    """Lookup a node group's UUID.
1318

1319
    @type target: string or None
1320
    @param target: group name or UUID or None to look for the default
1321
    @rtype: string
1322
    @return: nodegroup UUID
1323
    @raises errors.OpPrereqError: when the target group cannot be found
1324

1325
    """
1326
    if target is None:
1327
      if len(self._config_data.nodegroups) != 1:
1328
        raise errors.OpPrereqError("More than one node group exists. Target"
1329
                                   " group must be specified explicitly.")
1330
      else:
1331
        return self._config_data.nodegroups.keys()[0]
1332
    if target in self._config_data.nodegroups:
1333
      return target
1334
    for nodegroup in self._config_data.nodegroups.values():
1335
      if nodegroup.name == target:
1336
        return nodegroup.uuid
1337
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1338
                               errors.ECODE_NOENT)
1339

    
1340
  @locking.ssynchronized(_config_lock, shared=1)
1341
  def LookupNodeGroup(self, target):
1342
    """Lookup a node group's UUID.
1343

1344
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1345

1346
    @type target: string or None
1347
    @param target: group name or UUID or None to look for the default
1348
    @rtype: string
1349
    @return: nodegroup UUID
1350

1351
    """
1352
    return self._UnlockedLookupNodeGroup(target)
1353

    
1354
  def _UnlockedGetNodeGroup(self, uuid):
1355
    """Lookup a node group.
1356

1357
    @type uuid: string
1358
    @param uuid: group UUID
1359
    @rtype: L{objects.NodeGroup} or None
1360
    @return: nodegroup object, or None if not found
1361

1362
    """
1363
    if uuid not in self._config_data.nodegroups:
1364
      return None
1365

    
1366
    return self._config_data.nodegroups[uuid]
1367

    
1368
  @locking.ssynchronized(_config_lock, shared=1)
1369
  def GetNodeGroup(self, uuid):
1370
    """Lookup a node group.
1371

1372
    @type uuid: string
1373
    @param uuid: group UUID
1374
    @rtype: L{objects.NodeGroup} or None
1375
    @return: nodegroup object, or None if not found
1376

1377
    """
1378
    return self._UnlockedGetNodeGroup(uuid)
1379

    
1380
  @locking.ssynchronized(_config_lock, shared=1)
1381
  def GetAllNodeGroupsInfo(self):
1382
    """Get the configuration of all node groups.
1383

1384
    """
1385
    return dict(self._config_data.nodegroups)
1386

    
1387
  @locking.ssynchronized(_config_lock, shared=1)
1388
  def GetNodeGroupList(self):
1389
    """Get a list of node groups.
1390

1391
    """
1392
    return self._config_data.nodegroups.keys()
1393

    
1394
  @locking.ssynchronized(_config_lock, shared=1)
1395
  def GetNodeGroupMembersByNodes(self, nodes):
1396
    """Get nodes which are member in the same nodegroups as the given nodes.
1397

1398
    """
1399
    ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1400
    return frozenset(member_name
1401
                     for node_name in nodes
1402
                     for member_name in
1403
                       self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1404

    
1405
  @locking.ssynchronized(_config_lock, shared=1)
1406
  def GetMultiNodeGroupInfo(self, group_uuids):
1407
    """Get the configuration of multiple node groups.
1408

1409
    @param group_uuids: List of node group UUIDs
1410
    @rtype: list
1411
    @return: List of tuples of (group_uuid, group_info)
1412

1413
    """
1414
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1415

    
1416
  @locking.ssynchronized(_config_lock)
1417
  def AddInstance(self, instance, ec_id):
1418
    """Add an instance to the config.
1419

1420
    This should be used after creating a new instance.
1421

1422
    @type instance: L{objects.Instance}
1423
    @param instance: the instance object
1424

1425
    """
1426
    if not isinstance(instance, objects.Instance):
1427
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1428

    
1429
    if instance.disk_template != constants.DT_DISKLESS:
1430
      all_lvs = instance.MapLVsByNode()
1431
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1432

    
1433
    all_macs = self._AllMACs()
1434
    for nic in instance.nics:
1435
      if nic.mac in all_macs:
1436
        raise errors.ConfigurationError("Cannot add instance %s:"
1437
                                        " MAC address '%s' already in use." %
1438
                                        (instance.name, nic.mac))
1439

    
1440
    self._EnsureUUID(instance, ec_id)
1441

    
1442
    instance.serial_no = 1
1443
    instance.ctime = instance.mtime = time.time()
1444
    self._config_data.instances[instance.name] = instance
1445
    self._config_data.cluster.serial_no += 1
1446
    self._UnlockedReleaseDRBDMinors(instance.name)
1447
    self._UnlockedCommitTemporaryIps(ec_id)
1448
    self._WriteConfig()
1449

    
1450
  def _EnsureUUID(self, item, ec_id):
1451
    """Ensures a given object has a valid UUID.
1452

1453
    @param item: the instance or node to be checked
1454
    @param ec_id: the execution context id for the uuid reservation
1455

1456
    """
1457
    if not item.uuid:
1458
      item.uuid = self._GenerateUniqueID(ec_id)
1459
    elif item.uuid in self._AllIDs(include_temporary=True):
1460
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1461
                                      " in use" % (item.name, item.uuid))
1462

    
1463
  def _SetInstanceStatus(self, instance_name, status, disks_active):
1464
    """Set the instance's status to a given value.
1465

1466
    """
1467
    if instance_name not in self._config_data.instances:
1468
      raise errors.ConfigurationError("Unknown instance '%s'" %
1469
                                      instance_name)
1470
    instance = self._config_data.instances[instance_name]
1471

    
1472
    if status is None:
1473
      status = instance.admin_state
1474
    if disks_active is None:
1475
      disks_active = instance.disks_active
1476

    
1477
    assert status in constants.ADMINST_ALL, \
1478
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1479

    
1480
    if instance.admin_state != status or \
1481
       instance.disks_active != disks_active:
1482
      instance.admin_state = status
1483
      instance.disks_active = disks_active
1484
      instance.serial_no += 1
1485
      instance.mtime = time.time()
1486
      self._WriteConfig()
1487

    
1488
  @locking.ssynchronized(_config_lock)
1489
  def MarkInstanceUp(self, instance_name):
1490
    """Mark the instance status to up in the config.
1491

1492
    This also sets the instance disks active flag.
1493

1494
    """
1495
    self._SetInstanceStatus(instance_name, constants.ADMINST_UP, True)
1496

    
1497
  @locking.ssynchronized(_config_lock)
1498
  def MarkInstanceOffline(self, instance_name):
1499
    """Mark the instance status to down in the config.
1500

1501
    This also clears the instance disks active flag.
1502

1503
    """
1504
    self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE, False)
1505

    
1506
  @locking.ssynchronized(_config_lock)
1507
  def RemoveInstance(self, instance_name):
1508
    """Remove the instance from the configuration.
1509

1510
    """
1511
    if instance_name not in self._config_data.instances:
1512
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1513

    
1514
    # If a network port has been allocated to the instance,
1515
    # return it to the pool of free ports.
1516
    inst = self._config_data.instances[instance_name]
1517
    network_port = getattr(inst, "network_port", None)
1518
    if network_port is not None:
1519
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1520

    
1521
    instance = self._UnlockedGetInstanceInfo(instance_name)
1522

    
1523
    for nic in instance.nics:
1524
      if nic.network and nic.ip:
1525
        # Return all IP addresses to the respective address pools
1526
        self._UnlockedCommitIp(constants.RELEASE_ACTION, nic.network, nic.ip)
1527

    
1528
    del self._config_data.instances[instance_name]
1529
    self._config_data.cluster.serial_no += 1
1530
    self._WriteConfig()
1531

    
1532
  @locking.ssynchronized(_config_lock)
1533
  def RenameInstance(self, old_name, new_name):
1534
    """Rename an instance.
1535

1536
    This needs to be done in ConfigWriter and not by RemoveInstance
1537
    combined with AddInstance as only we can guarantee an atomic
1538
    rename.
1539

1540
    """
1541
    if old_name not in self._config_data.instances:
1542
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1543

    
1544
    # Operate on a copy to not loose instance object in case of a failure
1545
    inst = self._config_data.instances[old_name].Copy()
1546
    inst.name = new_name
1547

    
1548
    for (idx, disk) in enumerate(inst.disks):
1549
      if disk.dev_type == constants.LD_FILE:
1550
        # rename the file paths in logical and physical id
1551
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1552
        disk.logical_id = (disk.logical_id[0],
1553
                           utils.PathJoin(file_storage_dir, inst.name,
1554
                                          "disk%s" % idx))
1555
        disk.physical_id = disk.logical_id
1556

    
1557
    # Actually replace instance object
1558
    del self._config_data.instances[old_name]
1559
    self._config_data.instances[inst.name] = inst
1560

    
1561
    # Force update of ssconf files
1562
    self._config_data.cluster.serial_no += 1
1563

    
1564
    self._WriteConfig()
1565

    
1566
  @locking.ssynchronized(_config_lock)
1567
  def MarkInstanceDown(self, instance_name):
1568
    """Mark the status of an instance to down in the configuration.
1569

1570
    This does not touch the instance disks active flag, as shut down instances
1571
    can still have active disks.
1572

1573
    """
1574
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN, None)
1575

    
1576
  @locking.ssynchronized(_config_lock)
1577
  def MarkInstanceDisksActive(self, instance_name):
1578
    """Mark the status of instance disks active.
1579

1580
    """
1581
    self._SetInstanceStatus(instance_name, None, True)
1582

    
1583
  @locking.ssynchronized(_config_lock)
1584
  def MarkInstanceDisksInactive(self, instance_name):
1585
    """Mark the status of instance disks inactive.
1586

1587
    """
1588
    self._SetInstanceStatus(instance_name, None, False)
1589

    
1590
  def _UnlockedGetInstanceList(self):
1591
    """Get the list of instances.
1592

1593
    This function is for internal use, when the config lock is already held.
1594

1595
    """
1596
    return self._config_data.instances.keys()
1597

    
1598
  @locking.ssynchronized(_config_lock, shared=1)
1599
  def GetInstanceList(self):
1600
    """Get the list of instances.
1601

1602
    @return: array of instances, ex. ['instance2.example.com',
1603
        'instance1.example.com']
1604

1605
    """
1606
    return self._UnlockedGetInstanceList()
1607

    
1608
  def ExpandInstanceName(self, short_name):
1609
    """Attempt to expand an incomplete instance name.
1610

1611
    """
1612
    # Locking is done in L{ConfigWriter.GetInstanceList}
1613
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1614

    
1615
  def _UnlockedGetInstanceInfo(self, instance_name):
1616
    """Returns information about an instance.
1617

1618
    This function is for internal use, when the config lock is already held.
1619

1620
    """
1621
    if instance_name not in self._config_data.instances:
1622
      return None
1623

    
1624
    return self._config_data.instances[instance_name]
1625

    
1626
  @locking.ssynchronized(_config_lock, shared=1)
1627
  def GetInstanceInfo(self, instance_name):
1628
    """Returns information about an instance.
1629

1630
    It takes the information from the configuration file. Other information of
1631
    an instance are taken from the live systems.
1632

1633
    @param instance_name: name of the instance, e.g.
1634
        I{instance1.example.com}
1635

1636
    @rtype: L{objects.Instance}
1637
    @return: the instance object
1638

1639
    """
1640
    return self._UnlockedGetInstanceInfo(instance_name)
1641

    
1642
  @locking.ssynchronized(_config_lock, shared=1)
1643
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1644
    """Returns set of node group UUIDs for instance's nodes.
1645

1646
    @rtype: frozenset
1647

1648
    """
1649
    instance = self._UnlockedGetInstanceInfo(instance_name)
1650
    if not instance:
1651
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1652

    
1653
    if primary_only:
1654
      nodes = [instance.primary_node]
1655
    else:
1656
      nodes = instance.all_nodes
1657

    
1658
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1659
                     for node_name in nodes)
1660

    
1661
  @locking.ssynchronized(_config_lock, shared=1)
1662
  def GetInstanceNetworks(self, instance_name):
1663
    """Returns set of network UUIDs for instance's nics.
1664

1665
    @rtype: frozenset
1666

1667
    """
1668
    instance = self._UnlockedGetInstanceInfo(instance_name)
1669
    if not instance:
1670
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1671

    
1672
    networks = set()
1673
    for nic in instance.nics:
1674
      if nic.network:
1675
        networks.add(nic.network)
1676

    
1677
    return frozenset(networks)
1678

    
1679
  @locking.ssynchronized(_config_lock, shared=1)
1680
  def GetMultiInstanceInfo(self, instances):
1681
    """Get the configuration of multiple instances.
1682

1683
    @param instances: list of instance names
1684
    @rtype: list
1685
    @return: list of tuples (instance, instance_info), where
1686
        instance_info is what would GetInstanceInfo return for the
1687
        node, while keeping the original order
1688

1689
    """
1690
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1691

    
1692
  @locking.ssynchronized(_config_lock, shared=1)
1693
  def GetAllInstancesInfo(self):
1694
    """Get the configuration of all instances.
1695

1696
    @rtype: dict
1697
    @return: dict of (instance, instance_info), where instance_info is what
1698
              would GetInstanceInfo return for the node
1699

1700
    """
1701
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1702
                    for instance in self._UnlockedGetInstanceList()])
1703
    return my_dict
1704

    
1705
  @locking.ssynchronized(_config_lock, shared=1)
1706
  def GetInstancesInfoByFilter(self, filter_fn):
1707
    """Get instance configuration with a filter.
1708

1709
    @type filter_fn: callable
1710
    @param filter_fn: Filter function receiving instance object as parameter,
1711
      returning boolean. Important: this function is called while the
1712
      configuration locks is held. It must not do any complex work or call
1713
      functions potentially leading to a deadlock. Ideally it doesn't call any
1714
      other functions and just compares instance attributes.
1715

1716
    """
1717
    return dict((name, inst)
1718
                for (name, inst) in self._config_data.instances.items()
1719
                if filter_fn(inst))
1720

    
1721
  @locking.ssynchronized(_config_lock)
1722
  def AddNode(self, node, ec_id):
1723
    """Add a node to the configuration.
1724

1725
    @type node: L{objects.Node}
1726
    @param node: a Node instance
1727

1728
    """
1729
    logging.info("Adding node %s to configuration", node.name)
1730

    
1731
    self._EnsureUUID(node, ec_id)
1732

    
1733
    node.serial_no = 1
1734
    node.ctime = node.mtime = time.time()
1735
    self._UnlockedAddNodeToGroup(node.name, node.group)
1736
    self._config_data.nodes[node.name] = node
1737
    self._config_data.cluster.serial_no += 1
1738
    self._WriteConfig()
1739

    
1740
  @locking.ssynchronized(_config_lock)
1741
  def RemoveNode(self, node_name):
1742
    """Remove a node from the configuration.
1743

1744
    """
1745
    logging.info("Removing node %s from configuration", node_name)
1746

    
1747
    if node_name not in self._config_data.nodes:
1748
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1749

    
1750
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1751
    del self._config_data.nodes[node_name]
1752
    self._config_data.cluster.serial_no += 1
1753
    self._WriteConfig()
1754

    
1755
  def ExpandNodeName(self, short_name):
1756
    """Attempt to expand an incomplete node name.
1757

1758
    """
1759
    # Locking is done in L{ConfigWriter.GetNodeList}
1760
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1761

    
1762
  def _UnlockedGetNodeInfo(self, node_name):
1763
    """Get the configuration of a node, as stored in the config.
1764

1765
    This function is for internal use, when the config lock is already
1766
    held.
1767

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

1770
    @rtype: L{objects.Node}
1771
    @return: the node object
1772

1773
    """
1774
    if node_name not in self._config_data.nodes:
1775
      return None
1776

    
1777
    return self._config_data.nodes[node_name]
1778

    
1779
  @locking.ssynchronized(_config_lock, shared=1)
1780
  def GetNodeInfo(self, node_name):
1781
    """Get the configuration of a node, as stored in the config.
1782

1783
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1784

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

1787
    @rtype: L{objects.Node}
1788
    @return: the node object
1789

1790
    """
1791
    return self._UnlockedGetNodeInfo(node_name)
1792

    
1793
  @locking.ssynchronized(_config_lock, shared=1)
1794
  def GetNodeInstances(self, node_name):
1795
    """Get the instances of a node, as stored in the config.
1796

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

1799
    @rtype: (list, list)
1800
    @return: a tuple with two lists: the primary and the secondary instances
1801

1802
    """
1803
    pri = []
1804
    sec = []
1805
    for inst in self._config_data.instances.values():
1806
      if inst.primary_node == node_name:
1807
        pri.append(inst.name)
1808
      if node_name in inst.secondary_nodes:
1809
        sec.append(inst.name)
1810
    return (pri, sec)
1811

    
1812
  @locking.ssynchronized(_config_lock, shared=1)
1813
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1814
    """Get the instances of a node group.
1815

1816
    @param uuid: Node group UUID
1817
    @param primary_only: Whether to only consider primary nodes
1818
    @rtype: frozenset
1819
    @return: List of instance names in node group
1820

1821
    """
1822
    if primary_only:
1823
      nodes_fn = lambda inst: [inst.primary_node]
1824
    else:
1825
      nodes_fn = lambda inst: inst.all_nodes
1826

    
1827
    return frozenset(inst.name
1828
                     for inst in self._config_data.instances.values()
1829
                     for node_name in nodes_fn(inst)
1830
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1831

    
1832
  def _UnlockedGetNodeList(self):
1833
    """Return the list of nodes which are in the configuration.
1834

1835
    This function is for internal use, when the config lock is already
1836
    held.
1837

1838
    @rtype: list
1839

1840
    """
1841
    return self._config_data.nodes.keys()
1842

    
1843
  @locking.ssynchronized(_config_lock, shared=1)
1844
  def GetNodeList(self):
1845
    """Return the list of nodes which are in the configuration.
1846

1847
    """
1848
    return self._UnlockedGetNodeList()
1849

    
1850
  def _UnlockedGetOnlineNodeList(self):
1851
    """Return the list of nodes which are online.
1852

1853
    """
1854
    all_nodes = [self._UnlockedGetNodeInfo(node)
1855
                 for node in self._UnlockedGetNodeList()]
1856
    return [node.name for node in all_nodes if not node.offline]
1857

    
1858
  @locking.ssynchronized(_config_lock, shared=1)
1859
  def GetOnlineNodeList(self):
1860
    """Return the list of nodes which are online.
1861

1862
    """
1863
    return self._UnlockedGetOnlineNodeList()
1864

    
1865
  @locking.ssynchronized(_config_lock, shared=1)
1866
  def GetVmCapableNodeList(self):
1867
    """Return the list of nodes which are not vm capable.
1868

1869
    """
1870
    all_nodes = [self._UnlockedGetNodeInfo(node)
1871
                 for node in self._UnlockedGetNodeList()]
1872
    return [node.name for node in all_nodes if node.vm_capable]
1873

    
1874
  @locking.ssynchronized(_config_lock, shared=1)
1875
  def GetNonVmCapableNodeList(self):
1876
    """Return the list of nodes which are not vm capable.
1877

1878
    """
1879
    all_nodes = [self._UnlockedGetNodeInfo(node)
1880
                 for node in self._UnlockedGetNodeList()]
1881
    return [node.name for node in all_nodes if not node.vm_capable]
1882

    
1883
  @locking.ssynchronized(_config_lock, shared=1)
1884
  def GetMultiNodeInfo(self, nodes):
1885
    """Get the configuration of multiple nodes.
1886

1887
    @param nodes: list of node names
1888
    @rtype: list
1889
    @return: list of tuples of (node, node_info), where node_info is
1890
        what would GetNodeInfo return for the node, in the original
1891
        order
1892

1893
    """
1894
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1895

    
1896
  @locking.ssynchronized(_config_lock, shared=1)
1897
  def GetAllNodesInfo(self):
1898
    """Get the configuration of all nodes.
1899

1900
    @rtype: dict
1901
    @return: dict of (node, node_info), where node_info is what
1902
              would GetNodeInfo return for the node
1903

1904
    """
1905
    return self._UnlockedGetAllNodesInfo()
1906

    
1907
  def _UnlockedGetAllNodesInfo(self):
1908
    """Gets configuration of all nodes.
1909

1910
    @note: See L{GetAllNodesInfo}
1911

1912
    """
1913
    return dict([(node, self._UnlockedGetNodeInfo(node))
1914
                 for node in self._UnlockedGetNodeList()])
1915

    
1916
  @locking.ssynchronized(_config_lock, shared=1)
1917
  def GetNodeGroupsFromNodes(self, nodes):
1918
    """Returns groups for a list of nodes.
1919

1920
    @type nodes: list of string
1921
    @param nodes: List of node names
1922
    @rtype: frozenset
1923

1924
    """
1925
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1926

    
1927
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1928
    """Get the number of current and maximum desired and possible candidates.
1929

1930
    @type exceptions: list
1931
    @param exceptions: if passed, list of nodes that should be ignored
1932
    @rtype: tuple
1933
    @return: tuple of (current, desired and possible, possible)
1934

1935
    """
1936
    mc_now = mc_should = mc_max = 0
1937
    for node in self._config_data.nodes.values():
1938
      if exceptions and node.name in exceptions:
1939
        continue
1940
      if not (node.offline or node.drained) and node.master_capable:
1941
        mc_max += 1
1942
      if node.master_candidate:
1943
        mc_now += 1
1944
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1945
    return (mc_now, mc_should, mc_max)
1946

    
1947
  @locking.ssynchronized(_config_lock, shared=1)
1948
  def GetMasterCandidateStats(self, exceptions=None):
1949
    """Get the number of current and maximum possible candidates.
1950

1951
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1952

1953
    @type exceptions: list
1954
    @param exceptions: if passed, list of nodes that should be ignored
1955
    @rtype: tuple
1956
    @return: tuple of (current, max)
1957

1958
    """
1959
    return self._UnlockedGetMasterCandidateStats(exceptions)
1960

    
1961
  @locking.ssynchronized(_config_lock)
1962
  def MaintainCandidatePool(self, exceptions):
1963
    """Try to grow the candidate pool to the desired size.
1964

1965
    @type exceptions: list
1966
    @param exceptions: if passed, list of nodes that should be ignored
1967
    @rtype: list
1968
    @return: list with the adjusted nodes (L{objects.Node} instances)
1969

1970
    """
1971
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1972
    mod_list = []
1973
    if mc_now < mc_max:
1974
      node_list = self._config_data.nodes.keys()
1975
      random.shuffle(node_list)
1976
      for name in node_list:
1977
        if mc_now >= mc_max:
1978
          break
1979
        node = self._config_data.nodes[name]
1980
        if (node.master_candidate or node.offline or node.drained or
1981
            node.name in exceptions or not node.master_capable):
1982
          continue
1983
        mod_list.append(node)
1984
        node.master_candidate = True
1985
        node.serial_no += 1
1986
        mc_now += 1
1987
      if mc_now != mc_max:
1988
        # this should not happen
1989
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1990
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1991
      if mod_list:
1992
        self._config_data.cluster.serial_no += 1
1993
        self._WriteConfig()
1994

    
1995
    return mod_list
1996

    
1997
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1998
    """Add a given node to the specified group.
1999

2000
    """
2001
    if nodegroup_uuid not in self._config_data.nodegroups:
2002
      # This can happen if a node group gets deleted between its lookup and
2003
      # when we're adding the first node to it, since we don't keep a lock in
2004
      # the meantime. It's ok though, as we'll fail cleanly if the node group
2005
      # is not found anymore.
2006
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
2007
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
2008
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
2009

    
2010
  def _UnlockedRemoveNodeFromGroup(self, node):
2011
    """Remove a given node from its group.
2012

2013
    """
2014
    nodegroup = node.group
2015
    if nodegroup not in self._config_data.nodegroups:
2016
      logging.warning("Warning: node '%s' has unknown node group '%s'"
2017
                      " (while being removed from it)", node.name, nodegroup)
2018
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
2019
    if node.name not in nodegroup_obj.members:
2020
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
2021
                      " (while being removed from it)", node.name, nodegroup)
2022
    else:
2023
      nodegroup_obj.members.remove(node.name)
2024

    
2025
  @locking.ssynchronized(_config_lock)
2026
  def AssignGroupNodes(self, mods):
2027
    """Changes the group of a number of nodes.
2028

2029
    @type mods: list of tuples; (node name, new group UUID)
2030
    @param mods: Node membership modifications
2031

2032
    """
2033
    groups = self._config_data.nodegroups
2034
    nodes = self._config_data.nodes
2035

    
2036
    resmod = []
2037

    
2038
    # Try to resolve names/UUIDs first
2039
    for (node_name, new_group_uuid) in mods:
2040
      try:
2041
        node = nodes[node_name]
2042
      except KeyError:
2043
        raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
2044

    
2045
      if node.group == new_group_uuid:
2046
        # Node is being assigned to its current group
2047
        logging.debug("Node '%s' was assigned to its current group (%s)",
2048
                      node_name, node.group)
2049
        continue
2050

    
2051
      # Try to find current group of node
2052
      try:
2053
        old_group = groups[node.group]
2054
      except KeyError:
2055
        raise errors.ConfigurationError("Unable to find old group '%s'" %
2056
                                        node.group)
2057

    
2058
      # Try to find new group for node
2059
      try:
2060
        new_group = groups[new_group_uuid]
2061
      except KeyError:
2062
        raise errors.ConfigurationError("Unable to find new group '%s'" %
2063
                                        new_group_uuid)
2064

    
2065
      assert node.name in old_group.members, \
2066
        ("Inconsistent configuration: node '%s' not listed in members for its"
2067
         " old group '%s'" % (node.name, old_group.uuid))
2068
      assert node.name not in new_group.members, \
2069
        ("Inconsistent configuration: node '%s' already listed in members for"
2070
         " its new group '%s'" % (node.name, new_group.uuid))
2071

    
2072
      resmod.append((node, old_group, new_group))
2073

    
2074
    # Apply changes
2075
    for (node, old_group, new_group) in resmod:
2076
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
2077
        "Assigning to current group is not possible"
2078

    
2079
      node.group = new_group.uuid
2080

    
2081
      # Update members of involved groups
2082
      if node.name in old_group.members:
2083
        old_group.members.remove(node.name)
2084
      if node.name not in new_group.members:
2085
        new_group.members.append(node.name)
2086

    
2087
    # Update timestamps and serials (only once per node/group object)
2088
    now = time.time()
2089
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
2090
      obj.serial_no += 1
2091
      obj.mtime = now
2092

    
2093
    # Force ssconf update
2094
    self._config_data.cluster.serial_no += 1
2095

    
2096
    self._WriteConfig()
2097

    
2098
  def _BumpSerialNo(self):
2099
    """Bump up the serial number of the config.
2100

2101
    """
2102
    self._config_data.serial_no += 1
2103
    self._config_data.mtime = time.time()
2104

    
2105
  def _AllUUIDObjects(self):
2106
    """Returns all objects with uuid attributes.
2107

2108
    """
2109
    return (self._config_data.instances.values() +
2110
            self._config_data.nodes.values() +
2111
            self._config_data.nodegroups.values() +
2112
            self._config_data.networks.values() +
2113
            self._AllDisks() +
2114
            self._AllNICs() +
2115
            [self._config_data.cluster])
2116

    
2117
  def _OpenConfig(self, accept_foreign):
2118
    """Read the config data from disk.
2119

2120
    """
2121
    raw_data = utils.ReadFile(self._cfg_file)
2122

    
2123
    try:
2124
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
2125
    except Exception, err:
2126
      raise errors.ConfigurationError(err)
2127

    
2128
    # Make sure the configuration has the right version
2129
    _ValidateConfig(data)
2130

    
2131
    if (not hasattr(data, "cluster") or
2132
        not hasattr(data.cluster, "rsahostkeypub")):
2133
      raise errors.ConfigurationError("Incomplete configuration"
2134
                                      " (missing cluster.rsahostkeypub)")
2135

    
2136
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
2137
      msg = ("The configuration denotes node %s as master, while my"
2138
             " hostname is %s; opening a foreign configuration is only"
2139
             " possible in accept_foreign mode" %
2140
             (data.cluster.master_node, self._my_hostname))
2141
      raise errors.ConfigurationError(msg)
2142

    
2143
    self._config_data = data
2144
    # reset the last serial as -1 so that the next write will cause
2145
    # ssconf update
2146
    self._last_cluster_serial = -1
2147

    
2148
    # Upgrade configuration if needed
2149
    self._UpgradeConfig()
2150

    
2151
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2152

    
2153
  def _UpgradeConfig(self):
2154
    """Run any upgrade steps.
2155

2156
    This method performs both in-object upgrades and also update some data
2157
    elements that need uniqueness across the whole configuration or interact
2158
    with other objects.
2159

2160
    @warning: this function will call L{_WriteConfig()}, but also
2161
        L{DropECReservations} so it needs to be called only from a
2162
        "safe" place (the constructor). If one wanted to call it with
2163
        the lock held, a DropECReservationUnlocked would need to be
2164
        created first, to avoid causing deadlock.
2165

2166
    """
2167
    # Keep a copy of the persistent part of _config_data to check for changes
2168
    # Serialization doesn't guarantee order in dictionaries
2169
    oldconf = copy.deepcopy(self._config_data.ToDict())
2170

    
2171
    # In-object upgrades
2172
    self._config_data.UpgradeConfig()
2173

    
2174
    for item in self._AllUUIDObjects():
2175
      if item.uuid is None:
2176
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
2177
    if not self._config_data.nodegroups:
2178
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
2179
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
2180
                                            members=[])
2181
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
2182
    for node in self._config_data.nodes.values():
2183
      if not node.group:
2184
        node.group = self.LookupNodeGroup(None)
2185
      # This is technically *not* an upgrade, but needs to be done both when
2186
      # nodegroups are being added, and upon normally loading the config,
2187
      # because the members list of a node group is discarded upon
2188
      # serializing/deserializing the object.
2189
      self._UnlockedAddNodeToGroup(node.name, node.group)
2190

    
2191
    modified = (oldconf != self._config_data.ToDict())
2192
    if modified:
2193
      self._WriteConfig()
2194
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
2195
      # only called at config init time, without the lock held
2196
      self.DropECReservations(_UPGRADE_CONFIG_JID)
2197
    else:
2198
      config_errors = self._UnlockedVerifyConfig()
2199
      if config_errors:
2200
        errmsg = ("Loaded configuration data is not consistent: %s" %
2201
                  (utils.CommaJoin(config_errors)))
2202
        logging.critical(errmsg)
2203

    
2204
  def _DistributeConfig(self, feedback_fn):
2205
    """Distribute the configuration to the other nodes.
2206

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

2210
    """
2211
    if self._offline:
2212
      return True
2213

    
2214
    bad = False
2215

    
2216
    node_list = []
2217
    addr_list = []
2218
    myhostname = self._my_hostname
2219
    # we can skip checking whether _UnlockedGetNodeInfo returns None
2220
    # since the node list comes from _UnlocketGetNodeList, and we are
2221
    # called with the lock held, so no modifications should take place
2222
    # in between
2223
    for node_name in self._UnlockedGetNodeList():
2224
      if node_name == myhostname:
2225
        continue
2226
      node_info = self._UnlockedGetNodeInfo(node_name)
2227
      if not node_info.master_candidate:
2228
        continue
2229
      node_list.append(node_info.name)
2230
      addr_list.append(node_info.primary_ip)
2231

    
2232
    # TODO: Use dedicated resolver talking to config writer for name resolution
2233
    result = \
2234
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2235
    for to_node, to_result in result.items():
2236
      msg = to_result.fail_msg
2237
      if msg:
2238
        msg = ("Copy of file %s to node %s failed: %s" %
2239
               (self._cfg_file, to_node, msg))
2240
        logging.error(msg)
2241

    
2242
        if feedback_fn:
2243
          feedback_fn(msg)
2244

    
2245
        bad = True
2246

    
2247
    return not bad
2248

    
2249
  def _WriteConfig(self, destination=None, feedback_fn=None):
2250
    """Write the configuration data to persistent storage.
2251

2252
    """
2253
    assert feedback_fn is None or callable(feedback_fn)
2254

    
2255
    # Warn on config errors, but don't abort the save - the
2256
    # configuration has already been modified, and we can't revert;
2257
    # the best we can do is to warn the user and save as is, leaving
2258
    # recovery to the user
2259
    config_errors = self._UnlockedVerifyConfig()
2260
    if config_errors:
2261
      errmsg = ("Configuration data is not consistent: %s" %
2262
                (utils.CommaJoin(config_errors)))
2263
      logging.critical(errmsg)
2264
      if feedback_fn:
2265
        feedback_fn(errmsg)
2266

    
2267
    if destination is None:
2268
      destination = self._cfg_file
2269
    self._BumpSerialNo()
2270
    txt = serializer.Dump(self._config_data.ToDict())
2271

    
2272
    getents = self._getents()
2273
    try:
2274
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2275
                               close=False, gid=getents.confd_gid, mode=0640)
2276
    except errors.LockError:
2277
      raise errors.ConfigurationError("The configuration file has been"
2278
                                      " modified since the last write, cannot"
2279
                                      " update")
2280
    try:
2281
      self._cfg_id = utils.GetFileID(fd=fd)
2282
    finally:
2283
      os.close(fd)
2284

    
2285
    self.write_count += 1
2286

    
2287
    # and redistribute the config file to master candidates
2288
    self._DistributeConfig(feedback_fn)
2289

    
2290
    # Write ssconf files on all nodes (including locally)
2291
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2292
      if not self._offline:
2293
        result = self._GetRpc(None).call_write_ssconf_files(
2294
          self._UnlockedGetOnlineNodeList(),
2295
          self._UnlockedGetSsconfValues())
2296

    
2297
        for nname, nresu in result.items():
2298
          msg = nresu.fail_msg
2299
          if msg:
2300
            errmsg = ("Error while uploading ssconf files to"
2301
                      " node %s: %s" % (nname, msg))
2302
            logging.warning(errmsg)
2303

    
2304
            if feedback_fn:
2305
              feedback_fn(errmsg)
2306

    
2307
      self._last_cluster_serial = self._config_data.cluster.serial_no
2308

    
2309
  def _UnlockedGetSsconfValues(self):
2310
    """Return the values needed by ssconf.
2311

2312
    @rtype: dict
2313
    @return: a dictionary with keys the ssconf names and values their
2314
        associated value
2315

2316
    """
2317
    fn = "\n".join
2318
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
2319
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
2320
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
2321
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2322
                    for ninfo in node_info]
2323
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2324
                    for ninfo in node_info]
2325

    
2326
    instance_data = fn(instance_names)
2327
    off_data = fn(node.name for node in node_info if node.offline)
2328
    on_data = fn(node.name for node in node_info if not node.offline)
2329
    mc_data = fn(node.name for node in node_info if node.master_candidate)
2330
    mc_ips_data = fn(node.primary_ip for node in node_info
2331
                     if node.master_candidate)
2332
    node_data = fn(node_names)
2333
    node_pri_ips_data = fn(node_pri_ips)
2334
    node_snd_ips_data = fn(node_snd_ips)
2335

    
2336
    cluster = self._config_data.cluster
2337
    cluster_tags = fn(cluster.GetTags())
2338

    
2339
    hypervisor_list = fn(cluster.enabled_hypervisors)
2340

    
2341
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2342

    
2343
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2344
                  self._config_data.nodegroups.values()]
2345
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2346
    networks = ["%s %s" % (net.uuid, net.name) for net in
2347
                self._config_data.networks.values()]
2348
    networks_data = fn(utils.NiceSort(networks))
2349

    
2350
    ssconf_values = {
2351
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
2352
      constants.SS_CLUSTER_TAGS: cluster_tags,
2353
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2354
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2355
      constants.SS_MASTER_CANDIDATES: mc_data,
2356
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2357
      constants.SS_MASTER_IP: cluster.master_ip,
2358
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
2359
      constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2360
      constants.SS_MASTER_NODE: cluster.master_node,
2361
      constants.SS_NODE_LIST: node_data,
2362
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2363
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2364
      constants.SS_OFFLINE_NODES: off_data,
2365
      constants.SS_ONLINE_NODES: on_data,
2366
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2367
      constants.SS_INSTANCE_LIST: instance_data,
2368
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2369
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
2370
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2371
      constants.SS_UID_POOL: uid_pool,
2372
      constants.SS_NODEGROUPS: nodegroups_data,
2373
      constants.SS_NETWORKS: networks_data,
2374
      }
2375
    bad_values = [(k, v) for k, v in ssconf_values.items()
2376
                  if not isinstance(v, (str, basestring))]
2377
    if bad_values:
2378
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2379
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2380
                                      " values: %s" % err)
2381
    return ssconf_values
2382

    
2383
  @locking.ssynchronized(_config_lock, shared=1)
2384
  def GetSsconfValues(self):
2385
    """Wrapper using lock around _UnlockedGetSsconf().
2386

2387
    """
2388
    return self._UnlockedGetSsconfValues()
2389

    
2390
  @locking.ssynchronized(_config_lock, shared=1)
2391
  def GetVGName(self):
2392
    """Return the volume group name.
2393

2394
    """
2395
    return self._config_data.cluster.volume_group_name
2396

    
2397
  @locking.ssynchronized(_config_lock)
2398
  def SetVGName(self, vg_name):
2399
    """Set the volume group name.
2400

2401
    """
2402
    self._config_data.cluster.volume_group_name = vg_name
2403
    self._config_data.cluster.serial_no += 1
2404
    self._WriteConfig()
2405

    
2406
  @locking.ssynchronized(_config_lock, shared=1)
2407
  def GetDRBDHelper(self):
2408
    """Return DRBD usermode helper.
2409

2410
    """
2411
    return self._config_data.cluster.drbd_usermode_helper
2412

    
2413
  @locking.ssynchronized(_config_lock)
2414
  def SetDRBDHelper(self, drbd_helper):
2415
    """Set DRBD usermode helper.
2416

2417
    """
2418
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2419
    self._config_data.cluster.serial_no += 1
2420
    self._WriteConfig()
2421

    
2422
  @locking.ssynchronized(_config_lock, shared=1)
2423
  def GetMACPrefix(self):
2424
    """Return the mac prefix.
2425

2426
    """
2427
    return self._config_data.cluster.mac_prefix
2428

    
2429
  @locking.ssynchronized(_config_lock, shared=1)
2430
  def GetClusterInfo(self):
2431
    """Returns information about the cluster
2432

2433
    @rtype: L{objects.Cluster}
2434
    @return: the cluster object
2435

2436
    """
2437
    return self._config_data.cluster
2438

    
2439
  @locking.ssynchronized(_config_lock, shared=1)
2440
  def HasAnyDiskOfType(self, dev_type):
2441
    """Check if in there is at disk of the given type in the configuration.
2442

2443
    """
2444
    return self._config_data.HasAnyDiskOfType(dev_type)
2445

    
2446
  @locking.ssynchronized(_config_lock)
2447
  def Update(self, target, feedback_fn, ec_id=None):
2448
    """Notify function to be called after updates.
2449

2450
    This function must be called when an object (as returned by
2451
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2452
    caller wants the modifications saved to the backing store. Note
2453
    that all modified objects will be saved, but the target argument
2454
    is the one the caller wants to ensure that it's saved.
2455

2456
    @param target: an instance of either L{objects.Cluster},
2457
        L{objects.Node} or L{objects.Instance} which is existing in
2458
        the cluster
2459
    @param feedback_fn: Callable feedback function
2460

2461
    """
2462
    if self._config_data is None:
2463
      raise errors.ProgrammerError("Configuration file not read,"
2464
                                   " cannot save.")
2465
    update_serial = False
2466
    if isinstance(target, objects.Cluster):
2467
      test = target == self._config_data.cluster
2468
    elif isinstance(target, objects.Node):
2469
      test = target in self._config_data.nodes.values()
2470
      update_serial = True
2471
    elif isinstance(target, objects.Instance):
2472
      test = target in self._config_data.instances.values()
2473
    elif isinstance(target, objects.NodeGroup):
2474
      test = target in self._config_data.nodegroups.values()
2475
    elif isinstance(target, objects.Network):
2476
      test = target in self._config_data.networks.values()
2477
    else:
2478
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2479
                                   " ConfigWriter.Update" % type(target))
2480
    if not test:
2481
      raise errors.ConfigurationError("Configuration updated since object"
2482
                                      " has been read or unknown object")
2483
    target.serial_no += 1
2484
    target.mtime = now = time.time()
2485

    
2486
    if update_serial:
2487
      # for node updates, we need to increase the cluster serial too
2488
      self._config_data.cluster.serial_no += 1
2489
      self._config_data.cluster.mtime = now
2490

    
2491
    if isinstance(target, objects.Instance):
2492
      self._UnlockedReleaseDRBDMinors(target.name)
2493

    
2494
    if ec_id is not None:
2495
      # Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
2496
      self._UnlockedCommitTemporaryIps(ec_id)
2497

    
2498
    self._WriteConfig(feedback_fn=feedback_fn)
2499

    
2500
  @locking.ssynchronized(_config_lock)
2501
  def DropECReservations(self, ec_id):
2502
    """Drop per-execution-context reservations
2503

2504
    """
2505
    for rm in self._all_rms:
2506
      rm.DropECReservations(ec_id)
2507

    
2508
  @locking.ssynchronized(_config_lock, shared=1)
2509
  def GetAllNetworksInfo(self):
2510
    """Get configuration info of all the networks.
2511

2512
    """
2513
    return dict(self._config_data.networks)
2514

    
2515
  def _UnlockedGetNetworkList(self):
2516
    """Get the list of networks.
2517

2518
    This function is for internal use, when the config lock is already held.
2519

2520
    """
2521
    return self._config_data.networks.keys()
2522

    
2523
  @locking.ssynchronized(_config_lock, shared=1)
2524
  def GetNetworkList(self):
2525
    """Get the list of networks.
2526

2527
    @return: array of networks, ex. ["main", "vlan100", "200]
2528

2529
    """
2530
    return self._UnlockedGetNetworkList()
2531

    
2532
  @locking.ssynchronized(_config_lock, shared=1)
2533
  def GetNetworkNames(self):
2534
    """Get a list of network names
2535

2536
    """
2537
    names = [net.name
2538
             for net in self._config_data.networks.values()]
2539
    return names
2540

    
2541
  def _UnlockedGetNetwork(self, uuid):
2542
    """Returns information about a network.
2543

2544
    This function is for internal use, when the config lock is already held.
2545

2546
    """
2547
    if uuid not in self._config_data.networks:
2548
      return None
2549

    
2550
    return self._config_data.networks[uuid]
2551

    
2552
  @locking.ssynchronized(_config_lock, shared=1)
2553
  def GetNetwork(self, uuid):
2554
    """Returns information about a network.
2555

2556
    It takes the information from the configuration file.
2557

2558
    @param uuid: UUID of the network
2559

2560
    @rtype: L{objects.Network}
2561
    @return: the network object
2562

2563
    """
2564
    return self._UnlockedGetNetwork(uuid)
2565

    
2566
  @locking.ssynchronized(_config_lock)
2567
  def AddNetwork(self, net, ec_id, check_uuid=True):
2568
    """Add a network to the configuration.
2569

2570
    @type net: L{objects.Network}
2571
    @param net: the Network object to add
2572
    @type ec_id: string
2573
    @param ec_id: unique id for the job to use when creating a missing UUID
2574

2575
    """
2576
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2577
    self._WriteConfig()
2578

    
2579
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2580
    """Add a network to the configuration.
2581

2582
    """
2583
    logging.info("Adding network %s to configuration", net.name)
2584

    
2585
    if check_uuid:
2586
      self._EnsureUUID(net, ec_id)
2587

    
2588
    net.serial_no = 1
2589
    net.ctime = net.mtime = time.time()
2590
    self._config_data.networks[net.uuid] = net
2591
    self._config_data.cluster.serial_no += 1
2592

    
2593
  def _UnlockedLookupNetwork(self, target):
2594
    """Lookup a network's UUID.
2595

2596
    @type target: string
2597
    @param target: network name or UUID
2598
    @rtype: string
2599
    @return: network UUID
2600
    @raises errors.OpPrereqError: when the target network cannot be found
2601

2602
    """
2603
    if target is None:
2604
      return None
2605
    if target in self._config_data.networks:
2606
      return target
2607
    for net in self._config_data.networks.values():
2608
      if net.name == target:
2609
        return net.uuid
2610
    raise errors.OpPrereqError("Network '%s' not found" % target,
2611
                               errors.ECODE_NOENT)
2612

    
2613
  @locking.ssynchronized(_config_lock, shared=1)
2614
  def LookupNetwork(self, target):
2615
    """Lookup a network's UUID.
2616

2617
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2618

2619
    @type target: string
2620
    @param target: network name or UUID
2621
    @rtype: string
2622
    @return: network UUID
2623

2624
    """
2625
    return self._UnlockedLookupNetwork(target)
2626

    
2627
  @locking.ssynchronized(_config_lock)
2628
  def RemoveNetwork(self, network_uuid):
2629
    """Remove a network from the configuration.
2630

2631
    @type network_uuid: string
2632
    @param network_uuid: the UUID of the network to remove
2633

2634
    """
2635
    logging.info("Removing network %s from configuration", network_uuid)
2636

    
2637
    if network_uuid not in self._config_data.networks:
2638
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2639

    
2640
    del self._config_data.networks[network_uuid]
2641
    self._config_data.cluster.serial_no += 1
2642
    self._WriteConfig()
2643

    
2644
  def _UnlockedGetGroupNetParams(self, net_uuid, node):
2645
    """Get the netparams (mode, link) of a network.
2646

2647
    Get a network's netparams for a given node.
2648

2649
    @type net_uuid: string
2650
    @param net_uuid: network uuid
2651
    @type node: string
2652
    @param node: node name
2653
    @rtype: dict or None
2654
    @return: netparams
2655

2656
    """
2657
    node_info = self._UnlockedGetNodeInfo(node)
2658
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2659
    netparams = nodegroup_info.networks.get(net_uuid, None)
2660

    
2661
    return netparams
2662

    
2663
  @locking.ssynchronized(_config_lock, shared=1)
2664
  def GetGroupNetParams(self, net_uuid, node):
2665
    """Locking wrapper of _UnlockedGetGroupNetParams()
2666

2667
    """
2668
    return self._UnlockedGetGroupNetParams(net_uuid, node)
2669

    
2670
  @locking.ssynchronized(_config_lock, shared=1)
2671
  def CheckIPInNodeGroup(self, ip, node):
2672
    """Check IP uniqueness in nodegroup.
2673

2674
    Check networks that are connected in the node's node group
2675
    if ip is contained in any of them. Used when creating/adding
2676
    a NIC to ensure uniqueness among nodegroups.
2677

2678
    @type ip: string
2679
    @param ip: ip address
2680
    @type node: string
2681
    @param node: node name
2682
    @rtype: (string, dict) or (None, None)
2683
    @return: (network name, netparams)
2684

2685
    """
2686
    if ip is None:
2687
      return (None, None)
2688
    node_info = self._UnlockedGetNodeInfo(node)
2689
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2690
    for net_uuid in nodegroup_info.networks.keys():
2691
      net_info = self._UnlockedGetNetwork(net_uuid)
2692
      pool = network.AddressPool(net_info)
2693
      if pool.Contains(ip):
2694
        return (net_info.name, nodegroup_info.networks[net_uuid])
2695

    
2696
    return (None, None)