Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 3c286190

History | View | Annotate | Download (84.2 kB)

1
#
2
#
3

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

    
21

    
22
"""Configuration management for Ganeti
23

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

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

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

32
"""
33

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

    
37
import os
38
import random
39
import logging
40
import time
41
import itertools
42
from functools import wraps
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
    ec_reserved = set()
114
    if ec_id in self._ec_reserved:
115
      ec_reserved.update(self._ec_reserved[ec_id])
116
    return ec_reserved
117

    
118
  def Generate(self, existing, generate_one_fn, ec_id):
119
    """Generate a new resource of this type
120

121
    """
122
    assert callable(generate_one_fn)
123

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

    
137

    
138
def _MatchNameComponentIgnoreCase(short_name, names):
139
  """Wrapper around L{utils.text.MatchNameComponent}.
140

141
  """
142
  return utils.MatchNameComponent(short_name, names, case_sensitive=False)
143

    
144

    
145
def _CheckInstanceDiskIvNames(disks):
146
  """Checks if instance's disks' C{iv_name} attributes are in order.
147

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

154
  """
155
  result = []
156

    
157
  for (idx, disk) in enumerate(disks):
158
    exp_iv_name = "disk/%s" % idx
159
    if disk.iv_name != exp_iv_name:
160
      result.append((idx, exp_iv_name, disk.iv_name))
161

    
162
  return result
163

    
164

    
165
def _GenerateMACSuffix():
166
  """Generate one mac address
167

168
  """
169
  byte1 = random.randrange(0, 256)
170
  byte2 = random.randrange(0, 256)
171
  byte3 = random.randrange(0, 256)
172
  suffix = "%02x:%02x:%02x" % (byte1, byte2, byte3)
173
  return suffix
174

    
175

    
176
class ConfigWriter:
177
  """The interface to the cluster configuration.
178

179
  @ivar _temporary_lvs: reservation manager for temporary LVs
180
  @ivar _all_rms: a list of all temporary reservation managers
181

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

    
213
  def _GetRpc(self, address_list):
214
    """Returns RPC runner for configuration.
215

216
    """
217
    return rpc.ConfigRunner(self._context, address_list)
218

    
219
  def SetContext(self, context):
220
    """Sets Ganeti context.
221

222
    """
223
    self._context = context
224

    
225
  # this method needs to be static, so that we can call it on the class
226
  @staticmethod
227
  def IsCluster():
228
    """Check if the cluster is configured.
229

230
    """
231
    return os.path.exists(pathutils.CLUSTER_CONF_FILE)
232

    
233
  def _GenerateMACPrefix(self, net=None):
234
    def _get_mac_prefix(view_func):
235
      def _decorator(*args, **kwargs):
236
        prefix = self._config_data.cluster.mac_prefix
237
        if net:
238
          net_uuid = self._UnlockedLookupNetwork(net)
239
          if net_uuid:
240
            nobj = self._UnlockedGetNetwork(net_uuid)
241
            if nobj.mac_prefix:
242
              prefix = nobj.mac_prefix
243
        suffix = view_func(*args, **kwargs)
244
        return prefix + ':' + suffix
245
      return wraps(view_func)(_decorator)
246
    return _get_mac_prefix
247

    
248
  @locking.ssynchronized(_config_lock, shared=1)
249
  def GetNdParams(self, node):
250
    """Get the node params populated with cluster defaults.
251

252
    @type node: L{objects.Node}
253
    @param node: The node we want to know the params for
254
    @return: A dict with the filled in node params
255

256
    """
257
    nodegroup = self._UnlockedGetNodeGroup(node.group)
258
    return self._config_data.cluster.FillND(node, nodegroup)
259

    
260
  @locking.ssynchronized(_config_lock, shared=1)
261
  def GetInstanceDiskParams(self, instance):
262
    """Get the disk params populated with inherit chain.
263

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

268
    """
269
    node = self._UnlockedGetNodeInfo(instance.primary_node)
270
    nodegroup = self._UnlockedGetNodeGroup(node.group)
271
    return self._UnlockedGetGroupDiskParams(nodegroup)
272

    
273
  @locking.ssynchronized(_config_lock, shared=1)
274
  def GetGroupDiskParams(self, group):
275
    """Get the disk params populated with inherit chain.
276

277
    @type group: L{objects.NodeGroup}
278
    @param group: The group we want to know the params for
279
    @return: A dict with the filled in disk params
280

281
    """
282
    return self._UnlockedGetGroupDiskParams(group)
283

    
284
  def _UnlockedGetGroupDiskParams(self, group):
285
    """Get the disk params populated with inherit chain down to node-group.
286

287
    @type group: L{objects.NodeGroup}
288
    @param group: The group we want to know the params for
289
    @return: A dict with the filled in disk params
290

291
    """
292
    return self._config_data.cluster.SimpleFillDP(group.diskparams)
293

    
294
  @locking.ssynchronized(_config_lock, shared=1)
295
  def GenerateMAC(self, net, ec_id):
296
    """Generate a MAC for an instance.
297

298
    This should check the current instances for duplicates.
299

300
    """
301
    existing = self._AllMACs()
302
    gen_mac = self._GenerateMACPrefix(net)(_GenerateMACSuffix)
303
    return self._temporary_ids.Generate(existing, gen_mac, ec_id)
304

    
305
  @locking.ssynchronized(_config_lock, shared=1)
306
  def ReserveMAC(self, mac, ec_id):
307
    """Reserve a MAC for an instance.
308

309
    This only checks instances managed by this cluster, it does not
310
    check for potential collisions elsewhere.
311

312
    """
313
    all_macs = self._AllMACs()
314
    if mac in all_macs:
315
      raise errors.ReservationError("mac already in use")
316
    else:
317
      self._temporary_macs.Reserve(ec_id, mac)
318

    
319
  def _UnlockedCommitTemporaryIps(self, ec_id):
320
    """Commit all reserved IP address to their respective pools
321

322
    """
323
    for action, address, net_uuid in self._temporary_ips.GetECReserved(ec_id):
324
      self._UnlockedCommitIp(action, net_uuid, address)
325

    
326
  def _UnlockedCommitIp(self, action, net_uuid, address):
327
    """Commit a reserved IP address to an IP pool.
328

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

331
    """
332
    nobj = self._UnlockedGetNetwork(net_uuid)
333
    pool = network.AddressPool(nobj)
334
    if action == 'reserve':
335
      pool.Reserve(address)
336
    elif action == 'release':
337
      pool.Release(address)
338

    
339
  def _UnlockedReleaseIp(self, net_uuid, address, ec_id):
340
    """Give a specific IP address back to an IP pool.
341

342
    The IP address is returned to the IP pool designated by pool_id and marked
343
    as reserved.
344

345
    """
346
    self._temporary_ips.Reserve(ec_id, ('release', address, net_uuid))
347

    
348
  @locking.ssynchronized(_config_lock, shared=1)
349
  def ReleaseIp(self, net, address, ec_id):
350
    """Give a specified IP address back to an IP pool.
351

352
    This is just a wrapper around _UnlockedReleaseIp.
353

354
    """
355
    net_uuid = self._UnlockedLookupNetwork(net)
356
    if net_uuid:
357
      self._UnlockedReleaseIp(net_uuid, address, ec_id)
358

    
359
  @locking.ssynchronized(_config_lock, shared=1)
360
  def GenerateIp(self, net, ec_id):
361
    """Find a free IPv4 address for an instance.
362

363
    """
364
    net_uuid = self._UnlockedLookupNetwork(net)
365
    nobj = self._UnlockedGetNetwork(net_uuid)
366
    pool = network.AddressPool(nobj)
367
    gen_free = pool.GenerateFree()
368

    
369
    def gen_one():
370
      try:
371
        ip = gen_free()
372
      except StopIteration:
373
        raise errors.ReservationError("Cannot generate IP. Network is full")
374
      return ("reserve", ip, net_uuid)
375

    
376
    _, address, _ = self._temporary_ips.Generate([], gen_one, ec_id)
377
    return address
378

    
379
  def _UnlockedReserveIp(self, net_uuid, address, ec_id):
380
    """Reserve a given IPv4 address for use by an instance.
381

382
    """
383
    nobj = self._UnlockedGetNetwork(net_uuid)
384
    pool = network.AddressPool(nobj)
385
    try:
386
      isreserved = pool.IsReserved(address)
387
    except errors.AddressPoolError:
388
      raise errors.ReservationError("IP address not in network")
389
    if isreserved:
390
      raise errors.ReservationError("IP address already in use")
391

    
392
    return self._temporary_ips.Reserve(ec_id, ('reserve', address, net_uuid))
393

    
394
  @locking.ssynchronized(_config_lock, shared=1)
395
  def ReserveIp(self, net, address, ec_id):
396
    """Reserve a given IPv4 address for use by an instance.
397

398
    """
399
    net_uuid = self._UnlockedLookupNetwork(net)
400
    if net_uuid:
401
      return self._UnlockedReserveIp(net_uuid, address, ec_id)
402

    
403
  @locking.ssynchronized(_config_lock, shared=1)
404
  def ReserveLV(self, lv_name, ec_id):
405
    """Reserve an VG/LV pair for an instance.
406

407
    @type lv_name: string
408
    @param lv_name: the logical volume name to reserve
409

410
    """
411
    all_lvs = self._AllLVs()
412
    if lv_name in all_lvs:
413
      raise errors.ReservationError("LV already in use")
414
    else:
415
      self._temporary_lvs.Reserve(ec_id, lv_name)
416

    
417
  @locking.ssynchronized(_config_lock, shared=1)
418
  def GenerateDRBDSecret(self, ec_id):
419
    """Generate a DRBD secret.
420

421
    This checks the current disks for duplicates.
422

423
    """
424
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
425
                                            utils.GenerateSecret,
426
                                            ec_id)
427

    
428
  def _AllLVs(self):
429
    """Compute the list of all LVs.
430

431
    """
432
    lvnames = set()
433
    for instance in self._config_data.instances.values():
434
      node_data = instance.MapLVsByNode()
435
      for lv_list in node_data.values():
436
        lvnames.update(lv_list)
437
    return lvnames
438

    
439
  def _AllIDs(self, include_temporary):
440
    """Compute the list of all UUIDs and names we have.
441

442
    @type include_temporary: boolean
443
    @param include_temporary: whether to include the _temporary_ids set
444
    @rtype: set
445
    @return: a set of IDs
446

447
    """
448
    existing = set()
449
    if include_temporary:
450
      existing.update(self._temporary_ids.GetReserved())
451
    existing.update(self._AllLVs())
452
    existing.update(self._config_data.instances.keys())
453
    existing.update(self._config_data.nodes.keys())
454
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
455
    return existing
456

    
457
  def _GenerateUniqueID(self, ec_id):
458
    """Generate an unique UUID.
459

460
    This checks the current node, instances and disk names for
461
    duplicates.
462

463
    @rtype: string
464
    @return: the unique id
465

466
    """
467
    existing = self._AllIDs(include_temporary=False)
468
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
469

    
470
  @locking.ssynchronized(_config_lock, shared=1)
471
  def GenerateUniqueID(self, ec_id):
472
    """Generate an unique ID.
473

474
    This is just a wrapper over the unlocked version.
475

476
    @type ec_id: string
477
    @param ec_id: unique id for the job to reserve the id to
478

479
    """
480
    return self._GenerateUniqueID(ec_id)
481

    
482
  def _AllMACs(self):
483
    """Return all MACs present in the config.
484

485
    @rtype: list
486
    @return: the list of all MACs
487

488
    """
489
    result = []
490
    for instance in self._config_data.instances.values():
491
      for nic in instance.nics:
492
        result.append(nic.mac)
493

    
494
    return result
495

    
496
  def _AllDRBDSecrets(self):
497
    """Return all DRBD secrets present in the config.
498

499
    @rtype: list
500
    @return: the list of all DRBD secrets
501

502
    """
503
    def helper(disk, result):
504
      """Recursively gather secrets from this disk."""
505
      if disk.dev_type == constants.DT_DRBD8:
506
        result.append(disk.logical_id[5])
507
      if disk.children:
508
        for child in disk.children:
509
          helper(child, result)
510

    
511
    result = []
512
    for instance in self._config_data.instances.values():
513
      for disk in instance.disks:
514
        helper(disk, result)
515

    
516
    return result
517

    
518
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
519
    """Compute duplicate disk IDs
520

521
    @type disk: L{objects.Disk}
522
    @param disk: the disk at which to start searching
523
    @type l_ids: list
524
    @param l_ids: list of current logical ids
525
    @type p_ids: list
526
    @param p_ids: list of current physical ids
527
    @rtype: list
528
    @return: a list of error messages
529

530
    """
531
    result = []
532
    if disk.logical_id is not None:
533
      if disk.logical_id in l_ids:
534
        result.append("duplicate logical id %s" % str(disk.logical_id))
535
      else:
536
        l_ids.append(disk.logical_id)
537
    if disk.physical_id is not None:
538
      if disk.physical_id in p_ids:
539
        result.append("duplicate physical id %s" % str(disk.physical_id))
540
      else:
541
        p_ids.append(disk.physical_id)
542

    
543
    if disk.children:
544
      for child in disk.children:
545
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
546
    return result
547

    
548
  def _UnlockedVerifyConfig(self):
549
    """Verify function.
550

551
    @rtype: list
552
    @return: a list of error messages; a non-empty list signifies
553
        configuration errors
554

555
    """
556
    # pylint: disable=R0914
557
    result = []
558
    seen_macs = []
559
    ports = {}
560
    data = self._config_data
561
    cluster = data.cluster
562
    seen_lids = []
563
    seen_pids = []
564

    
565
    # global cluster checks
566
    if not cluster.enabled_hypervisors:
567
      result.append("enabled hypervisors list doesn't have any entries")
568
    invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
569
    if invalid_hvs:
570
      result.append("enabled hypervisors contains invalid entries: %s" %
571
                    invalid_hvs)
572
    missing_hvp = (set(cluster.enabled_hypervisors) -
573
                   set(cluster.hvparams.keys()))
574
    if missing_hvp:
575
      result.append("hypervisor parameters missing for the enabled"
576
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
577

    
578
    if cluster.master_node not in data.nodes:
579
      result.append("cluster has invalid primary node '%s'" %
580
                    cluster.master_node)
581

    
582
    def _helper(owner, attr, value, template):
583
      try:
584
        utils.ForceDictType(value, template)
585
      except errors.GenericError, err:
586
        result.append("%s has invalid %s: %s" % (owner, attr, err))
587

    
588
    def _helper_nic(owner, params):
589
      try:
590
        objects.NIC.CheckParameterSyntax(params)
591
      except errors.ConfigurationError, err:
592
        result.append("%s has invalid nicparams: %s" % (owner, err))
593

    
594
    def _helper_ipolicy(owner, params, check_std):
595
      try:
596
        objects.InstancePolicy.CheckParameterSyntax(params, check_std)
597
      except errors.ConfigurationError, err:
598
        result.append("%s has invalid instance policy: %s" % (owner, err))
599

    
600
    def _helper_ispecs(owner, params):
601
      for key, value in params.items():
602
        if key in constants.IPOLICY_ISPECS:
603
          fullkey = "ipolicy/" + key
604
          _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
605
        else:
606
          # FIXME: assuming list type
607
          if key in constants.IPOLICY_PARAMETERS:
608
            exp_type = float
609
          else:
610
            exp_type = list
611
          if not isinstance(value, exp_type):
612
            result.append("%s has invalid instance policy: for %s,"
613
                          " expecting %s, got %s" %
614
                          (owner, key, exp_type.__name__, type(value)))
615

    
616
    # check cluster parameters
617
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
618
            constants.BES_PARAMETER_TYPES)
619
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
620
            constants.NICS_PARAMETER_TYPES)
621
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
622
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
623
            constants.NDS_PARAMETER_TYPES)
624
    _helper_ipolicy("cluster", cluster.SimpleFillIPolicy({}), True)
625
    _helper_ispecs("cluster", cluster.SimpleFillIPolicy({}))
626

    
627
    # per-instance checks
628
    for instance_name in data.instances:
629
      instance = data.instances[instance_name]
630
      if instance.name != instance_name:
631
        result.append("instance '%s' is indexed by wrong name '%s'" %
632
                      (instance.name, instance_name))
633
      if instance.primary_node not in data.nodes:
634
        result.append("instance '%s' has invalid primary node '%s'" %
635
                      (instance_name, instance.primary_node))
636
      for snode in instance.secondary_nodes:
637
        if snode not in data.nodes:
638
          result.append("instance '%s' has invalid secondary node '%s'" %
639
                        (instance_name, snode))
640
      for idx, nic in enumerate(instance.nics):
641
        if nic.mac in seen_macs:
642
          result.append("instance '%s' has NIC %d mac %s duplicate" %
643
                        (instance_name, idx, nic.mac))
644
        else:
645
          seen_macs.append(nic.mac)
646
        if nic.nicparams:
647
          filled = cluster.SimpleFillNIC(nic.nicparams)
648
          owner = "instance %s nic %d" % (instance.name, idx)
649
          _helper(owner, "nicparams",
650
                  filled, constants.NICS_PARAMETER_TYPES)
651
          _helper_nic(owner, filled)
652

    
653
      # parameter checks
654
      if instance.beparams:
655
        _helper("instance %s" % instance.name, "beparams",
656
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
657

    
658
      # gather the drbd ports for duplicate checks
659
      for (idx, dsk) in enumerate(instance.disks):
660
        if dsk.dev_type in constants.LDS_DRBD:
661
          tcp_port = dsk.logical_id[2]
662
          if tcp_port not in ports:
663
            ports[tcp_port] = []
664
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
665
      # gather network port reservation
666
      net_port = getattr(instance, "network_port", None)
667
      if net_port is not None:
668
        if net_port not in ports:
669
          ports[net_port] = []
670
        ports[net_port].append((instance.name, "network port"))
671

    
672
      # instance disk verify
673
      for idx, disk in enumerate(instance.disks):
674
        result.extend(["instance '%s' disk %d error: %s" %
675
                       (instance.name, idx, msg) for msg in disk.Verify()])
676
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
677

    
678
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
679
      if wrong_names:
680
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
681
                         (idx, exp_name, actual_name))
682
                        for (idx, exp_name, actual_name) in wrong_names)
683

    
684
        result.append("Instance '%s' has wrongly named disks: %s" %
685
                      (instance.name, tmp))
686

    
687
    # cluster-wide pool of free ports
688
    for free_port in cluster.tcpudp_port_pool:
689
      if free_port not in ports:
690
        ports[free_port] = []
691
      ports[free_port].append(("cluster", "port marked as free"))
692

    
693
    # compute tcp/udp duplicate ports
694
    keys = ports.keys()
695
    keys.sort()
696
    for pnum in keys:
697
      pdata = ports[pnum]
698
      if len(pdata) > 1:
699
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
700
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
701

    
702
    # highest used tcp port check
703
    if keys:
704
      if keys[-1] > cluster.highest_used_port:
705
        result.append("Highest used port mismatch, saved %s, computed %s" %
706
                      (cluster.highest_used_port, keys[-1]))
707

    
708
    if not data.nodes[cluster.master_node].master_candidate:
709
      result.append("Master node is not a master candidate")
710

    
711
    # master candidate checks
712
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
713
    if mc_now < mc_max:
714
      result.append("Not enough master candidates: actual %d, target %d" %
715
                    (mc_now, mc_max))
716

    
717
    # node checks
718
    for node_name, node in data.nodes.items():
719
      if node.name != node_name:
720
        result.append("Node '%s' is indexed by wrong name '%s'" %
721
                      (node.name, node_name))
722
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
723
        result.append("Node %s state is invalid: master_candidate=%s,"
724
                      " drain=%s, offline=%s" %
725
                      (node.name, node.master_candidate, node.drained,
726
                       node.offline))
727
      if node.group not in data.nodegroups:
728
        result.append("Node '%s' has invalid group '%s'" %
729
                      (node.name, node.group))
730
      else:
731
        _helper("node %s" % node.name, "ndparams",
732
                cluster.FillND(node, data.nodegroups[node.group]),
733
                constants.NDS_PARAMETER_TYPES)
734

    
735
    # nodegroups checks
736
    nodegroups_names = set()
737
    for nodegroup_uuid in data.nodegroups:
738
      nodegroup = data.nodegroups[nodegroup_uuid]
739
      if nodegroup.uuid != nodegroup_uuid:
740
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
741
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
742
      if utils.UUID_RE.match(nodegroup.name.lower()):
743
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
744
                      (nodegroup.name, nodegroup.uuid))
745
      if nodegroup.name in nodegroups_names:
746
        result.append("duplicate node group name '%s'" % nodegroup.name)
747
      else:
748
        nodegroups_names.add(nodegroup.name)
749
      group_name = "group %s" % nodegroup.name
750
      _helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy),
751
                      False)
752
      _helper_ispecs(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy))
753
      if nodegroup.ndparams:
754
        _helper(group_name, "ndparams",
755
                cluster.SimpleFillND(nodegroup.ndparams),
756
                constants.NDS_PARAMETER_TYPES)
757

    
758
    # drbd minors check
759
    _, duplicates = self._UnlockedComputeDRBDMap()
760
    for node, minor, instance_a, instance_b in duplicates:
761
      result.append("DRBD minor %d on node %s is assigned twice to instances"
762
                    " %s and %s" % (minor, node, instance_a, instance_b))
763

    
764
    # IP checks
765
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
766
    ips = {}
767

    
768
    def _AddIpAddress(ip, name):
769
      ips.setdefault(ip, []).append(name)
770

    
771
    _AddIpAddress(cluster.master_ip, "cluster_ip")
772

    
773
    for node in data.nodes.values():
774
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
775
      if node.secondary_ip != node.primary_ip:
776
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
777

    
778
    for instance in data.instances.values():
779
      for idx, nic in enumerate(instance.nics):
780
        if nic.ip is None:
781
          continue
782

    
783
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
784
        nic_mode = nicparams[constants.NIC_MODE]
785
        nic_link = nicparams[constants.NIC_LINK]
786

    
787
        if nic_mode == constants.NIC_MODE_BRIDGED:
788
          link = "bridge:%s" % nic_link
789
        elif nic_mode == constants.NIC_MODE_ROUTED:
790
          link = "route:%s" % nic_link
791
        else:
792
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
793

    
794
        _AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
795
                      "instance:%s/nic:%d" % (instance.name, idx))
796

    
797
    for ip, owners in ips.items():
798
      if len(owners) > 1:
799
        result.append("IP address %s is used by multiple owners: %s" %
800
                      (ip, utils.CommaJoin(owners)))
801

    
802
    return result
803

    
804
  @locking.ssynchronized(_config_lock, shared=1)
805
  def VerifyConfig(self):
806
    """Verify function.
807

808
    This is just a wrapper over L{_UnlockedVerifyConfig}.
809

810
    @rtype: list
811
    @return: a list of error messages; a non-empty list signifies
812
        configuration errors
813

814
    """
815
    return self._UnlockedVerifyConfig()
816

    
817
  def _UnlockedSetDiskID(self, disk, node_name):
818
    """Convert the unique ID to the ID needed on the target nodes.
819

820
    This is used only for drbd, which needs ip/port configuration.
821

822
    The routine descends down and updates its children also, because
823
    this helps when the only the top device is passed to the remote
824
    node.
825

826
    This function is for internal use, when the config lock is already held.
827

828
    """
829
    if disk.children:
830
      for child in disk.children:
831
        self._UnlockedSetDiskID(child, node_name)
832

    
833
    if disk.logical_id is None and disk.physical_id is not None:
834
      return
835
    if disk.dev_type == constants.LD_DRBD8:
836
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
837
      if node_name not in (pnode, snode):
838
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
839
                                        node_name)
840
      pnode_info = self._UnlockedGetNodeInfo(pnode)
841
      snode_info = self._UnlockedGetNodeInfo(snode)
842
      if pnode_info is None or snode_info is None:
843
        raise errors.ConfigurationError("Can't find primary or secondary node"
844
                                        " for %s" % str(disk))
845
      p_data = (pnode_info.secondary_ip, port)
846
      s_data = (snode_info.secondary_ip, port)
847
      if pnode == node_name:
848
        disk.physical_id = p_data + s_data + (pminor, secret)
849
      else: # it must be secondary, we tested above
850
        disk.physical_id = s_data + p_data + (sminor, secret)
851
    else:
852
      disk.physical_id = disk.logical_id
853
    return
854

    
855
  @locking.ssynchronized(_config_lock)
856
  def SetDiskID(self, disk, node_name):
857
    """Convert the unique ID to the ID needed on the target nodes.
858

859
    This is used only for drbd, which needs ip/port configuration.
860

861
    The routine descends down and updates its children also, because
862
    this helps when the only the top device is passed to the remote
863
    node.
864

865
    """
866
    return self._UnlockedSetDiskID(disk, node_name)
867

    
868
  @locking.ssynchronized(_config_lock)
869
  def AddTcpUdpPort(self, port):
870
    """Adds a new port to the available port pool.
871

872
    @warning: this method does not "flush" the configuration (via
873
        L{_WriteConfig}); callers should do that themselves once the
874
        configuration is stable
875

876
    """
877
    if not isinstance(port, int):
878
      raise errors.ProgrammerError("Invalid type passed for port")
879

    
880
    self._config_data.cluster.tcpudp_port_pool.add(port)
881

    
882
  @locking.ssynchronized(_config_lock, shared=1)
883
  def GetPortList(self):
884
    """Returns a copy of the current port list.
885

886
    """
887
    return self._config_data.cluster.tcpudp_port_pool.copy()
888

    
889
  @locking.ssynchronized(_config_lock)
890
  def AllocatePort(self):
891
    """Allocate a port.
892

893
    The port will be taken from the available port pool or from the
894
    default port range (and in this case we increase
895
    highest_used_port).
896

897
    """
898
    # If there are TCP/IP ports configured, we use them first.
899
    if self._config_data.cluster.tcpudp_port_pool:
900
      port = self._config_data.cluster.tcpudp_port_pool.pop()
901
    else:
902
      port = self._config_data.cluster.highest_used_port + 1
903
      if port >= constants.LAST_DRBD_PORT:
904
        raise errors.ConfigurationError("The highest used port is greater"
905
                                        " than %s. Aborting." %
906
                                        constants.LAST_DRBD_PORT)
907
      self._config_data.cluster.highest_used_port = port
908

    
909
    self._WriteConfig()
910
    return port
911

    
912
  def _UnlockedComputeDRBDMap(self):
913
    """Compute the used DRBD minor/nodes.
914

915
    @rtype: (dict, list)
916
    @return: dictionary of node_name: dict of minor: instance_name;
917
        the returned dict will have all the nodes in it (even if with
918
        an empty list), and a list of duplicates; if the duplicates
919
        list is not empty, the configuration is corrupted and its caller
920
        should raise an exception
921

922
    """
923
    def _AppendUsedPorts(instance_name, disk, used):
924
      duplicates = []
925
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
926
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
927
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
928
          assert node in used, ("Node '%s' of instance '%s' not found"
929
                                " in node list" % (node, instance_name))
930
          if port in used[node]:
931
            duplicates.append((node, port, instance_name, used[node][port]))
932
          else:
933
            used[node][port] = instance_name
934
      if disk.children:
935
        for child in disk.children:
936
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
937
      return duplicates
938

    
939
    duplicates = []
940
    my_dict = dict((node, {}) for node in self._config_data.nodes)
941
    for instance in self._config_data.instances.itervalues():
942
      for disk in instance.disks:
943
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
944
    for (node, minor), instance in self._temporary_drbds.iteritems():
945
      if minor in my_dict[node] and my_dict[node][minor] != instance:
946
        duplicates.append((node, minor, instance, my_dict[node][minor]))
947
      else:
948
        my_dict[node][minor] = instance
949
    return my_dict, duplicates
950

    
951
  @locking.ssynchronized(_config_lock)
952
  def ComputeDRBDMap(self):
953
    """Compute the used DRBD minor/nodes.
954

955
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
956

957
    @return: dictionary of node_name: dict of minor: instance_name;
958
        the returned dict will have all the nodes in it (even if with
959
        an empty list).
960

961
    """
962
    d_map, duplicates = self._UnlockedComputeDRBDMap()
963
    if duplicates:
964
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
965
                                      str(duplicates))
966
    return d_map
967

    
968
  @locking.ssynchronized(_config_lock)
969
  def AllocateDRBDMinor(self, nodes, instance):
970
    """Allocate a drbd minor.
971

972
    The free minor will be automatically computed from the existing
973
    devices. A node can be given multiple times in order to allocate
974
    multiple minors. The result is the list of minors, in the same
975
    order as the passed nodes.
976

977
    @type instance: string
978
    @param instance: the instance for which we allocate minors
979

980
    """
981
    assert isinstance(instance, basestring), \
982
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
983

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

    
1024
  def _UnlockedReleaseDRBDMinors(self, instance):
1025
    """Release temporary drbd minors allocated for a given instance.
1026

1027
    @type instance: string
1028
    @param instance: the instance for which temporary minors should be
1029
                     released
1030

1031
    """
1032
    assert isinstance(instance, basestring), \
1033
           "Invalid argument passed to ReleaseDRBDMinors"
1034
    for key, name in self._temporary_drbds.items():
1035
      if name == instance:
1036
        del self._temporary_drbds[key]
1037

    
1038
  @locking.ssynchronized(_config_lock)
1039
  def ReleaseDRBDMinors(self, instance):
1040
    """Release temporary drbd minors allocated for a given instance.
1041

1042
    This should be called on the error paths, on the success paths
1043
    it's automatically called by the ConfigWriter add and update
1044
    functions.
1045

1046
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
1047

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

1052
    """
1053
    self._UnlockedReleaseDRBDMinors(instance)
1054

    
1055
  @locking.ssynchronized(_config_lock, shared=1)
1056
  def GetConfigVersion(self):
1057
    """Get the configuration version.
1058

1059
    @return: Config version
1060

1061
    """
1062
    return self._config_data.version
1063

    
1064
  @locking.ssynchronized(_config_lock, shared=1)
1065
  def GetClusterName(self):
1066
    """Get cluster name.
1067

1068
    @return: Cluster name
1069

1070
    """
1071
    return self._config_data.cluster.cluster_name
1072

    
1073
  @locking.ssynchronized(_config_lock, shared=1)
1074
  def GetMasterNode(self):
1075
    """Get the hostname of the master node for this cluster.
1076

1077
    @return: Master hostname
1078

1079
    """
1080
    return self._config_data.cluster.master_node
1081

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

1086
    @return: Master IP
1087

1088
    """
1089
    return self._config_data.cluster.master_ip
1090

    
1091
  @locking.ssynchronized(_config_lock, shared=1)
1092
  def GetMasterNetdev(self):
1093
    """Get the master network device for this cluster.
1094

1095
    """
1096
    return self._config_data.cluster.master_netdev
1097

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

1102
    """
1103
    return self._config_data.cluster.master_netmask
1104

    
1105
  @locking.ssynchronized(_config_lock, shared=1)
1106
  def GetUseExternalMipScript(self):
1107
    """Get flag representing whether to use the external master IP setup script.
1108

1109
    """
1110
    return self._config_data.cluster.use_external_mip_script
1111

    
1112
  @locking.ssynchronized(_config_lock, shared=1)
1113
  def GetFileStorageDir(self):
1114
    """Get the file storage dir for this cluster.
1115

1116
    """
1117
    return self._config_data.cluster.file_storage_dir
1118

    
1119
  @locking.ssynchronized(_config_lock, shared=1)
1120
  def GetSharedFileStorageDir(self):
1121
    """Get the shared file storage dir for this cluster.
1122

1123
    """
1124
    return self._config_data.cluster.shared_file_storage_dir
1125

    
1126
  @locking.ssynchronized(_config_lock, shared=1)
1127
  def GetHypervisorType(self):
1128
    """Get the hypervisor type for this cluster.
1129

1130
    """
1131
    return self._config_data.cluster.enabled_hypervisors[0]
1132

    
1133
  @locking.ssynchronized(_config_lock, shared=1)
1134
  def GetHostKey(self):
1135
    """Return the rsa hostkey from the config.
1136

1137
    @rtype: string
1138
    @return: the rsa hostkey
1139

1140
    """
1141
    return self._config_data.cluster.rsahostkeypub
1142

    
1143
  @locking.ssynchronized(_config_lock, shared=1)
1144
  def GetDefaultIAllocator(self):
1145
    """Get the default instance allocator for this cluster.
1146

1147
    """
1148
    return self._config_data.cluster.default_iallocator
1149

    
1150
  @locking.ssynchronized(_config_lock, shared=1)
1151
  def GetPrimaryIPFamily(self):
1152
    """Get cluster primary ip family.
1153

1154
    @return: primary ip family
1155

1156
    """
1157
    return self._config_data.cluster.primary_ip_family
1158

    
1159
  @locking.ssynchronized(_config_lock, shared=1)
1160
  def GetMasterNetworkParameters(self):
1161
    """Get network parameters of the master node.
1162

1163
    @rtype: L{object.MasterNetworkParameters}
1164
    @return: network parameters of the master node
1165

1166
    """
1167
    cluster = self._config_data.cluster
1168
    result = objects.MasterNetworkParameters(
1169
      name=cluster.master_node, ip=cluster.master_ip,
1170
      netmask=cluster.master_netmask, netdev=cluster.master_netdev,
1171
      ip_family=cluster.primary_ip_family)
1172

    
1173
    return result
1174

    
1175
  @locking.ssynchronized(_config_lock)
1176
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1177
    """Add a node group to the configuration.
1178

1179
    This method calls group.UpgradeConfig() to fill any missing attributes
1180
    according to their default values.
1181

1182
    @type group: L{objects.NodeGroup}
1183
    @param group: the NodeGroup object to add
1184
    @type ec_id: string
1185
    @param ec_id: unique id for the job to use when creating a missing UUID
1186
    @type check_uuid: bool
1187
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1188
                       it does, ensure that it does not exist in the
1189
                       configuration already
1190

1191
    """
1192
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1193
    self._WriteConfig()
1194

    
1195
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1196
    """Add a node group to the configuration.
1197

1198
    """
1199
    logging.info("Adding node group %s to configuration", group.name)
1200

    
1201
    # Some code might need to add a node group with a pre-populated UUID
1202
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1203
    # the "does this UUID" exist already check.
1204
    if check_uuid:
1205
      self._EnsureUUID(group, ec_id)
1206

    
1207
    try:
1208
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1209
    except errors.OpPrereqError:
1210
      pass
1211
    else:
1212
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1213
                                 " node group (UUID: %s)" %
1214
                                 (group.name, existing_uuid),
1215
                                 errors.ECODE_EXISTS)
1216

    
1217
    group.serial_no = 1
1218
    group.ctime = group.mtime = time.time()
1219
    group.UpgradeConfig()
1220

    
1221
    self._config_data.nodegroups[group.uuid] = group
1222
    self._config_data.cluster.serial_no += 1
1223

    
1224
  @locking.ssynchronized(_config_lock)
1225
  def RemoveNodeGroup(self, group_uuid):
1226
    """Remove a node group from the configuration.
1227

1228
    @type group_uuid: string
1229
    @param group_uuid: the UUID of the node group to remove
1230

1231
    """
1232
    logging.info("Removing node group %s from configuration", group_uuid)
1233

    
1234
    if group_uuid not in self._config_data.nodegroups:
1235
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1236

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

    
1240
    del self._config_data.nodegroups[group_uuid]
1241
    self._config_data.cluster.serial_no += 1
1242
    self._WriteConfig()
1243

    
1244
  def _UnlockedLookupNodeGroup(self, target):
1245
    """Lookup a node group's UUID.
1246

1247
    @type target: string or None
1248
    @param target: group name or UUID or None to look for the default
1249
    @rtype: string
1250
    @return: nodegroup UUID
1251
    @raises errors.OpPrereqError: when the target group cannot be found
1252

1253
    """
1254
    if target is None:
1255
      if len(self._config_data.nodegroups) != 1:
1256
        raise errors.OpPrereqError("More than one node group exists. Target"
1257
                                   " group must be specified explicitly.")
1258
      else:
1259
        return self._config_data.nodegroups.keys()[0]
1260
    if target in self._config_data.nodegroups:
1261
      return target
1262
    for nodegroup in self._config_data.nodegroups.values():
1263
      if nodegroup.name == target:
1264
        return nodegroup.uuid
1265
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1266
                               errors.ECODE_NOENT)
1267

    
1268
  @locking.ssynchronized(_config_lock, shared=1)
1269
  def LookupNodeGroup(self, target):
1270
    """Lookup a node group's UUID.
1271

1272
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1273

1274
    @type target: string or None
1275
    @param target: group name or UUID or None to look for the default
1276
    @rtype: string
1277
    @return: nodegroup UUID
1278

1279
    """
1280
    return self._UnlockedLookupNodeGroup(target)
1281

    
1282
  def _UnlockedGetNodeGroup(self, uuid):
1283
    """Lookup a node group.
1284

1285
    @type uuid: string
1286
    @param uuid: group UUID
1287
    @rtype: L{objects.NodeGroup} or None
1288
    @return: nodegroup object, or None if not found
1289

1290
    """
1291
    if uuid not in self._config_data.nodegroups:
1292
      return None
1293

    
1294
    return self._config_data.nodegroups[uuid]
1295

    
1296
  @locking.ssynchronized(_config_lock, shared=1)
1297
  def GetNodeGroup(self, uuid):
1298
    """Lookup a node group.
1299

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

1305
    """
1306
    return self._UnlockedGetNodeGroup(uuid)
1307

    
1308
  @locking.ssynchronized(_config_lock, shared=1)
1309
  def GetAllNodeGroupsInfo(self):
1310
    """Get the configuration of all node groups.
1311

1312
    """
1313
    return dict(self._config_data.nodegroups)
1314

    
1315
  @locking.ssynchronized(_config_lock, shared=1)
1316
  def GetNodeGroupList(self):
1317
    """Get a list of node groups.
1318

1319
    """
1320
    return self._config_data.nodegroups.keys()
1321

    
1322
  @locking.ssynchronized(_config_lock, shared=1)
1323
  def GetNodeGroupMembersByNodes(self, nodes):
1324
    """Get nodes which are member in the same nodegroups as the given nodes.
1325

1326
    """
1327
    ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1328
    return frozenset(member_name
1329
                     for node_name in nodes
1330
                     for member_name in
1331
                       self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1332

    
1333
  @locking.ssynchronized(_config_lock, shared=1)
1334
  def GetMultiNodeGroupInfo(self, group_uuids):
1335
    """Get the configuration of multiple node groups.
1336

1337
    @param group_uuids: List of node group UUIDs
1338
    @rtype: list
1339
    @return: List of tuples of (group_uuid, group_info)
1340

1341
    """
1342
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1343

    
1344
  @locking.ssynchronized(_config_lock)
1345
  def AddInstance(self, instance, ec_id):
1346
    """Add an instance to the config.
1347

1348
    This should be used after creating a new instance.
1349

1350
    @type instance: L{objects.Instance}
1351
    @param instance: the instance object
1352

1353
    """
1354
    if not isinstance(instance, objects.Instance):
1355
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1356

    
1357
    if instance.disk_template != constants.DT_DISKLESS:
1358
      all_lvs = instance.MapLVsByNode()
1359
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1360

    
1361
    all_macs = self._AllMACs()
1362
    for nic in instance.nics:
1363
      if nic.mac in all_macs:
1364
        raise errors.ConfigurationError("Cannot add instance %s:"
1365
                                        " MAC address '%s' already in use." %
1366
                                        (instance.name, nic.mac))
1367

    
1368
    self._EnsureUUID(instance, ec_id)
1369

    
1370
    instance.serial_no = 1
1371
    instance.ctime = instance.mtime = time.time()
1372
    self._config_data.instances[instance.name] = instance
1373
    self._config_data.cluster.serial_no += 1
1374
    self._UnlockedReleaseDRBDMinors(instance.name)
1375
    self._UnlockedCommitTemporaryIps(ec_id)
1376
    self._WriteConfig()
1377

    
1378
  def _EnsureUUID(self, item, ec_id):
1379
    """Ensures a given object has a valid UUID.
1380

1381
    @param item: the instance or node to be checked
1382
    @param ec_id: the execution context id for the uuid reservation
1383

1384
    """
1385
    if not item.uuid:
1386
      item.uuid = self._GenerateUniqueID(ec_id)
1387
    elif item.uuid in self._AllIDs(include_temporary=True):
1388
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1389
                                      " in use" % (item.name, item.uuid))
1390

    
1391
  def _SetInstanceStatus(self, instance_name, status):
1392
    """Set the instance's status to a given value.
1393

1394
    """
1395
    assert status in constants.ADMINST_ALL, \
1396
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1397

    
1398
    if instance_name not in self._config_data.instances:
1399
      raise errors.ConfigurationError("Unknown instance '%s'" %
1400
                                      instance_name)
1401
    instance = self._config_data.instances[instance_name]
1402
    if instance.admin_state != status:
1403
      instance.admin_state = status
1404
      instance.serial_no += 1
1405
      instance.mtime = time.time()
1406
      self._WriteConfig()
1407

    
1408
  @locking.ssynchronized(_config_lock)
1409
  def MarkInstanceUp(self, instance_name):
1410
    """Mark the instance status to up in the config.
1411

1412
    """
1413
    self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1414

    
1415
  @locking.ssynchronized(_config_lock)
1416
  def MarkInstanceOffline(self, instance_name):
1417
    """Mark the instance status to down in the config.
1418

1419
    """
1420
    self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1421

    
1422
  @locking.ssynchronized(_config_lock)
1423
  def RemoveInstance(self, instance_name):
1424
    """Remove the instance from the configuration.
1425

1426
    """
1427
    if instance_name not in self._config_data.instances:
1428
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1429

    
1430
    # If a network port has been allocated to the instance,
1431
    # return it to the pool of free ports.
1432
    inst = self._config_data.instances[instance_name]
1433
    network_port = getattr(inst, "network_port", None)
1434
    if network_port is not None:
1435
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1436

    
1437
    instance = self._UnlockedGetInstanceInfo(instance_name)
1438

    
1439
    for nic in instance.nics:
1440
      if nic.network is not None and nic.ip is not None:
1441
        net_uuid = self._UnlockedLookupNetwork(nic.network)
1442
        if net_uuid:
1443
          # Return all IP addresses to the respective address pools
1444
          self._UnlockedCommitIp('release', net_uuid, nic.ip)
1445

    
1446
    del self._config_data.instances[instance_name]
1447
    self._config_data.cluster.serial_no += 1
1448
    self._WriteConfig()
1449

    
1450
  @locking.ssynchronized(_config_lock)
1451
  def RenameInstance(self, old_name, new_name):
1452
    """Rename an instance.
1453

1454
    This needs to be done in ConfigWriter and not by RemoveInstance
1455
    combined with AddInstance as only we can guarantee an atomic
1456
    rename.
1457

1458
    """
1459
    if old_name not in self._config_data.instances:
1460
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1461

    
1462
    # Operate on a copy to not loose instance object in case of a failure
1463
    inst = self._config_data.instances[old_name].Copy()
1464
    inst.name = new_name
1465

    
1466
    for (idx, disk) in enumerate(inst.disks):
1467
      if disk.dev_type == constants.LD_FILE:
1468
        # rename the file paths in logical and physical id
1469
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1470
        disk.logical_id = (disk.logical_id[0],
1471
                           utils.PathJoin(file_storage_dir, inst.name,
1472
                                          "disk%s" % idx))
1473
        disk.physical_id = disk.logical_id
1474

    
1475
    # Actually replace instance object
1476
    del self._config_data.instances[old_name]
1477
    self._config_data.instances[inst.name] = inst
1478

    
1479
    # Force update of ssconf files
1480
    self._config_data.cluster.serial_no += 1
1481

    
1482
    self._WriteConfig()
1483

    
1484
  @locking.ssynchronized(_config_lock)
1485
  def MarkInstanceDown(self, instance_name):
1486
    """Mark the status of an instance to down in the configuration.
1487

1488
    """
1489
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1490

    
1491
  def _UnlockedGetInstanceList(self):
1492
    """Get the list of instances.
1493

1494
    This function is for internal use, when the config lock is already held.
1495

1496
    """
1497
    return self._config_data.instances.keys()
1498

    
1499
  @locking.ssynchronized(_config_lock, shared=1)
1500
  def GetInstanceList(self):
1501
    """Get the list of instances.
1502

1503
    @return: array of instances, ex. ['instance2.example.com',
1504
        'instance1.example.com']
1505

1506
    """
1507
    return self._UnlockedGetInstanceList()
1508

    
1509
  def ExpandInstanceName(self, short_name):
1510
    """Attempt to expand an incomplete instance name.
1511

1512
    """
1513
    # Locking is done in L{ConfigWriter.GetInstanceList}
1514
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1515

    
1516
  def _UnlockedGetInstanceInfo(self, instance_name):
1517
    """Returns information about an instance.
1518

1519
    This function is for internal use, when the config lock is already held.
1520

1521
    """
1522
    if instance_name not in self._config_data.instances:
1523
      return None
1524

    
1525
    return self._config_data.instances[instance_name]
1526

    
1527
  @locking.ssynchronized(_config_lock, shared=1)
1528
  def GetInstanceInfo(self, instance_name):
1529
    """Returns information about an instance.
1530

1531
    It takes the information from the configuration file. Other information of
1532
    an instance are taken from the live systems.
1533

1534
    @param instance_name: name of the instance, e.g.
1535
        I{instance1.example.com}
1536

1537
    @rtype: L{objects.Instance}
1538
    @return: the instance object
1539

1540
    """
1541
    return self._UnlockedGetInstanceInfo(instance_name)
1542

    
1543
  @locking.ssynchronized(_config_lock, shared=1)
1544
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1545
    """Returns set of node group UUIDs for instance's nodes.
1546

1547
    @rtype: frozenset
1548

1549
    """
1550
    instance = self._UnlockedGetInstanceInfo(instance_name)
1551
    if not instance:
1552
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1553

    
1554
    if primary_only:
1555
      nodes = [instance.primary_node]
1556
    else:
1557
      nodes = instance.all_nodes
1558

    
1559
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1560
                     for node_name in nodes)
1561

    
1562
  @locking.ssynchronized(_config_lock, shared=1)
1563
  def GetMultiInstanceInfo(self, instances):
1564
    """Get the configuration of multiple instances.
1565

1566
    @param instances: list of instance names
1567
    @rtype: list
1568
    @return: list of tuples (instance, instance_info), where
1569
        instance_info is what would GetInstanceInfo return for the
1570
        node, while keeping the original order
1571

1572
    """
1573
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1574

    
1575
  @locking.ssynchronized(_config_lock, shared=1)
1576
  def GetAllInstancesInfo(self):
1577
    """Get the configuration of all instances.
1578

1579
    @rtype: dict
1580
    @return: dict of (instance, instance_info), where instance_info is what
1581
              would GetInstanceInfo return for the node
1582

1583
    """
1584
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1585
                    for instance in self._UnlockedGetInstanceList()])
1586
    return my_dict
1587

    
1588
  @locking.ssynchronized(_config_lock, shared=1)
1589
  def GetInstancesInfoByFilter(self, filter_fn):
1590
    """Get instance configuration with a filter.
1591

1592
    @type filter_fn: callable
1593
    @param filter_fn: Filter function receiving instance object as parameter,
1594
      returning boolean. Important: this function is called while the
1595
      configuration locks is held. It must not do any complex work or call
1596
      functions potentially leading to a deadlock. Ideally it doesn't call any
1597
      other functions and just compares instance attributes.
1598

1599
    """
1600
    return dict((name, inst)
1601
                for (name, inst) in self._config_data.instances.items()
1602
                if filter_fn(inst))
1603

    
1604
  @locking.ssynchronized(_config_lock)
1605
  def AddNode(self, node, ec_id):
1606
    """Add a node to the configuration.
1607

1608
    @type node: L{objects.Node}
1609
    @param node: a Node instance
1610

1611
    """
1612
    logging.info("Adding node %s to configuration", node.name)
1613

    
1614
    self._EnsureUUID(node, ec_id)
1615

    
1616
    node.serial_no = 1
1617
    node.ctime = node.mtime = time.time()
1618
    self._UnlockedAddNodeToGroup(node.name, node.group)
1619
    self._config_data.nodes[node.name] = node
1620
    self._config_data.cluster.serial_no += 1
1621
    self._WriteConfig()
1622

    
1623
  @locking.ssynchronized(_config_lock)
1624
  def RemoveNode(self, node_name):
1625
    """Remove a node from the configuration.
1626

1627
    """
1628
    logging.info("Removing node %s from configuration", node_name)
1629

    
1630
    if node_name not in self._config_data.nodes:
1631
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1632

    
1633
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1634
    del self._config_data.nodes[node_name]
1635
    self._config_data.cluster.serial_no += 1
1636
    self._WriteConfig()
1637

    
1638
  def ExpandNodeName(self, short_name):
1639
    """Attempt to expand an incomplete node name.
1640

1641
    """
1642
    # Locking is done in L{ConfigWriter.GetNodeList}
1643
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1644

    
1645
  def _UnlockedGetNodeInfo(self, node_name):
1646
    """Get the configuration of a node, as stored in the config.
1647

1648
    This function is for internal use, when the config lock is already
1649
    held.
1650

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

1653
    @rtype: L{objects.Node}
1654
    @return: the node object
1655

1656
    """
1657
    if node_name not in self._config_data.nodes:
1658
      return None
1659

    
1660
    return self._config_data.nodes[node_name]
1661

    
1662
  @locking.ssynchronized(_config_lock, shared=1)
1663
  def GetNodeInfo(self, node_name):
1664
    """Get the configuration of a node, as stored in the config.
1665

1666
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1667

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

1670
    @rtype: L{objects.Node}
1671
    @return: the node object
1672

1673
    """
1674
    return self._UnlockedGetNodeInfo(node_name)
1675

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

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

1682
    @rtype: (list, list)
1683
    @return: a tuple with two lists: the primary and the secondary instances
1684

1685
    """
1686
    pri = []
1687
    sec = []
1688
    for inst in self._config_data.instances.values():
1689
      if inst.primary_node == node_name:
1690
        pri.append(inst.name)
1691
      if node_name in inst.secondary_nodes:
1692
        sec.append(inst.name)
1693
    return (pri, sec)
1694

    
1695
  @locking.ssynchronized(_config_lock, shared=1)
1696
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1697
    """Get the instances of a node group.
1698

1699
    @param uuid: Node group UUID
1700
    @param primary_only: Whether to only consider primary nodes
1701
    @rtype: frozenset
1702
    @return: List of instance names in node group
1703

1704
    """
1705
    if primary_only:
1706
      nodes_fn = lambda inst: [inst.primary_node]
1707
    else:
1708
      nodes_fn = lambda inst: inst.all_nodes
1709

    
1710
    return frozenset(inst.name
1711
                     for inst in self._config_data.instances.values()
1712
                     for node_name in nodes_fn(inst)
1713
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1714

    
1715
  def _UnlockedGetNodeList(self):
1716
    """Return the list of nodes which are in the configuration.
1717

1718
    This function is for internal use, when the config lock is already
1719
    held.
1720

1721
    @rtype: list
1722

1723
    """
1724
    return self._config_data.nodes.keys()
1725

    
1726
  @locking.ssynchronized(_config_lock, shared=1)
1727
  def GetNodeList(self):
1728
    """Return the list of nodes which are in the configuration.
1729

1730
    """
1731
    return self._UnlockedGetNodeList()
1732

    
1733
  def _UnlockedGetOnlineNodeList(self):
1734
    """Return the list of nodes which are online.
1735

1736
    """
1737
    all_nodes = [self._UnlockedGetNodeInfo(node)
1738
                 for node in self._UnlockedGetNodeList()]
1739
    return [node.name for node in all_nodes if not node.offline]
1740

    
1741
  @locking.ssynchronized(_config_lock, shared=1)
1742
  def GetOnlineNodeList(self):
1743
    """Return the list of nodes which are online.
1744

1745
    """
1746
    return self._UnlockedGetOnlineNodeList()
1747

    
1748
  @locking.ssynchronized(_config_lock, shared=1)
1749
  def GetVmCapableNodeList(self):
1750
    """Return the list of nodes which are not vm capable.
1751

1752
    """
1753
    all_nodes = [self._UnlockedGetNodeInfo(node)
1754
                 for node in self._UnlockedGetNodeList()]
1755
    return [node.name for node in all_nodes if node.vm_capable]
1756

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

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

    
1766
  @locking.ssynchronized(_config_lock, shared=1)
1767
  def GetMultiNodeInfo(self, nodes):
1768
    """Get the configuration of multiple nodes.
1769

1770
    @param nodes: list of node names
1771
    @rtype: list
1772
    @return: list of tuples of (node, node_info), where node_info is
1773
        what would GetNodeInfo return for the node, in the original
1774
        order
1775

1776
    """
1777
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1778

    
1779
  @locking.ssynchronized(_config_lock, shared=1)
1780
  def GetAllNodesInfo(self):
1781
    """Get the configuration of all nodes.
1782

1783
    @rtype: dict
1784
    @return: dict of (node, node_info), where node_info is what
1785
              would GetNodeInfo return for the node
1786

1787
    """
1788
    return self._UnlockedGetAllNodesInfo()
1789

    
1790
  def _UnlockedGetAllNodesInfo(self):
1791
    """Gets configuration of all nodes.
1792

1793
    @note: See L{GetAllNodesInfo}
1794

1795
    """
1796
    return dict([(node, self._UnlockedGetNodeInfo(node))
1797
                 for node in self._UnlockedGetNodeList()])
1798

    
1799
  @locking.ssynchronized(_config_lock, shared=1)
1800
  def GetNodeGroupsFromNodes(self, nodes):
1801
    """Returns groups for a list of nodes.
1802

1803
    @type nodes: list of string
1804
    @param nodes: List of node names
1805
    @rtype: frozenset
1806

1807
    """
1808
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1809

    
1810
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1811
    """Get the number of current and maximum desired and possible candidates.
1812

1813
    @type exceptions: list
1814
    @param exceptions: if passed, list of nodes that should be ignored
1815
    @rtype: tuple
1816
    @return: tuple of (current, desired and possible, possible)
1817

1818
    """
1819
    mc_now = mc_should = mc_max = 0
1820
    for node in self._config_data.nodes.values():
1821
      if exceptions and node.name in exceptions:
1822
        continue
1823
      if not (node.offline or node.drained) and node.master_capable:
1824
        mc_max += 1
1825
      if node.master_candidate:
1826
        mc_now += 1
1827
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1828
    return (mc_now, mc_should, mc_max)
1829

    
1830
  @locking.ssynchronized(_config_lock, shared=1)
1831
  def GetMasterCandidateStats(self, exceptions=None):
1832
    """Get the number of current and maximum possible candidates.
1833

1834
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1835

1836
    @type exceptions: list
1837
    @param exceptions: if passed, list of nodes that should be ignored
1838
    @rtype: tuple
1839
    @return: tuple of (current, max)
1840

1841
    """
1842
    return self._UnlockedGetMasterCandidateStats(exceptions)
1843

    
1844
  @locking.ssynchronized(_config_lock)
1845
  def MaintainCandidatePool(self, exceptions):
1846
    """Try to grow the candidate pool to the desired size.
1847

1848
    @type exceptions: list
1849
    @param exceptions: if passed, list of nodes that should be ignored
1850
    @rtype: list
1851
    @return: list with the adjusted nodes (L{objects.Node} instances)
1852

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

    
1878
    return mod_list
1879

    
1880
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1881
    """Add a given node to the specified group.
1882

1883
    """
1884
    if nodegroup_uuid not in self._config_data.nodegroups:
1885
      # This can happen if a node group gets deleted between its lookup and
1886
      # when we're adding the first node to it, since we don't keep a lock in
1887
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1888
      # is not found anymore.
1889
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1890
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1891
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1892

    
1893
  def _UnlockedRemoveNodeFromGroup(self, node):
1894
    """Remove a given node from its group.
1895

1896
    """
1897
    nodegroup = node.group
1898
    if nodegroup not in self._config_data.nodegroups:
1899
      logging.warning("Warning: node '%s' has unknown node group '%s'"
1900
                      " (while being removed from it)", node.name, nodegroup)
1901
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1902
    if node.name not in nodegroup_obj.members:
1903
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
1904
                      " (while being removed from it)", node.name, nodegroup)
1905
    else:
1906
      nodegroup_obj.members.remove(node.name)
1907

    
1908
  @locking.ssynchronized(_config_lock)
1909
  def AssignGroupNodes(self, mods):
1910
    """Changes the group of a number of nodes.
1911

1912
    @type mods: list of tuples; (node name, new group UUID)
1913
    @param mods: Node membership modifications
1914

1915
    """
1916
    groups = self._config_data.nodegroups
1917
    nodes = self._config_data.nodes
1918

    
1919
    resmod = []
1920

    
1921
    # Try to resolve names/UUIDs first
1922
    for (node_name, new_group_uuid) in mods:
1923
      try:
1924
        node = nodes[node_name]
1925
      except KeyError:
1926
        raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1927

    
1928
      if node.group == new_group_uuid:
1929
        # Node is being assigned to its current group
1930
        logging.debug("Node '%s' was assigned to its current group (%s)",
1931
                      node_name, node.group)
1932
        continue
1933

    
1934
      # Try to find current group of node
1935
      try:
1936
        old_group = groups[node.group]
1937
      except KeyError:
1938
        raise errors.ConfigurationError("Unable to find old group '%s'" %
1939
                                        node.group)
1940

    
1941
      # Try to find new group for node
1942
      try:
1943
        new_group = groups[new_group_uuid]
1944
      except KeyError:
1945
        raise errors.ConfigurationError("Unable to find new group '%s'" %
1946
                                        new_group_uuid)
1947

    
1948
      assert node.name in old_group.members, \
1949
        ("Inconsistent configuration: node '%s' not listed in members for its"
1950
         " old group '%s'" % (node.name, old_group.uuid))
1951
      assert node.name not in new_group.members, \
1952
        ("Inconsistent configuration: node '%s' already listed in members for"
1953
         " its new group '%s'" % (node.name, new_group.uuid))
1954

    
1955
      resmod.append((node, old_group, new_group))
1956

    
1957
    # Apply changes
1958
    for (node, old_group, new_group) in resmod:
1959
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
1960
        "Assigning to current group is not possible"
1961

    
1962
      node.group = new_group.uuid
1963

    
1964
      # Update members of involved groups
1965
      if node.name in old_group.members:
1966
        old_group.members.remove(node.name)
1967
      if node.name not in new_group.members:
1968
        new_group.members.append(node.name)
1969

    
1970
    # Update timestamps and serials (only once per node/group object)
1971
    now = time.time()
1972
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
1973
      obj.serial_no += 1
1974
      obj.mtime = now
1975

    
1976
    # Force ssconf update
1977
    self._config_data.cluster.serial_no += 1
1978

    
1979
    self._WriteConfig()
1980

    
1981
  def _BumpSerialNo(self):
1982
    """Bump up the serial number of the config.
1983

1984
    """
1985
    self._config_data.serial_no += 1
1986
    self._config_data.mtime = time.time()
1987

    
1988
  def _AllUUIDObjects(self):
1989
    """Returns all objects with uuid attributes.
1990

1991
    """
1992
    return (self._config_data.instances.values() +
1993
            self._config_data.nodes.values() +
1994
            self._config_data.nodegroups.values() +
1995
            [self._config_data.cluster])
1996

    
1997
  def _OpenConfig(self, accept_foreign):
1998
    """Read the config data from disk.
1999

2000
    """
2001
    raw_data = utils.ReadFile(self._cfg_file)
2002

    
2003
    try:
2004
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
2005
    except Exception, err:
2006
      raise errors.ConfigurationError(err)
2007

    
2008
    # Make sure the configuration has the right version
2009
    _ValidateConfig(data)
2010

    
2011
    if (not hasattr(data, "cluster") or
2012
        not hasattr(data.cluster, "rsahostkeypub")):
2013
      raise errors.ConfigurationError("Incomplete configuration"
2014
                                      " (missing cluster.rsahostkeypub)")
2015

    
2016
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
2017
      msg = ("The configuration denotes node %s as master, while my"
2018
             " hostname is %s; opening a foreign configuration is only"
2019
             " possible in accept_foreign mode" %
2020
             (data.cluster.master_node, self._my_hostname))
2021
      raise errors.ConfigurationError(msg)
2022

    
2023
    # Upgrade configuration if needed
2024
    data.UpgradeConfig()
2025

    
2026
    self._config_data = data
2027
    # reset the last serial as -1 so that the next write will cause
2028
    # ssconf update
2029
    self._last_cluster_serial = -1
2030

    
2031
    # And finally run our (custom) config upgrade sequence
2032
    self._UpgradeConfig()
2033

    
2034
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
2035

    
2036
  def _UpgradeConfig(self):
2037
    """Run upgrade steps that cannot be done purely in the objects.
2038

2039
    This is because some data elements need uniqueness across the
2040
    whole configuration, etc.
2041

2042
    @warning: this function will call L{_WriteConfig()}, but also
2043
        L{DropECReservations} so it needs to be called only from a
2044
        "safe" place (the constructor). If one wanted to call it with
2045
        the lock held, a DropECReservationUnlocked would need to be
2046
        created first, to avoid causing deadlock.
2047

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

    
2075
  def _DistributeConfig(self, feedback_fn):
2076
    """Distribute the configuration to the other nodes.
2077

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

2081
    """
2082
    if self._offline:
2083
      return True
2084

    
2085
    bad = False
2086

    
2087
    node_list = []
2088
    addr_list = []
2089
    myhostname = self._my_hostname
2090
    # we can skip checking whether _UnlockedGetNodeInfo returns None
2091
    # since the node list comes from _UnlocketGetNodeList, and we are
2092
    # called with the lock held, so no modifications should take place
2093
    # in between
2094
    for node_name in self._UnlockedGetNodeList():
2095
      if node_name == myhostname:
2096
        continue
2097
      node_info = self._UnlockedGetNodeInfo(node_name)
2098
      if not node_info.master_candidate:
2099
        continue
2100
      node_list.append(node_info.name)
2101
      addr_list.append(node_info.primary_ip)
2102

    
2103
    # TODO: Use dedicated resolver talking to config writer for name resolution
2104
    result = \
2105
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2106
    for to_node, to_result in result.items():
2107
      msg = to_result.fail_msg
2108
      if msg:
2109
        msg = ("Copy of file %s to node %s failed: %s" %
2110
               (self._cfg_file, to_node, msg))
2111
        logging.error(msg)
2112

    
2113
        if feedback_fn:
2114
          feedback_fn(msg)
2115

    
2116
        bad = True
2117

    
2118
    return not bad
2119

    
2120
  def _WriteConfig(self, destination=None, feedback_fn=None):
2121
    """Write the configuration data to persistent storage.
2122

2123
    """
2124
    assert feedback_fn is None or callable(feedback_fn)
2125

    
2126
    # Warn on config errors, but don't abort the save - the
2127
    # configuration has already been modified, and we can't revert;
2128
    # the best we can do is to warn the user and save as is, leaving
2129
    # recovery to the user
2130
    config_errors = self._UnlockedVerifyConfig()
2131
    if config_errors:
2132
      errmsg = ("Configuration data is not consistent: %s" %
2133
                (utils.CommaJoin(config_errors)))
2134
      logging.critical(errmsg)
2135
      if feedback_fn:
2136
        feedback_fn(errmsg)
2137

    
2138
    if destination is None:
2139
      destination = self._cfg_file
2140
    self._BumpSerialNo()
2141
    txt = serializer.Dump(self._config_data.ToDict())
2142

    
2143
    getents = self._getents()
2144
    try:
2145
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2146
                               close=False, gid=getents.confd_gid, mode=0640)
2147
    except errors.LockError:
2148
      raise errors.ConfigurationError("The configuration file has been"
2149
                                      " modified since the last write, cannot"
2150
                                      " update")
2151
    try:
2152
      self._cfg_id = utils.GetFileID(fd=fd)
2153
    finally:
2154
      os.close(fd)
2155

    
2156
    self.write_count += 1
2157

    
2158
    # and redistribute the config file to master candidates
2159
    self._DistributeConfig(feedback_fn)
2160

    
2161
    # Write ssconf files on all nodes (including locally)
2162
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2163
      if not self._offline:
2164
        result = self._GetRpc(None).call_write_ssconf_files(
2165
          self._UnlockedGetOnlineNodeList(),
2166
          self._UnlockedGetSsconfValues())
2167

    
2168
        for nname, nresu in result.items():
2169
          msg = nresu.fail_msg
2170
          if msg:
2171
            errmsg = ("Error while uploading ssconf files to"
2172
                      " node %s: %s" % (nname, msg))
2173
            logging.warning(errmsg)
2174

    
2175
            if feedback_fn:
2176
              feedback_fn(errmsg)
2177

    
2178
      self._last_cluster_serial = self._config_data.cluster.serial_no
2179

    
2180
  def _UnlockedGetSsconfValues(self):
2181
    """Return the values needed by ssconf.
2182

2183
    @rtype: dict
2184
    @return: a dictionary with keys the ssconf names and values their
2185
        associated value
2186

2187
    """
2188
    fn = "\n".join
2189
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
2190
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
2191
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
2192
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2193
                    for ninfo in node_info]
2194
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2195
                    for ninfo in node_info]
2196

    
2197
    instance_data = fn(instance_names)
2198
    off_data = fn(node.name for node in node_info if node.offline)
2199
    on_data = fn(node.name for node in node_info if not node.offline)
2200
    mc_data = fn(node.name for node in node_info if node.master_candidate)
2201
    mc_ips_data = fn(node.primary_ip for node in node_info
2202
                     if node.master_candidate)
2203
    node_data = fn(node_names)
2204
    node_pri_ips_data = fn(node_pri_ips)
2205
    node_snd_ips_data = fn(node_snd_ips)
2206

    
2207
    cluster = self._config_data.cluster
2208
    cluster_tags = fn(cluster.GetTags())
2209

    
2210
    hypervisor_list = fn(cluster.enabled_hypervisors)
2211

    
2212
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2213

    
2214
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2215
                  self._config_data.nodegroups.values()]
2216
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2217
    networks = ["%s %s" % (net.uuid, net.name) for net in
2218
                self._config_data.networks.values()]
2219
    networks_data = fn(utils.NiceSort(networks))
2220

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

    
2254
  @locking.ssynchronized(_config_lock, shared=1)
2255
  def GetSsconfValues(self):
2256
    """Wrapper using lock around _UnlockedGetSsconf().
2257

2258
    """
2259
    return self._UnlockedGetSsconfValues()
2260

    
2261
  @locking.ssynchronized(_config_lock, shared=1)
2262
  def GetVGName(self):
2263
    """Return the volume group name.
2264

2265
    """
2266
    return self._config_data.cluster.volume_group_name
2267

    
2268
  @locking.ssynchronized(_config_lock)
2269
  def SetVGName(self, vg_name):
2270
    """Set the volume group name.
2271

2272
    """
2273
    self._config_data.cluster.volume_group_name = vg_name
2274
    self._config_data.cluster.serial_no += 1
2275
    self._WriteConfig()
2276

    
2277
  @locking.ssynchronized(_config_lock, shared=1)
2278
  def GetDRBDHelper(self):
2279
    """Return DRBD usermode helper.
2280

2281
    """
2282
    return self._config_data.cluster.drbd_usermode_helper
2283

    
2284
  @locking.ssynchronized(_config_lock)
2285
  def SetDRBDHelper(self, drbd_helper):
2286
    """Set DRBD usermode helper.
2287

2288
    """
2289
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2290
    self._config_data.cluster.serial_no += 1
2291
    self._WriteConfig()
2292

    
2293
  @locking.ssynchronized(_config_lock, shared=1)
2294
  def GetMACPrefix(self):
2295
    """Return the mac prefix.
2296

2297
    """
2298
    return self._config_data.cluster.mac_prefix
2299

    
2300
  @locking.ssynchronized(_config_lock, shared=1)
2301
  def GetClusterInfo(self):
2302
    """Returns information about the cluster
2303

2304
    @rtype: L{objects.Cluster}
2305
    @return: the cluster object
2306

2307
    """
2308
    return self._config_data.cluster
2309

    
2310
  @locking.ssynchronized(_config_lock, shared=1)
2311
  def HasAnyDiskOfType(self, dev_type):
2312
    """Check if in there is at disk of the given type in the configuration.
2313

2314
    """
2315
    return self._config_data.HasAnyDiskOfType(dev_type)
2316

    
2317
  @locking.ssynchronized(_config_lock)
2318
  def Update(self, target, feedback_fn, ec_id=None):
2319
    """Notify function to be called after updates.
2320

2321
    This function must be called when an object (as returned by
2322
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2323
    caller wants the modifications saved to the backing store. Note
2324
    that all modified objects will be saved, but the target argument
2325
    is the one the caller wants to ensure that it's saved.
2326

2327
    @param target: an instance of either L{objects.Cluster},
2328
        L{objects.Node} or L{objects.Instance} which is existing in
2329
        the cluster
2330
    @param feedback_fn: Callable feedback function
2331

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

    
2357
    if update_serial:
2358
      # for node updates, we need to increase the cluster serial too
2359
      self._config_data.cluster.serial_no += 1
2360
      self._config_data.cluster.mtime = now
2361

    
2362
    if isinstance(target, objects.Instance):
2363
      self._UnlockedReleaseDRBDMinors(target.name)
2364

    
2365
    if ec_id is not None:
2366
      # Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
2367
      self._UnlockedCommitTemporaryIps(ec_id)
2368

    
2369
    self._WriteConfig(feedback_fn=feedback_fn)
2370

    
2371
  @locking.ssynchronized(_config_lock)
2372
  def DropECReservations(self, ec_id):
2373
    """Drop per-execution-context reservations
2374

2375
    """
2376
    for rm in self._all_rms:
2377
      rm.DropECReservations(ec_id)
2378

    
2379
  @locking.ssynchronized(_config_lock, shared=1)
2380
  def GetAllNetworksInfo(self):
2381
    """Get the configuration of all networks
2382

2383
    """
2384
    return dict(self._config_data.networks)
2385

    
2386
  def _UnlockedGetNetworkList(self):
2387
    """Get the list of networks.
2388

2389
    This function is for internal use, when the config lock is already held.
2390

2391
    """
2392
    return self._config_data.networks.keys()
2393

    
2394
  @locking.ssynchronized(_config_lock, shared=1)
2395
  def GetNetworkList(self):
2396
    """Get the list of networks.
2397

2398
    @return: array of networks, ex. ["main", "vlan100", "200]
2399

2400
    """
2401
    return self._UnlockedGetNetworkList()
2402

    
2403
  @locking.ssynchronized(_config_lock, shared=1)
2404
  def GetNetworkNames(self):
2405
    """Get a list of network names
2406

2407
    """
2408
    names = [net.name
2409
             for net in self._config_data.networks.values()]
2410
    return names
2411

    
2412
  def _UnlockedGetNetwork(self, uuid):
2413
    """Returns information about a network.
2414

2415
    This function is for internal use, when the config lock is already held.
2416

2417
    """
2418
    if uuid not in self._config_data.networks:
2419
      return None
2420

    
2421
    return self._config_data.networks[uuid]
2422

    
2423
  @locking.ssynchronized(_config_lock, shared=1)
2424
  def GetNetwork(self, uuid):
2425
    """Returns information about a network.
2426

2427
    It takes the information from the configuration file.
2428

2429
    @param uuid: UUID of the network
2430

2431
    @rtype: L{objects.Network}
2432
    @return: the network object
2433

2434
    """
2435
    return self._UnlockedGetNetwork(uuid)
2436

    
2437
  @locking.ssynchronized(_config_lock)
2438
  def AddNetwork(self, net, ec_id, check_uuid=True):
2439
    """Add a network to the configuration.
2440

2441
    @type net: L{objects.Network}
2442
    @param net: the Network object to add
2443
    @type ec_id: string
2444
    @param ec_id: unique id for the job to use when creating a missing UUID
2445

2446
    """
2447
    self._UnlockedAddNetwork(net, ec_id, check_uuid)
2448
    self._WriteConfig()
2449

    
2450
  def _UnlockedAddNetwork(self, net, ec_id, check_uuid):
2451
    """Add a network to the configuration.
2452

2453
    """
2454
    logging.info("Adding network %s to configuration", net.name)
2455

    
2456
    if check_uuid:
2457
      self._EnsureUUID(net, ec_id)
2458

    
2459
    existing_uuid = self._UnlockedLookupNetwork(net.name)
2460
    if existing_uuid:
2461
      raise errors.OpPrereqError("Desired network name '%s' already"
2462
                                 " exists as a network (UUID: %s)" %
2463
                                 (net.name, existing_uuid),
2464
                                 errors.ECODE_EXISTS)
2465
    net.serial_no = 1
2466
    self._config_data.networks[net.uuid] = net
2467
    self._config_data.cluster.serial_no += 1
2468

    
2469
  def _UnlockedLookupNetwork(self, target):
2470
    """Lookup a network's UUID.
2471

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

2478
    """
2479
    if target in self._config_data.networks:
2480
      return target
2481
    for net in self._config_data.networks.values():
2482
      if net.name == target:
2483
        return net.uuid
2484
    return None
2485

    
2486
  @locking.ssynchronized(_config_lock, shared=1)
2487
  def LookupNetwork(self, target):
2488
    """Lookup a network's UUID.
2489

2490
    This function is just a wrapper over L{_UnlockedLookupNetwork}.
2491

2492
    @type target: string
2493
    @param target: network name or UUID
2494
    @rtype: string
2495
    @return: network UUID
2496

2497
    """
2498
    return self._UnlockedLookupNetwork(target)
2499

    
2500
  @locking.ssynchronized(_config_lock)
2501
  def RemoveNetwork(self, network_uuid):
2502
    """Remove a network from the configuration.
2503

2504
    @type network_uuid: string
2505
    @param network_uuid: the UUID of the network to remove
2506

2507
    """
2508
    logging.info("Removing network %s from configuration", network_uuid)
2509

    
2510
    if network_uuid not in self._config_data.networks:
2511
      raise errors.ConfigurationError("Unknown network '%s'" % network_uuid)
2512

    
2513
    del self._config_data.networks[network_uuid]
2514
    self._config_data.cluster.serial_no += 1
2515
    self._WriteConfig()
2516

    
2517
  def _UnlockedGetGroupNetParams(self, net, node):
2518
    """Get the netparams (mode, link) of a network.
2519

2520
    Get a network's netparams for a given node.
2521

2522
    @type net: string
2523
    @param net: network name
2524
    @type node: string
2525
    @param node: node name
2526
    @rtype: dict or None
2527
    @return: netparams
2528

2529
    """
2530
    net_uuid = self._UnlockedLookupNetwork(net)
2531
    if net_uuid is None:
2532
      return None
2533

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

    
2538
    return netparams
2539

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

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

    
2547
  @locking.ssynchronized(_config_lock, shared=1)
2548
  def CheckIPInNodeGroup(self, ip, node):
2549
    """Check for conflictig IP.
2550

2551
    @type ip: string
2552
    @param ip: ip address
2553
    @type node: string
2554
    @param node: node name
2555
    @rtype: (string, dict) or (None, None)
2556
    @return: (network name, netparams)
2557

2558
    """
2559
    if ip is None:
2560
      return (None, None)
2561
    node_info = self._UnlockedGetNodeInfo(node)
2562
    nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
2563
    for net_uuid in nodegroup_info.networks.keys():
2564
      net_info = self._UnlockedGetNetwork(net_uuid)
2565
      pool = network.AddressPool(net_info)
2566
      if pool.Contains(ip):
2567
        return (net_info.name, nodegroup_info.networks[net_uuid])
2568

    
2569
    return (None, None)