Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ c1bfc2eb

History | View | Annotate | Download (75.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

    
43
from ganeti import errors
44
from ganeti import locking
45
from ganeti import utils
46
from ganeti import constants
47
from ganeti import rpc
48
from ganeti import objects
49
from ganeti import serializer
50
from ganeti import uidpool
51
from ganeti import netutils
52
from ganeti import runtime
53

    
54

    
55
_config_lock = locking.SharedLock("ConfigWriter")
56

    
57
# job id used for resource management at config upgrade time
58
_UPGRADE_CONFIG_JID = "jid-cfg-upgrade"
59

    
60

    
61
def _ValidateConfig(data):
62
  """Verifies that a configuration objects looks valid.
63

64
  This only verifies the version of the configuration.
65

66
  @raise errors.ConfigurationError: if the version differs from what
67
      we expect
68

69
  """
70
  if data.version != constants.CONFIG_VERSION:
71
    raise errors.ConfigVersionMismatch(constants.CONFIG_VERSION, data.version)
72

    
73

    
74
class TemporaryReservationManager:
75
  """A temporary resource reservation manager.
76

77
  This is used to reserve resources in a job, before using them, making sure
78
  other jobs cannot get them in the meantime.
79

80
  """
81
  def __init__(self):
82
    self._ec_reserved = {}
83

    
84
  def Reserved(self, resource):
85
    for holder_reserved in self._ec_reserved.values():
86
      if resource in holder_reserved:
87
        return True
88
    return False
89

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

    
99
  def DropECReservations(self, ec_id):
100
    if ec_id in self._ec_reserved:
101
      del self._ec_reserved[ec_id]
102

    
103
  def GetReserved(self):
104
    all_reserved = set()
105
    for holder_reserved in self._ec_reserved.values():
106
      all_reserved.update(holder_reserved)
107
    return all_reserved
108

    
109
  def Generate(self, existing, generate_one_fn, ec_id):
110
    """Generate a new resource of this type
111

112
    """
113
    assert callable(generate_one_fn)
114

    
115
    all_elems = self.GetReserved()
116
    all_elems.update(existing)
117
    retries = 64
118
    while retries > 0:
119
      new_resource = generate_one_fn()
120
      if new_resource is not None and new_resource not in all_elems:
121
        break
122
    else:
123
      raise errors.ConfigurationError("Not able generate new resource"
124
                                      " (last tried: %s)" % new_resource)
125
    self.Reserve(ec_id, new_resource)
126
    return new_resource
127

    
128

    
129
def _MatchNameComponentIgnoreCase(short_name, names):
130
  """Wrapper around L{utils.text.MatchNameComponent}.
131

132
  """
133
  return utils.MatchNameComponent(short_name, names, case_sensitive=False)
134

    
135

    
136
def _CheckInstanceDiskIvNames(disks):
137
  """Checks if instance's disks' C{iv_name} attributes are in order.
138

139
  @type disks: list of L{objects.Disk}
140
  @param disks: List of disks
141
  @rtype: list of tuples; (int, string, string)
142
  @return: List of wrongly named disks, each tuple contains disk index,
143
    expected and actual name
144

145
  """
146
  result = []
147

    
148
  for (idx, disk) in enumerate(disks):
149
    exp_iv_name = "disk/%s" % idx
150
    if disk.iv_name != exp_iv_name:
151
      result.append((idx, exp_iv_name, disk.iv_name))
152

    
153
  return result
154

    
155

    
156
class ConfigWriter:
157
  """The interface to the cluster configuration.
158

159
  @ivar _temporary_lvs: reservation manager for temporary LVs
160
  @ivar _all_rms: a list of all temporary reservation managers
161

162
  """
163
  def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts,
164
               accept_foreign=False):
165
    self.write_count = 0
166
    self._lock = _config_lock
167
    self._config_data = None
168
    self._offline = offline
169
    if cfg_file is None:
170
      self._cfg_file = constants.CLUSTER_CONF_FILE
171
    else:
172
      self._cfg_file = cfg_file
173
    self._getents = _getents
174
    self._temporary_ids = TemporaryReservationManager()
175
    self._temporary_drbds = {}
176
    self._temporary_macs = TemporaryReservationManager()
177
    self._temporary_secrets = TemporaryReservationManager()
178
    self._temporary_lvs = TemporaryReservationManager()
179
    self._all_rms = [self._temporary_ids, self._temporary_macs,
180
                     self._temporary_secrets, self._temporary_lvs]
181
    # Note: in order to prevent errors when resolving our name in
182
    # _DistributeConfig, we compute it here once and reuse it; it's
183
    # better to raise an error before starting to modify the config
184
    # file than after it was modified
185
    self._my_hostname = netutils.Hostname.GetSysName()
186
    self._last_cluster_serial = -1
187
    self._cfg_id = None
188
    self._context = None
189
    self._OpenConfig(accept_foreign)
190

    
191
  def _GetRpc(self, address_list):
192
    """Returns RPC runner for configuration.
193

194
    """
195
    return rpc.ConfigRunner(self._context, address_list)
196

    
197
  def SetContext(self, context):
198
    """Sets Ganeti context.
199

200
    """
201
    self._context = context
202

    
203
  # this method needs to be static, so that we can call it on the class
204
  @staticmethod
205
  def IsCluster():
206
    """Check if the cluster is configured.
207

208
    """
209
    return os.path.exists(constants.CLUSTER_CONF_FILE)
210

    
211
  def _GenerateOneMAC(self):
212
    """Generate one mac address
213

214
    """
215
    prefix = self._config_data.cluster.mac_prefix
216
    byte1 = random.randrange(0, 256)
217
    byte2 = random.randrange(0, 256)
218
    byte3 = random.randrange(0, 256)
219
    mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
220
    return mac
221

    
222
  @locking.ssynchronized(_config_lock, shared=1)
223
  def GetNdParams(self, node):
224
    """Get the node params populated with cluster defaults.
225

226
    @type node: L{objects.Node}
227
    @param node: The node we want to know the params for
228
    @return: A dict with the filled in node params
229

230
    """
231
    nodegroup = self._UnlockedGetNodeGroup(node.group)
232
    return self._config_data.cluster.FillND(node, nodegroup)
233

    
234
  @locking.ssynchronized(_config_lock, shared=1)
235
  def GetInstanceDiskParams(self, instance):
236
    """Get the disk params populated with inherit chain.
237

238
    @type instance: L{objects.Instance}
239
    @param instance: The instance we want to know the params for
240
    @return: A dict with the filled in disk params
241

242
    """
243
    node = self._UnlockedGetNodeInfo(instance.primary_node)
244
    nodegroup = self._UnlockedGetNodeGroup(node.group)
245
    return self._UnlockedGetGroupDiskParams(nodegroup)
246

    
247
  @locking.ssynchronized(_config_lock, shared=1)
248
  def GetGroupDiskParams(self, group):
249
    """Get the disk params populated with inherit chain.
250

251
    @type group: L{objects.NodeGroup}
252
    @param group: The group we want to know the params for
253
    @return: A dict with the filled in disk params
254

255
    """
256
    return self._UnlockedGetGroupDiskParams(group)
257

    
258
  def _UnlockedGetGroupDiskParams(self, group):
259
    """Get the disk params populated with inherit chain down to node-group.
260

261
    @type group: L{objects.NodeGroup}
262
    @param group: The group we want to know the params for
263
    @return: A dict with the filled in disk params
264

265
    """
266
    return self._config_data.cluster.SimpleFillDP(group.diskparams)
267

    
268
  @locking.ssynchronized(_config_lock, shared=1)
269
  def GenerateMAC(self, ec_id):
270
    """Generate a MAC for an instance.
271

272
    This should check the current instances for duplicates.
273

274
    """
275
    existing = self._AllMACs()
276
    return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
277

    
278
  @locking.ssynchronized(_config_lock, shared=1)
279
  def ReserveMAC(self, mac, ec_id):
280
    """Reserve a MAC for an instance.
281

282
    This only checks instances managed by this cluster, it does not
283
    check for potential collisions elsewhere.
284

285
    """
286
    all_macs = self._AllMACs()
287
    if mac in all_macs:
288
      raise errors.ReservationError("mac already in use")
289
    else:
290
      self._temporary_macs.Reserve(ec_id, mac)
291

    
292
  @locking.ssynchronized(_config_lock)
293
  def GetPCIInfo(self, instance, dev_type):
294

    
295
    if not instance.hotplug_info:
296
      return None, None
297
    idx = getattr(instance.hotplug_info, dev_type)
298
    setattr(instance.hotplug_info, dev_type, idx+1)
299
    pci = instance.hotplug_info.pci_pool.pop()
300
    self._WriteConfig()
301

    
302
    return idx, pci
303

    
304
  @locking.ssynchronized(_config_lock)
305
  def UpdatePCIInfo(self, instance, pci_slot):
306

    
307
    if instance.hotplug_info:
308
      logging.info("Releasing PCI slot %d for instance %s",
309
                    pci_slot, instance.name)
310
      instance.hotplug_info.pci_pool.append(pci_slot)
311
      self._WriteConfig()
312

    
313
  @locking.ssynchronized(_config_lock, shared=1)
314
  def ReserveLV(self, lv_name, ec_id):
315
    """Reserve an VG/LV pair for an instance.
316

317
    @type lv_name: string
318
    @param lv_name: the logical volume name to reserve
319

320
    """
321
    all_lvs = self._AllLVs()
322
    if lv_name in all_lvs:
323
      raise errors.ReservationError("LV already in use")
324
    else:
325
      self._temporary_lvs.Reserve(ec_id, lv_name)
326

    
327
  @locking.ssynchronized(_config_lock, shared=1)
328
  def GenerateDRBDSecret(self, ec_id):
329
    """Generate a DRBD secret.
330

331
    This checks the current disks for duplicates.
332

333
    """
334
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
335
                                            utils.GenerateSecret,
336
                                            ec_id)
337

    
338
  def _AllLVs(self):
339
    """Compute the list of all LVs.
340

341
    """
342
    lvnames = set()
343
    for instance in self._config_data.instances.values():
344
      node_data = instance.MapLVsByNode()
345
      for lv_list in node_data.values():
346
        lvnames.update(lv_list)
347
    return lvnames
348

    
349
  def _AllIDs(self, include_temporary):
350
    """Compute the list of all UUIDs and names we have.
351

352
    @type include_temporary: boolean
353
    @param include_temporary: whether to include the _temporary_ids set
354
    @rtype: set
355
    @return: a set of IDs
356

357
    """
358
    existing = set()
359
    if include_temporary:
360
      existing.update(self._temporary_ids.GetReserved())
361
    existing.update(self._AllLVs())
362
    existing.update(self._config_data.instances.keys())
363
    existing.update(self._config_data.nodes.keys())
364
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
365
    return existing
366

    
367
  def _GenerateUniqueID(self, ec_id):
368
    """Generate an unique UUID.
369

370
    This checks the current node, instances and disk names for
371
    duplicates.
372

373
    @rtype: string
374
    @return: the unique id
375

376
    """
377
    existing = self._AllIDs(include_temporary=False)
378
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
379

    
380
  @locking.ssynchronized(_config_lock, shared=1)
381
  def GenerateUniqueID(self, ec_id):
382
    """Generate an unique ID.
383

384
    This is just a wrapper over the unlocked version.
385

386
    @type ec_id: string
387
    @param ec_id: unique id for the job to reserve the id to
388

389
    """
390
    return self._GenerateUniqueID(ec_id)
391

    
392
  def _AllMACs(self):
393
    """Return all MACs present in the config.
394

395
    @rtype: list
396
    @return: the list of all MACs
397

398
    """
399
    result = []
400
    for instance in self._config_data.instances.values():
401
      for nic in instance.nics:
402
        result.append(nic.mac)
403

    
404
    return result
405

    
406
  def _AllDRBDSecrets(self):
407
    """Return all DRBD secrets present in the config.
408

409
    @rtype: list
410
    @return: the list of all DRBD secrets
411

412
    """
413
    def helper(disk, result):
414
      """Recursively gather secrets from this disk."""
415
      if disk.dev_type == constants.DT_DRBD8:
416
        result.append(disk.logical_id[5])
417
      if disk.children:
418
        for child in disk.children:
419
          helper(child, result)
420

    
421
    result = []
422
    for instance in self._config_data.instances.values():
423
      for disk in instance.disks:
424
        helper(disk, result)
425

    
426
    return result
427

    
428
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
429
    """Compute duplicate disk IDs
430

431
    @type disk: L{objects.Disk}
432
    @param disk: the disk at which to start searching
433
    @type l_ids: list
434
    @param l_ids: list of current logical ids
435
    @type p_ids: list
436
    @param p_ids: list of current physical ids
437
    @rtype: list
438
    @return: a list of error messages
439

440
    """
441
    result = []
442
    if disk.logical_id is not None:
443
      if disk.logical_id in l_ids:
444
        result.append("duplicate logical id %s" % str(disk.logical_id))
445
      else:
446
        l_ids.append(disk.logical_id)
447
    if disk.physical_id is not None:
448
      if disk.physical_id in p_ids:
449
        result.append("duplicate physical id %s" % str(disk.physical_id))
450
      else:
451
        p_ids.append(disk.physical_id)
452

    
453
    if disk.children:
454
      for child in disk.children:
455
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
456
    return result
457

    
458
  def _UnlockedVerifyConfig(self):
459
    """Verify function.
460

461
    @rtype: list
462
    @return: a list of error messages; a non-empty list signifies
463
        configuration errors
464

465
    """
466
    # pylint: disable=R0914
467
    result = []
468
    seen_macs = []
469
    ports = {}
470
    data = self._config_data
471
    cluster = data.cluster
472
    seen_lids = []
473
    seen_pids = []
474

    
475
    # global cluster checks
476
    if not cluster.enabled_hypervisors:
477
      result.append("enabled hypervisors list doesn't have any entries")
478
    invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
479
    if invalid_hvs:
480
      result.append("enabled hypervisors contains invalid entries: %s" %
481
                    invalid_hvs)
482
    missing_hvp = (set(cluster.enabled_hypervisors) -
483
                   set(cluster.hvparams.keys()))
484
    if missing_hvp:
485
      result.append("hypervisor parameters missing for the enabled"
486
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
487

    
488
    if cluster.master_node not in data.nodes:
489
      result.append("cluster has invalid primary node '%s'" %
490
                    cluster.master_node)
491

    
492
    def _helper(owner, attr, value, template):
493
      try:
494
        utils.ForceDictType(value, template)
495
      except errors.GenericError, err:
496
        result.append("%s has invalid %s: %s" % (owner, attr, err))
497

    
498
    def _helper_nic(owner, params):
499
      try:
500
        objects.NIC.CheckParameterSyntax(params)
501
      except errors.ConfigurationError, err:
502
        result.append("%s has invalid nicparams: %s" % (owner, err))
503

    
504
    def _helper_ipolicy(owner, params, check_std):
505
      try:
506
        objects.InstancePolicy.CheckParameterSyntax(params, check_std)
507
      except errors.ConfigurationError, err:
508
        result.append("%s has invalid instance policy: %s" % (owner, err))
509

    
510
    def _helper_ispecs(owner, params):
511
      for key, value in params.items():
512
        if key in constants.IPOLICY_ISPECS:
513
          fullkey = "ipolicy/" + key
514
          _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
515
        else:
516
          # FIXME: assuming list type
517
          if key in constants.IPOLICY_PARAMETERS:
518
            exp_type = float
519
          else:
520
            exp_type = list
521
          if not isinstance(value, exp_type):
522
            result.append("%s has invalid instance policy: for %s,"
523
                          " expecting %s, got %s" %
524
                          (owner, key, exp_type.__name__, type(value)))
525

    
526
    # check cluster parameters
527
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
528
            constants.BES_PARAMETER_TYPES)
529
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
530
            constants.NICS_PARAMETER_TYPES)
531
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
532
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
533
            constants.NDS_PARAMETER_TYPES)
534
    _helper_ipolicy("cluster", cluster.SimpleFillIPolicy({}), True)
535
    _helper_ispecs("cluster", cluster.SimpleFillIPolicy({}))
536

    
537
    # per-instance checks
538
    for instance_name in data.instances:
539
      instance = data.instances[instance_name]
540
      if instance.name != instance_name:
541
        result.append("instance '%s' is indexed by wrong name '%s'" %
542
                      (instance.name, instance_name))
543
      if instance.primary_node not in data.nodes:
544
        result.append("instance '%s' has invalid primary node '%s'" %
545
                      (instance_name, instance.primary_node))
546
      for snode in instance.secondary_nodes:
547
        if snode not in data.nodes:
548
          result.append("instance '%s' has invalid secondary node '%s'" %
549
                        (instance_name, snode))
550
      for idx, nic in enumerate(instance.nics):
551
        if nic.mac in seen_macs:
552
          result.append("instance '%s' has NIC %d mac %s duplicate" %
553
                        (instance_name, idx, nic.mac))
554
        else:
555
          seen_macs.append(nic.mac)
556
        if nic.nicparams:
557
          filled = cluster.SimpleFillNIC(nic.nicparams)
558
          owner = "instance %s nic %d" % (instance.name, idx)
559
          _helper(owner, "nicparams",
560
                  filled, constants.NICS_PARAMETER_TYPES)
561
          _helper_nic(owner, filled)
562

    
563
      # parameter checks
564
      if instance.beparams:
565
        _helper("instance %s" % instance.name, "beparams",
566
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
567

    
568
      # gather the drbd ports for duplicate checks
569
      for (idx, dsk) in enumerate(instance.disks):
570
        if dsk.dev_type in constants.LDS_DRBD:
571
          tcp_port = dsk.logical_id[2]
572
          if tcp_port not in ports:
573
            ports[tcp_port] = []
574
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
575
      # gather network port reservation
576
      net_port = getattr(instance, "network_port", None)
577
      if net_port is not None:
578
        if net_port not in ports:
579
          ports[net_port] = []
580
        ports[net_port].append((instance.name, "network port"))
581

    
582
      # instance disk verify
583
      for idx, disk in enumerate(instance.disks):
584
        result.extend(["instance '%s' disk %d error: %s" %
585
                       (instance.name, idx, msg) for msg in disk.Verify()])
586
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
587

    
588
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
589
      if wrong_names:
590
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
591
                         (idx, exp_name, actual_name))
592
                        for (idx, exp_name, actual_name) in wrong_names)
593

    
594
        result.append("Instance '%s' has wrongly named disks: %s" %
595
                      (instance.name, tmp))
596

    
597
    # cluster-wide pool of free ports
598
    for free_port in cluster.tcpudp_port_pool:
599
      if free_port not in ports:
600
        ports[free_port] = []
601
      ports[free_port].append(("cluster", "port marked as free"))
602

    
603
    # compute tcp/udp duplicate ports
604
    keys = ports.keys()
605
    keys.sort()
606
    for pnum in keys:
607
      pdata = ports[pnum]
608
      if len(pdata) > 1:
609
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
610
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
611

    
612
    # highest used tcp port check
613
    if keys:
614
      if keys[-1] > cluster.highest_used_port:
615
        result.append("Highest used port mismatch, saved %s, computed %s" %
616
                      (cluster.highest_used_port, keys[-1]))
617

    
618
    if not data.nodes[cluster.master_node].master_candidate:
619
      result.append("Master node is not a master candidate")
620

    
621
    # master candidate checks
622
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
623
    if mc_now < mc_max:
624
      result.append("Not enough master candidates: actual %d, target %d" %
625
                    (mc_now, mc_max))
626

    
627
    # node checks
628
    for node_name, node in data.nodes.items():
629
      if node.name != node_name:
630
        result.append("Node '%s' is indexed by wrong name '%s'" %
631
                      (node.name, node_name))
632
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
633
        result.append("Node %s state is invalid: master_candidate=%s,"
634
                      " drain=%s, offline=%s" %
635
                      (node.name, node.master_candidate, node.drained,
636
                       node.offline))
637
      if node.group not in data.nodegroups:
638
        result.append("Node '%s' has invalid group '%s'" %
639
                      (node.name, node.group))
640
      else:
641
        _helper("node %s" % node.name, "ndparams",
642
                cluster.FillND(node, data.nodegroups[node.group]),
643
                constants.NDS_PARAMETER_TYPES)
644

    
645
    # nodegroups checks
646
    nodegroups_names = set()
647
    for nodegroup_uuid in data.nodegroups:
648
      nodegroup = data.nodegroups[nodegroup_uuid]
649
      if nodegroup.uuid != nodegroup_uuid:
650
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
651
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
652
      if utils.UUID_RE.match(nodegroup.name.lower()):
653
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
654
                      (nodegroup.name, nodegroup.uuid))
655
      if nodegroup.name in nodegroups_names:
656
        result.append("duplicate node group name '%s'" % nodegroup.name)
657
      else:
658
        nodegroups_names.add(nodegroup.name)
659
      group_name = "group %s" % nodegroup.name
660
      _helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy),
661
                      False)
662
      _helper_ispecs(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy))
663
      if nodegroup.ndparams:
664
        _helper(group_name, "ndparams",
665
                cluster.SimpleFillND(nodegroup.ndparams),
666
                constants.NDS_PARAMETER_TYPES)
667

    
668
    # drbd minors check
669
    _, duplicates = self._UnlockedComputeDRBDMap()
670
    for node, minor, instance_a, instance_b in duplicates:
671
      result.append("DRBD minor %d on node %s is assigned twice to instances"
672
                    " %s and %s" % (minor, node, instance_a, instance_b))
673

    
674
    # IP checks
675
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
676
    ips = {}
677

    
678
    def _AddIpAddress(ip, name):
679
      ips.setdefault(ip, []).append(name)
680

    
681
    _AddIpAddress(cluster.master_ip, "cluster_ip")
682

    
683
    for node in data.nodes.values():
684
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
685
      if node.secondary_ip != node.primary_ip:
686
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
687

    
688
    for instance in data.instances.values():
689
      for idx, nic in enumerate(instance.nics):
690
        if nic.ip is None:
691
          continue
692

    
693
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
694
        nic_mode = nicparams[constants.NIC_MODE]
695
        nic_link = nicparams[constants.NIC_LINK]
696

    
697
        if nic_mode == constants.NIC_MODE_BRIDGED:
698
          link = "bridge:%s" % nic_link
699
        elif nic_mode == constants.NIC_MODE_ROUTED:
700
          link = "route:%s" % nic_link
701
        else:
702
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
703

    
704
        _AddIpAddress("%s/%s" % (link, nic.ip),
705
                      "instance:%s/nic:%d" % (instance.name, idx))
706

    
707
    for ip, owners in ips.items():
708
      if len(owners) > 1:
709
        result.append("IP address %s is used by multiple owners: %s" %
710
                      (ip, utils.CommaJoin(owners)))
711

    
712
    return result
713

    
714
  @locking.ssynchronized(_config_lock, shared=1)
715
  def VerifyConfig(self):
716
    """Verify function.
717

718
    This is just a wrapper over L{_UnlockedVerifyConfig}.
719

720
    @rtype: list
721
    @return: a list of error messages; a non-empty list signifies
722
        configuration errors
723

724
    """
725
    return self._UnlockedVerifyConfig()
726

    
727
  def _UnlockedSetDiskID(self, disk, node_name):
728
    """Convert the unique ID to the ID needed on the target nodes.
729

730
    This is used only for drbd, which needs ip/port configuration.
731

732
    The routine descends down and updates its children also, because
733
    this helps when the only the top device is passed to the remote
734
    node.
735

736
    This function is for internal use, when the config lock is already held.
737

738
    """
739
    if disk.children:
740
      for child in disk.children:
741
        self._UnlockedSetDiskID(child, node_name)
742

    
743
    if disk.logical_id is None and disk.physical_id is not None:
744
      return
745
    if disk.dev_type == constants.LD_DRBD8:
746
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
747
      if node_name not in (pnode, snode):
748
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
749
                                        node_name)
750
      pnode_info = self._UnlockedGetNodeInfo(pnode)
751
      snode_info = self._UnlockedGetNodeInfo(snode)
752
      if pnode_info is None or snode_info is None:
753
        raise errors.ConfigurationError("Can't find primary or secondary node"
754
                                        " for %s" % str(disk))
755
      p_data = (pnode_info.secondary_ip, port)
756
      s_data = (snode_info.secondary_ip, port)
757
      if pnode == node_name:
758
        disk.physical_id = p_data + s_data + (pminor, secret)
759
      else: # it must be secondary, we tested above
760
        disk.physical_id = s_data + p_data + (sminor, secret)
761
    else:
762
      disk.physical_id = disk.logical_id
763
    return
764

    
765
  @locking.ssynchronized(_config_lock)
766
  def SetDiskID(self, disk, node_name):
767
    """Convert the unique ID to the ID needed on the target nodes.
768

769
    This is used only for drbd, which needs ip/port configuration.
770

771
    The routine descends down and updates its children also, because
772
    this helps when the only the top device is passed to the remote
773
    node.
774

775
    """
776
    return self._UnlockedSetDiskID(disk, node_name)
777

    
778
  @locking.ssynchronized(_config_lock)
779
  def AddTcpUdpPort(self, port):
780
    """Adds a new port to the available port pool.
781

782
    @warning: this method does not "flush" the configuration (via
783
        L{_WriteConfig}); callers should do that themselves once the
784
        configuration is stable
785

786
    """
787
    if not isinstance(port, int):
788
      raise errors.ProgrammerError("Invalid type passed for port")
789

    
790
    self._config_data.cluster.tcpudp_port_pool.add(port)
791

    
792
  @locking.ssynchronized(_config_lock, shared=1)
793
  def GetPortList(self):
794
    """Returns a copy of the current port list.
795

796
    """
797
    return self._config_data.cluster.tcpudp_port_pool.copy()
798

    
799
  @locking.ssynchronized(_config_lock)
800
  def AllocatePort(self):
801
    """Allocate a port.
802

803
    The port will be taken from the available port pool or from the
804
    default port range (and in this case we increase
805
    highest_used_port).
806

807
    """
808
    # If there are TCP/IP ports configured, we use them first.
809
    if self._config_data.cluster.tcpudp_port_pool:
810
      port = self._config_data.cluster.tcpudp_port_pool.pop()
811
    else:
812
      port = self._config_data.cluster.highest_used_port + 1
813
      if port >= constants.LAST_DRBD_PORT:
814
        raise errors.ConfigurationError("The highest used port is greater"
815
                                        " than %s. Aborting." %
816
                                        constants.LAST_DRBD_PORT)
817
      self._config_data.cluster.highest_used_port = port
818

    
819
    self._WriteConfig()
820
    return port
821

    
822
  def _UnlockedComputeDRBDMap(self):
823
    """Compute the used DRBD minor/nodes.
824

825
    @rtype: (dict, list)
826
    @return: dictionary of node_name: dict of minor: instance_name;
827
        the returned dict will have all the nodes in it (even if with
828
        an empty list), and a list of duplicates; if the duplicates
829
        list is not empty, the configuration is corrupted and its caller
830
        should raise an exception
831

832
    """
833
    def _AppendUsedPorts(instance_name, disk, used):
834
      duplicates = []
835
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
836
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
837
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
838
          assert node in used, ("Node '%s' of instance '%s' not found"
839
                                " in node list" % (node, instance_name))
840
          if port in used[node]:
841
            duplicates.append((node, port, instance_name, used[node][port]))
842
          else:
843
            used[node][port] = instance_name
844
      if disk.children:
845
        for child in disk.children:
846
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
847
      return duplicates
848

    
849
    duplicates = []
850
    my_dict = dict((node, {}) for node in self._config_data.nodes)
851
    for instance in self._config_data.instances.itervalues():
852
      for disk in instance.disks:
853
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
854
    for (node, minor), instance in self._temporary_drbds.iteritems():
855
      if minor in my_dict[node] and my_dict[node][minor] != instance:
856
        duplicates.append((node, minor, instance, my_dict[node][minor]))
857
      else:
858
        my_dict[node][minor] = instance
859
    return my_dict, duplicates
860

    
861
  @locking.ssynchronized(_config_lock)
862
  def ComputeDRBDMap(self):
863
    """Compute the used DRBD minor/nodes.
864

865
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
866

867
    @return: dictionary of node_name: dict of minor: instance_name;
868
        the returned dict will have all the nodes in it (even if with
869
        an empty list).
870

871
    """
872
    d_map, duplicates = self._UnlockedComputeDRBDMap()
873
    if duplicates:
874
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
875
                                      str(duplicates))
876
    return d_map
877

    
878
  @locking.ssynchronized(_config_lock)
879
  def AllocateDRBDMinor(self, nodes, instance):
880
    """Allocate a drbd minor.
881

882
    The free minor will be automatically computed from the existing
883
    devices. A node can be given multiple times in order to allocate
884
    multiple minors. The result is the list of minors, in the same
885
    order as the passed nodes.
886

887
    @type instance: string
888
    @param instance: the instance for which we allocate minors
889

890
    """
891
    assert isinstance(instance, basestring), \
892
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
893

    
894
    d_map, duplicates = self._UnlockedComputeDRBDMap()
895
    if duplicates:
896
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
897
                                      str(duplicates))
898
    result = []
899
    for nname in nodes:
900
      ndata = d_map[nname]
901
      if not ndata:
902
        # no minors used, we can start at 0
903
        result.append(0)
904
        ndata[0] = instance
905
        self._temporary_drbds[(nname, 0)] = instance
906
        continue
907
      keys = ndata.keys()
908
      keys.sort()
909
      ffree = utils.FirstFree(keys)
910
      if ffree is None:
911
        # return the next minor
912
        # TODO: implement high-limit check
913
        minor = keys[-1] + 1
914
      else:
915
        minor = ffree
916
      # double-check minor against current instances
917
      assert minor not in d_map[nname], \
918
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
919
              " already allocated to instance %s" %
920
              (minor, nname, d_map[nname][minor]))
921
      ndata[minor] = instance
922
      # double-check minor against reservation
923
      r_key = (nname, minor)
924
      assert r_key not in self._temporary_drbds, \
925
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
926
              " reserved for instance %s" %
927
              (minor, nname, self._temporary_drbds[r_key]))
928
      self._temporary_drbds[r_key] = instance
929
      result.append(minor)
930
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
931
                  nodes, result)
932
    return result
933

    
934
  def _UnlockedReleaseDRBDMinors(self, instance):
935
    """Release temporary drbd minors allocated for a given instance.
936

937
    @type instance: string
938
    @param instance: the instance for which temporary minors should be
939
                     released
940

941
    """
942
    assert isinstance(instance, basestring), \
943
           "Invalid argument passed to ReleaseDRBDMinors"
944
    for key, name in self._temporary_drbds.items():
945
      if name == instance:
946
        del self._temporary_drbds[key]
947

    
948
  @locking.ssynchronized(_config_lock)
949
  def ReleaseDRBDMinors(self, instance):
950
    """Release temporary drbd minors allocated for a given instance.
951

952
    This should be called on the error paths, on the success paths
953
    it's automatically called by the ConfigWriter add and update
954
    functions.
955

956
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
957

958
    @type instance: string
959
    @param instance: the instance for which temporary minors should be
960
                     released
961

962
    """
963
    self._UnlockedReleaseDRBDMinors(instance)
964

    
965
  @locking.ssynchronized(_config_lock, shared=1)
966
  def GetConfigVersion(self):
967
    """Get the configuration version.
968

969
    @return: Config version
970

971
    """
972
    return self._config_data.version
973

    
974
  @locking.ssynchronized(_config_lock, shared=1)
975
  def GetClusterName(self):
976
    """Get cluster name.
977

978
    @return: Cluster name
979

980
    """
981
    return self._config_data.cluster.cluster_name
982

    
983
  @locking.ssynchronized(_config_lock, shared=1)
984
  def GetMasterNode(self):
985
    """Get the hostname of the master node for this cluster.
986

987
    @return: Master hostname
988

989
    """
990
    return self._config_data.cluster.master_node
991

    
992
  @locking.ssynchronized(_config_lock, shared=1)
993
  def GetMasterIP(self):
994
    """Get the IP of the master node for this cluster.
995

996
    @return: Master IP
997

998
    """
999
    return self._config_data.cluster.master_ip
1000

    
1001
  @locking.ssynchronized(_config_lock, shared=1)
1002
  def GetMasterNetdev(self):
1003
    """Get the master network device for this cluster.
1004

1005
    """
1006
    return self._config_data.cluster.master_netdev
1007

    
1008
  @locking.ssynchronized(_config_lock, shared=1)
1009
  def GetMasterNetmask(self):
1010
    """Get the netmask of the master node for this cluster.
1011

1012
    """
1013
    return self._config_data.cluster.master_netmask
1014

    
1015
  @locking.ssynchronized(_config_lock, shared=1)
1016
  def GetUseExternalMipScript(self):
1017
    """Get flag representing whether to use the external master IP setup script.
1018

1019
    """
1020
    return self._config_data.cluster.use_external_mip_script
1021

    
1022
  @locking.ssynchronized(_config_lock, shared=1)
1023
  def GetFileStorageDir(self):
1024
    """Get the file storage dir for this cluster.
1025

1026
    """
1027
    return self._config_data.cluster.file_storage_dir
1028

    
1029
  @locking.ssynchronized(_config_lock, shared=1)
1030
  def GetSharedFileStorageDir(self):
1031
    """Get the shared file storage dir for this cluster.
1032

1033
    """
1034
    return self._config_data.cluster.shared_file_storage_dir
1035

    
1036
  @locking.ssynchronized(_config_lock, shared=1)
1037
  def GetHypervisorType(self):
1038
    """Get the hypervisor type for this cluster.
1039

1040
    """
1041
    return self._config_data.cluster.enabled_hypervisors[0]
1042

    
1043
  @locking.ssynchronized(_config_lock, shared=1)
1044
  def GetHostKey(self):
1045
    """Return the rsa hostkey from the config.
1046

1047
    @rtype: string
1048
    @return: the rsa hostkey
1049

1050
    """
1051
    return self._config_data.cluster.rsahostkeypub
1052

    
1053
  @locking.ssynchronized(_config_lock, shared=1)
1054
  def GetDefaultIAllocator(self):
1055
    """Get the default instance allocator for this cluster.
1056

1057
    """
1058
    return self._config_data.cluster.default_iallocator
1059

    
1060
  @locking.ssynchronized(_config_lock, shared=1)
1061
  def GetPrimaryIPFamily(self):
1062
    """Get cluster primary ip family.
1063

1064
    @return: primary ip family
1065

1066
    """
1067
    return self._config_data.cluster.primary_ip_family
1068

    
1069
  @locking.ssynchronized(_config_lock, shared=1)
1070
  def GetMasterNetworkParameters(self):
1071
    """Get network parameters of the master node.
1072

1073
    @rtype: L{object.MasterNetworkParameters}
1074
    @return: network parameters of the master node
1075

1076
    """
1077
    cluster = self._config_data.cluster
1078
    result = objects.MasterNetworkParameters(name=cluster.master_node,
1079
      ip=cluster.master_ip,
1080
      netmask=cluster.master_netmask,
1081
      netdev=cluster.master_netdev,
1082
      ip_family=cluster.primary_ip_family)
1083

    
1084
    return result
1085

    
1086
  @locking.ssynchronized(_config_lock)
1087
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1088
    """Add a node group to the configuration.
1089

1090
    This method calls group.UpgradeConfig() to fill any missing attributes
1091
    according to their default values.
1092

1093
    @type group: L{objects.NodeGroup}
1094
    @param group: the NodeGroup object to add
1095
    @type ec_id: string
1096
    @param ec_id: unique id for the job to use when creating a missing UUID
1097
    @type check_uuid: bool
1098
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1099
                       it does, ensure that it does not exist in the
1100
                       configuration already
1101

1102
    """
1103
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1104
    self._WriteConfig()
1105

    
1106
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1107
    """Add a node group to the configuration.
1108

1109
    """
1110
    logging.info("Adding node group %s to configuration", group.name)
1111

    
1112
    # Some code might need to add a node group with a pre-populated UUID
1113
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1114
    # the "does this UUID" exist already check.
1115
    if check_uuid:
1116
      self._EnsureUUID(group, ec_id)
1117

    
1118
    try:
1119
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1120
    except errors.OpPrereqError:
1121
      pass
1122
    else:
1123
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1124
                                 " node group (UUID: %s)" %
1125
                                 (group.name, existing_uuid),
1126
                                 errors.ECODE_EXISTS)
1127

    
1128
    group.serial_no = 1
1129
    group.ctime = group.mtime = time.time()
1130
    group.UpgradeConfig()
1131

    
1132
    self._config_data.nodegroups[group.uuid] = group
1133
    self._config_data.cluster.serial_no += 1
1134

    
1135
  @locking.ssynchronized(_config_lock)
1136
  def RemoveNodeGroup(self, group_uuid):
1137
    """Remove a node group from the configuration.
1138

1139
    @type group_uuid: string
1140
    @param group_uuid: the UUID of the node group to remove
1141

1142
    """
1143
    logging.info("Removing node group %s from configuration", group_uuid)
1144

    
1145
    if group_uuid not in self._config_data.nodegroups:
1146
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1147

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

    
1151
    del self._config_data.nodegroups[group_uuid]
1152
    self._config_data.cluster.serial_no += 1
1153
    self._WriteConfig()
1154

    
1155
  def _UnlockedLookupNodeGroup(self, target):
1156
    """Lookup a node group's UUID.
1157

1158
    @type target: string or None
1159
    @param target: group name or UUID or None to look for the default
1160
    @rtype: string
1161
    @return: nodegroup UUID
1162
    @raises errors.OpPrereqError: when the target group cannot be found
1163

1164
    """
1165
    if target is None:
1166
      if len(self._config_data.nodegroups) != 1:
1167
        raise errors.OpPrereqError("More than one node group exists. Target"
1168
                                   " group must be specified explicitly.")
1169
      else:
1170
        return self._config_data.nodegroups.keys()[0]
1171
    if target in self._config_data.nodegroups:
1172
      return target
1173
    for nodegroup in self._config_data.nodegroups.values():
1174
      if nodegroup.name == target:
1175
        return nodegroup.uuid
1176
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1177
                               errors.ECODE_NOENT)
1178

    
1179
  @locking.ssynchronized(_config_lock, shared=1)
1180
  def LookupNodeGroup(self, target):
1181
    """Lookup a node group's UUID.
1182

1183
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1184

1185
    @type target: string or None
1186
    @param target: group name or UUID or None to look for the default
1187
    @rtype: string
1188
    @return: nodegroup UUID
1189

1190
    """
1191
    return self._UnlockedLookupNodeGroup(target)
1192

    
1193
  def _UnlockedGetNodeGroup(self, uuid):
1194
    """Lookup a node group.
1195

1196
    @type uuid: string
1197
    @param uuid: group UUID
1198
    @rtype: L{objects.NodeGroup} or None
1199
    @return: nodegroup object, or None if not found
1200

1201
    """
1202
    if uuid not in self._config_data.nodegroups:
1203
      return None
1204

    
1205
    return self._config_data.nodegroups[uuid]
1206

    
1207
  @locking.ssynchronized(_config_lock, shared=1)
1208
  def GetNodeGroup(self, uuid):
1209
    """Lookup a node group.
1210

1211
    @type uuid: string
1212
    @param uuid: group UUID
1213
    @rtype: L{objects.NodeGroup} or None
1214
    @return: nodegroup object, or None if not found
1215

1216
    """
1217
    return self._UnlockedGetNodeGroup(uuid)
1218

    
1219
  @locking.ssynchronized(_config_lock, shared=1)
1220
  def GetAllNodeGroupsInfo(self):
1221
    """Get the configuration of all node groups.
1222

1223
    """
1224
    return dict(self._config_data.nodegroups)
1225

    
1226
  @locking.ssynchronized(_config_lock, shared=1)
1227
  def GetNodeGroupList(self):
1228
    """Get a list of node groups.
1229

1230
    """
1231
    return self._config_data.nodegroups.keys()
1232

    
1233
  @locking.ssynchronized(_config_lock, shared=1)
1234
  def GetNodeGroupMembersByNodes(self, nodes):
1235
    """Get nodes which are member in the same nodegroups as the given nodes.
1236

1237
    """
1238
    ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1239
    return frozenset(member_name
1240
                     for node_name in nodes
1241
                     for member_name in
1242
                       self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1243

    
1244
  @locking.ssynchronized(_config_lock, shared=1)
1245
  def GetMultiNodeGroupInfo(self, group_uuids):
1246
    """Get the configuration of multiple node groups.
1247

1248
    @param group_uuids: List of node group UUIDs
1249
    @rtype: list
1250
    @return: List of tuples of (group_uuid, group_info)
1251

1252
    """
1253
    return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids]
1254

    
1255
  @locking.ssynchronized(_config_lock)
1256
  def AddInstance(self, instance, ec_id):
1257
    """Add an instance to the config.
1258

1259
    This should be used after creating a new instance.
1260

1261
    @type instance: L{objects.Instance}
1262
    @param instance: the instance object
1263

1264
    """
1265
    if not isinstance(instance, objects.Instance):
1266
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1267

    
1268
    if instance.disk_template != constants.DT_DISKLESS:
1269
      all_lvs = instance.MapLVsByNode()
1270
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1271

    
1272
    all_macs = self._AllMACs()
1273
    for nic in instance.nics:
1274
      if nic.mac in all_macs:
1275
        raise errors.ConfigurationError("Cannot add instance %s:"
1276
                                        " MAC address '%s' already in use." %
1277
                                        (instance.name, nic.mac))
1278

    
1279
    self._EnsureUUID(instance, ec_id)
1280

    
1281
    instance.serial_no = 1
1282
    instance.ctime = instance.mtime = time.time()
1283
    self._config_data.instances[instance.name] = instance
1284
    self._config_data.cluster.serial_no += 1
1285
    self._UnlockedReleaseDRBDMinors(instance.name)
1286
    self._WriteConfig()
1287

    
1288
  def _EnsureUUID(self, item, ec_id):
1289
    """Ensures a given object has a valid UUID.
1290

1291
    @param item: the instance or node to be checked
1292
    @param ec_id: the execution context id for the uuid reservation
1293

1294
    """
1295
    if not item.uuid:
1296
      item.uuid = self._GenerateUniqueID(ec_id)
1297
    elif item.uuid in self._AllIDs(include_temporary=True):
1298
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1299
                                      " in use" % (item.name, item.uuid))
1300

    
1301
  def _SetInstanceStatus(self, instance_name, status):
1302
    """Set the instance's status to a given value.
1303

1304
    """
1305
    assert status in constants.ADMINST_ALL, \
1306
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1307

    
1308
    if instance_name not in self._config_data.instances:
1309
      raise errors.ConfigurationError("Unknown instance '%s'" %
1310
                                      instance_name)
1311
    instance = self._config_data.instances[instance_name]
1312
    if instance.admin_state != status:
1313
      instance.admin_state = status
1314
      instance.serial_no += 1
1315
      instance.mtime = time.time()
1316
      self._WriteConfig()
1317

    
1318
  @locking.ssynchronized(_config_lock)
1319
  def MarkInstanceUp(self, instance_name):
1320
    """Mark the instance status to up in the config.
1321

1322
    """
1323
    self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1324

    
1325
  @locking.ssynchronized(_config_lock)
1326
  def MarkInstanceOffline(self, instance_name):
1327
    """Mark the instance status to down in the config.
1328

1329
    """
1330
    self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1331

    
1332
  @locking.ssynchronized(_config_lock)
1333
  def RemoveInstance(self, instance_name):
1334
    """Remove the instance from the configuration.
1335

1336
    """
1337
    if instance_name not in self._config_data.instances:
1338
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1339

    
1340
    # If a network port has been allocated to the instance,
1341
    # return it to the pool of free ports.
1342
    inst = self._config_data.instances[instance_name]
1343
    network_port = getattr(inst, "network_port", None)
1344
    if network_port is not None:
1345
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1346

    
1347
    del self._config_data.instances[instance_name]
1348
    self._config_data.cluster.serial_no += 1
1349
    self._WriteConfig()
1350

    
1351
  @locking.ssynchronized(_config_lock)
1352
  def RenameInstance(self, old_name, new_name):
1353
    """Rename an instance.
1354

1355
    This needs to be done in ConfigWriter and not by RemoveInstance
1356
    combined with AddInstance as only we can guarantee an atomic
1357
    rename.
1358

1359
    """
1360
    if old_name not in self._config_data.instances:
1361
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1362

    
1363
    # Operate on a copy to not loose instance object in case of a failure
1364
    inst = self._config_data.instances[old_name].Copy()
1365
    inst.name = new_name
1366

    
1367
    for (idx, disk) in enumerate(inst.disks):
1368
      if disk.dev_type == constants.LD_FILE:
1369
        # rename the file paths in logical and physical id
1370
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1371
        disk.logical_id = (disk.logical_id[0],
1372
                           utils.PathJoin(file_storage_dir, inst.name,
1373
                                          "disk%s" % idx))
1374
        disk.physical_id = disk.logical_id
1375

    
1376
    # Actually replace instance object
1377
    del self._config_data.instances[old_name]
1378
    self._config_data.instances[inst.name] = inst
1379

    
1380
    # Force update of ssconf files
1381
    self._config_data.cluster.serial_no += 1
1382

    
1383
    self._WriteConfig()
1384

    
1385
  @locking.ssynchronized(_config_lock)
1386
  def MarkInstanceDown(self, instance_name):
1387
    """Mark the status of an instance to down in the configuration.
1388

1389
    """
1390
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1391

    
1392
  def _UnlockedGetInstanceList(self):
1393
    """Get the list of instances.
1394

1395
    This function is for internal use, when the config lock is already held.
1396

1397
    """
1398
    return self._config_data.instances.keys()
1399

    
1400
  @locking.ssynchronized(_config_lock, shared=1)
1401
  def GetInstanceList(self):
1402
    """Get the list of instances.
1403

1404
    @return: array of instances, ex. ['instance2.example.com',
1405
        'instance1.example.com']
1406

1407
    """
1408
    return self._UnlockedGetInstanceList()
1409

    
1410
  def ExpandInstanceName(self, short_name):
1411
    """Attempt to expand an incomplete instance name.
1412

1413
    """
1414
    # Locking is done in L{ConfigWriter.GetInstanceList}
1415
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1416

    
1417
  def _UnlockedGetInstanceInfo(self, instance_name):
1418
    """Returns information about an instance.
1419

1420
    This function is for internal use, when the config lock is already held.
1421

1422
    """
1423
    if instance_name not in self._config_data.instances:
1424
      return None
1425

    
1426
    return self._config_data.instances[instance_name]
1427

    
1428
  @locking.ssynchronized(_config_lock, shared=1)
1429
  def GetInstanceInfo(self, instance_name):
1430
    """Returns information about an instance.
1431

1432
    It takes the information from the configuration file. Other information of
1433
    an instance are taken from the live systems.
1434

1435
    @param instance_name: name of the instance, e.g.
1436
        I{instance1.example.com}
1437

1438
    @rtype: L{objects.Instance}
1439
    @return: the instance object
1440

1441
    """
1442
    return self._UnlockedGetInstanceInfo(instance_name)
1443

    
1444
  @locking.ssynchronized(_config_lock, shared=1)
1445
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1446
    """Returns set of node group UUIDs for instance's nodes.
1447

1448
    @rtype: frozenset
1449

1450
    """
1451
    instance = self._UnlockedGetInstanceInfo(instance_name)
1452
    if not instance:
1453
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1454

    
1455
    if primary_only:
1456
      nodes = [instance.primary_node]
1457
    else:
1458
      nodes = instance.all_nodes
1459

    
1460
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1461
                     for node_name in nodes)
1462

    
1463
  @locking.ssynchronized(_config_lock, shared=1)
1464
  def GetMultiInstanceInfo(self, instances):
1465
    """Get the configuration of multiple instances.
1466

1467
    @param instances: list of instance names
1468
    @rtype: list
1469
    @return: list of tuples (instance, instance_info), where
1470
        instance_info is what would GetInstanceInfo return for the
1471
        node, while keeping the original order
1472

1473
    """
1474
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1475

    
1476
  @locking.ssynchronized(_config_lock, shared=1)
1477
  def GetAllInstancesInfo(self):
1478
    """Get the configuration of all instances.
1479

1480
    @rtype: dict
1481
    @return: dict of (instance, instance_info), where instance_info is what
1482
              would GetInstanceInfo return for the node
1483

1484
    """
1485
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1486
                    for instance in self._UnlockedGetInstanceList()])
1487
    return my_dict
1488

    
1489
  @locking.ssynchronized(_config_lock, shared=1)
1490
  def GetInstancesInfoByFilter(self, filter_fn):
1491
    """Get instance configuration with a filter.
1492

1493
    @type filter_fn: callable
1494
    @param filter_fn: Filter function receiving instance object as parameter,
1495
      returning boolean. Important: this function is called while the
1496
      configuration locks is held. It must not do any complex work or call
1497
      functions potentially leading to a deadlock. Ideally it doesn't call any
1498
      other functions and just compares instance attributes.
1499

1500
    """
1501
    return dict((name, inst)
1502
                for (name, inst) in self._config_data.instances.items()
1503
                if filter_fn(inst))
1504

    
1505
  @locking.ssynchronized(_config_lock)
1506
  def AddNode(self, node, ec_id):
1507
    """Add a node to the configuration.
1508

1509
    @type node: L{objects.Node}
1510
    @param node: a Node instance
1511

1512
    """
1513
    logging.info("Adding node %s to configuration", node.name)
1514

    
1515
    self._EnsureUUID(node, ec_id)
1516

    
1517
    node.serial_no = 1
1518
    node.ctime = node.mtime = time.time()
1519
    self._UnlockedAddNodeToGroup(node.name, node.group)
1520
    self._config_data.nodes[node.name] = node
1521
    self._config_data.cluster.serial_no += 1
1522
    self._WriteConfig()
1523

    
1524
  @locking.ssynchronized(_config_lock)
1525
  def RemoveNode(self, node_name):
1526
    """Remove a node from the configuration.
1527

1528
    """
1529
    logging.info("Removing node %s from configuration", node_name)
1530

    
1531
    if node_name not in self._config_data.nodes:
1532
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1533

    
1534
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1535
    del self._config_data.nodes[node_name]
1536
    self._config_data.cluster.serial_no += 1
1537
    self._WriteConfig()
1538

    
1539
  def ExpandNodeName(self, short_name):
1540
    """Attempt to expand an incomplete node name.
1541

1542
    """
1543
    # Locking is done in L{ConfigWriter.GetNodeList}
1544
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1545

    
1546
  def _UnlockedGetNodeInfo(self, node_name):
1547
    """Get the configuration of a node, as stored in the config.
1548

1549
    This function is for internal use, when the config lock is already
1550
    held.
1551

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

1554
    @rtype: L{objects.Node}
1555
    @return: the node object
1556

1557
    """
1558
    if node_name not in self._config_data.nodes:
1559
      return None
1560

    
1561
    return self._config_data.nodes[node_name]
1562

    
1563
  @locking.ssynchronized(_config_lock, shared=1)
1564
  def GetNodeInfo(self, node_name):
1565
    """Get the configuration of a node, as stored in the config.
1566

1567
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1568

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

1571
    @rtype: L{objects.Node}
1572
    @return: the node object
1573

1574
    """
1575
    return self._UnlockedGetNodeInfo(node_name)
1576

    
1577
  @locking.ssynchronized(_config_lock, shared=1)
1578
  def GetNodeInstances(self, node_name):
1579
    """Get the instances of a node, as stored in the config.
1580

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

1583
    @rtype: (list, list)
1584
    @return: a tuple with two lists: the primary and the secondary instances
1585

1586
    """
1587
    pri = []
1588
    sec = []
1589
    for inst in self._config_data.instances.values():
1590
      if inst.primary_node == node_name:
1591
        pri.append(inst.name)
1592
      if node_name in inst.secondary_nodes:
1593
        sec.append(inst.name)
1594
    return (pri, sec)
1595

    
1596
  @locking.ssynchronized(_config_lock, shared=1)
1597
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1598
    """Get the instances of a node group.
1599

1600
    @param uuid: Node group UUID
1601
    @param primary_only: Whether to only consider primary nodes
1602
    @rtype: frozenset
1603
    @return: List of instance names in node group
1604

1605
    """
1606
    if primary_only:
1607
      nodes_fn = lambda inst: [inst.primary_node]
1608
    else:
1609
      nodes_fn = lambda inst: inst.all_nodes
1610

    
1611
    return frozenset(inst.name
1612
                     for inst in self._config_data.instances.values()
1613
                     for node_name in nodes_fn(inst)
1614
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1615

    
1616
  def _UnlockedGetNodeList(self):
1617
    """Return the list of nodes which are in the configuration.
1618

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

1622
    @rtype: list
1623

1624
    """
1625
    return self._config_data.nodes.keys()
1626

    
1627
  @locking.ssynchronized(_config_lock, shared=1)
1628
  def GetNodeList(self):
1629
    """Return the list of nodes which are in the configuration.
1630

1631
    """
1632
    return self._UnlockedGetNodeList()
1633

    
1634
  def _UnlockedGetOnlineNodeList(self):
1635
    """Return the list of nodes which are online.
1636

1637
    """
1638
    all_nodes = [self._UnlockedGetNodeInfo(node)
1639
                 for node in self._UnlockedGetNodeList()]
1640
    return [node.name for node in all_nodes if not node.offline]
1641

    
1642
  @locking.ssynchronized(_config_lock, shared=1)
1643
  def GetOnlineNodeList(self):
1644
    """Return the list of nodes which are online.
1645

1646
    """
1647
    return self._UnlockedGetOnlineNodeList()
1648

    
1649
  @locking.ssynchronized(_config_lock, shared=1)
1650
  def GetVmCapableNodeList(self):
1651
    """Return the list of nodes which are not vm capable.
1652

1653
    """
1654
    all_nodes = [self._UnlockedGetNodeInfo(node)
1655
                 for node in self._UnlockedGetNodeList()]
1656
    return [node.name for node in all_nodes if node.vm_capable]
1657

    
1658
  @locking.ssynchronized(_config_lock, shared=1)
1659
  def GetNonVmCapableNodeList(self):
1660
    """Return the list of nodes which are not vm capable.
1661

1662
    """
1663
    all_nodes = [self._UnlockedGetNodeInfo(node)
1664
                 for node in self._UnlockedGetNodeList()]
1665
    return [node.name for node in all_nodes if not node.vm_capable]
1666

    
1667
  @locking.ssynchronized(_config_lock, shared=1)
1668
  def GetMultiNodeInfo(self, nodes):
1669
    """Get the configuration of multiple nodes.
1670

1671
    @param nodes: list of node names
1672
    @rtype: list
1673
    @return: list of tuples of (node, node_info), where node_info is
1674
        what would GetNodeInfo return for the node, in the original
1675
        order
1676

1677
    """
1678
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1679

    
1680
  @locking.ssynchronized(_config_lock, shared=1)
1681
  def GetAllNodesInfo(self):
1682
    """Get the configuration of all nodes.
1683

1684
    @rtype: dict
1685
    @return: dict of (node, node_info), where node_info is what
1686
              would GetNodeInfo return for the node
1687

1688
    """
1689
    return self._UnlockedGetAllNodesInfo()
1690

    
1691
  def _UnlockedGetAllNodesInfo(self):
1692
    """Gets configuration of all nodes.
1693

1694
    @note: See L{GetAllNodesInfo}
1695

1696
    """
1697
    return dict([(node, self._UnlockedGetNodeInfo(node))
1698
                 for node in self._UnlockedGetNodeList()])
1699

    
1700
  @locking.ssynchronized(_config_lock, shared=1)
1701
  def GetNodeGroupsFromNodes(self, nodes):
1702
    """Returns groups for a list of nodes.
1703

1704
    @type nodes: list of string
1705
    @param nodes: List of node names
1706
    @rtype: frozenset
1707

1708
    """
1709
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1710

    
1711
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1712
    """Get the number of current and maximum desired and possible candidates.
1713

1714
    @type exceptions: list
1715
    @param exceptions: if passed, list of nodes that should be ignored
1716
    @rtype: tuple
1717
    @return: tuple of (current, desired and possible, possible)
1718

1719
    """
1720
    mc_now = mc_should = mc_max = 0
1721
    for node in self._config_data.nodes.values():
1722
      if exceptions and node.name in exceptions:
1723
        continue
1724
      if not (node.offline or node.drained) and node.master_capable:
1725
        mc_max += 1
1726
      if node.master_candidate:
1727
        mc_now += 1
1728
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1729
    return (mc_now, mc_should, mc_max)
1730

    
1731
  @locking.ssynchronized(_config_lock, shared=1)
1732
  def GetMasterCandidateStats(self, exceptions=None):
1733
    """Get the number of current and maximum possible candidates.
1734

1735
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1736

1737
    @type exceptions: list
1738
    @param exceptions: if passed, list of nodes that should be ignored
1739
    @rtype: tuple
1740
    @return: tuple of (current, max)
1741

1742
    """
1743
    return self._UnlockedGetMasterCandidateStats(exceptions)
1744

    
1745
  @locking.ssynchronized(_config_lock)
1746
  def MaintainCandidatePool(self, exceptions):
1747
    """Try to grow the candidate pool to the desired size.
1748

1749
    @type exceptions: list
1750
    @param exceptions: if passed, list of nodes that should be ignored
1751
    @rtype: list
1752
    @return: list with the adjusted nodes (L{objects.Node} instances)
1753

1754
    """
1755
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1756
    mod_list = []
1757
    if mc_now < mc_max:
1758
      node_list = self._config_data.nodes.keys()
1759
      random.shuffle(node_list)
1760
      for name in node_list:
1761
        if mc_now >= mc_max:
1762
          break
1763
        node = self._config_data.nodes[name]
1764
        if (node.master_candidate or node.offline or node.drained or
1765
            node.name in exceptions or not node.master_capable):
1766
          continue
1767
        mod_list.append(node)
1768
        node.master_candidate = True
1769
        node.serial_no += 1
1770
        mc_now += 1
1771
      if mc_now != mc_max:
1772
        # this should not happen
1773
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1774
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1775
      if mod_list:
1776
        self._config_data.cluster.serial_no += 1
1777
        self._WriteConfig()
1778

    
1779
    return mod_list
1780

    
1781
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1782
    """Add a given node to the specified group.
1783

1784
    """
1785
    if nodegroup_uuid not in self._config_data.nodegroups:
1786
      # This can happen if a node group gets deleted between its lookup and
1787
      # when we're adding the first node to it, since we don't keep a lock in
1788
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1789
      # is not found anymore.
1790
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1791
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1792
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1793

    
1794
  def _UnlockedRemoveNodeFromGroup(self, node):
1795
    """Remove a given node from its group.
1796

1797
    """
1798
    nodegroup = node.group
1799
    if nodegroup not in self._config_data.nodegroups:
1800
      logging.warning("Warning: node '%s' has unknown node group '%s'"
1801
                      " (while being removed from it)", node.name, nodegroup)
1802
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1803
    if node.name not in nodegroup_obj.members:
1804
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
1805
                      " (while being removed from it)", node.name, nodegroup)
1806
    else:
1807
      nodegroup_obj.members.remove(node.name)
1808

    
1809
  @locking.ssynchronized(_config_lock)
1810
  def AssignGroupNodes(self, mods):
1811
    """Changes the group of a number of nodes.
1812

1813
    @type mods: list of tuples; (node name, new group UUID)
1814
    @param mods: Node membership modifications
1815

1816
    """
1817
    groups = self._config_data.nodegroups
1818
    nodes = self._config_data.nodes
1819

    
1820
    resmod = []
1821

    
1822
    # Try to resolve names/UUIDs first
1823
    for (node_name, new_group_uuid) in mods:
1824
      try:
1825
        node = nodes[node_name]
1826
      except KeyError:
1827
        raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1828

    
1829
      if node.group == new_group_uuid:
1830
        # Node is being assigned to its current group
1831
        logging.debug("Node '%s' was assigned to its current group (%s)",
1832
                      node_name, node.group)
1833
        continue
1834

    
1835
      # Try to find current group of node
1836
      try:
1837
        old_group = groups[node.group]
1838
      except KeyError:
1839
        raise errors.ConfigurationError("Unable to find old group '%s'" %
1840
                                        node.group)
1841

    
1842
      # Try to find new group for node
1843
      try:
1844
        new_group = groups[new_group_uuid]
1845
      except KeyError:
1846
        raise errors.ConfigurationError("Unable to find new group '%s'" %
1847
                                        new_group_uuid)
1848

    
1849
      assert node.name in old_group.members, \
1850
        ("Inconsistent configuration: node '%s' not listed in members for its"
1851
         " old group '%s'" % (node.name, old_group.uuid))
1852
      assert node.name not in new_group.members, \
1853
        ("Inconsistent configuration: node '%s' already listed in members for"
1854
         " its new group '%s'" % (node.name, new_group.uuid))
1855

    
1856
      resmod.append((node, old_group, new_group))
1857

    
1858
    # Apply changes
1859
    for (node, old_group, new_group) in resmod:
1860
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
1861
        "Assigning to current group is not possible"
1862

    
1863
      node.group = new_group.uuid
1864

    
1865
      # Update members of involved groups
1866
      if node.name in old_group.members:
1867
        old_group.members.remove(node.name)
1868
      if node.name not in new_group.members:
1869
        new_group.members.append(node.name)
1870

    
1871
    # Update timestamps and serials (only once per node/group object)
1872
    now = time.time()
1873
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
1874
      obj.serial_no += 1
1875
      obj.mtime = now
1876

    
1877
    # Force ssconf update
1878
    self._config_data.cluster.serial_no += 1
1879

    
1880
    self._WriteConfig()
1881

    
1882
  def _BumpSerialNo(self):
1883
    """Bump up the serial number of the config.
1884

1885
    """
1886
    self._config_data.serial_no += 1
1887
    self._config_data.mtime = time.time()
1888

    
1889
  def _AllUUIDObjects(self):
1890
    """Returns all objects with uuid attributes.
1891

1892
    """
1893
    return (self._config_data.instances.values() +
1894
            self._config_data.nodes.values() +
1895
            self._config_data.nodegroups.values() +
1896
            [self._config_data.cluster])
1897

    
1898
  def _OpenConfig(self, accept_foreign):
1899
    """Read the config data from disk.
1900

1901
    """
1902
    raw_data = utils.ReadFile(self._cfg_file)
1903

    
1904
    try:
1905
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1906
    except Exception, err:
1907
      raise errors.ConfigurationError(err)
1908

    
1909
    # Make sure the configuration has the right version
1910
    _ValidateConfig(data)
1911

    
1912
    if (not hasattr(data, "cluster") or
1913
        not hasattr(data.cluster, "rsahostkeypub")):
1914
      raise errors.ConfigurationError("Incomplete configuration"
1915
                                      " (missing cluster.rsahostkeypub)")
1916

    
1917
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
1918
      msg = ("The configuration denotes node %s as master, while my"
1919
             " hostname is %s; opening a foreign configuration is only"
1920
             " possible in accept_foreign mode" %
1921
             (data.cluster.master_node, self._my_hostname))
1922
      raise errors.ConfigurationError(msg)
1923

    
1924
    # Upgrade configuration if needed
1925
    data.UpgradeConfig()
1926

    
1927
    self._config_data = data
1928
    # reset the last serial as -1 so that the next write will cause
1929
    # ssconf update
1930
    self._last_cluster_serial = -1
1931

    
1932
    # And finally run our (custom) config upgrade sequence
1933
    self._UpgradeConfig()
1934

    
1935
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
1936

    
1937
  def _UpgradeConfig(self):
1938
    """Run upgrade steps that cannot be done purely in the objects.
1939

1940
    This is because some data elements need uniqueness across the
1941
    whole configuration, etc.
1942

1943
    @warning: this function will call L{_WriteConfig()}, but also
1944
        L{DropECReservations} so it needs to be called only from a
1945
        "safe" place (the constructor). If one wanted to call it with
1946
        the lock held, a DropECReservationUnlocked would need to be
1947
        created first, to avoid causing deadlock.
1948

1949
    """
1950
    modified = False
1951
    for item in self._AllUUIDObjects():
1952
      if item.uuid is None:
1953
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1954
        modified = True
1955
    if not self._config_data.nodegroups:
1956
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
1957
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
1958
                                            members=[])
1959
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
1960
      modified = True
1961
    for node in self._config_data.nodes.values():
1962
      if not node.group:
1963
        node.group = self.LookupNodeGroup(None)
1964
        modified = True
1965
      # This is technically *not* an upgrade, but needs to be done both when
1966
      # nodegroups are being added, and upon normally loading the config,
1967
      # because the members list of a node group is discarded upon
1968
      # serializing/deserializing the object.
1969
      self._UnlockedAddNodeToGroup(node.name, node.group)
1970
    if modified:
1971
      self._WriteConfig()
1972
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
1973
      # only called at config init time, without the lock held
1974
      self.DropECReservations(_UPGRADE_CONFIG_JID)
1975

    
1976
  def _DistributeConfig(self, feedback_fn):
1977
    """Distribute the configuration to the other nodes.
1978

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

1982
    """
1983
    if self._offline:
1984
      return True
1985

    
1986
    bad = False
1987

    
1988
    node_list = []
1989
    addr_list = []
1990
    myhostname = self._my_hostname
1991
    # we can skip checking whether _UnlockedGetNodeInfo returns None
1992
    # since the node list comes from _UnlocketGetNodeList, and we are
1993
    # called with the lock held, so no modifications should take place
1994
    # in between
1995
    for node_name in self._UnlockedGetNodeList():
1996
      if node_name == myhostname:
1997
        continue
1998
      node_info = self._UnlockedGetNodeInfo(node_name)
1999
      if not node_info.master_candidate:
2000
        continue
2001
      node_list.append(node_info.name)
2002
      addr_list.append(node_info.primary_ip)
2003

    
2004
    # TODO: Use dedicated resolver talking to config writer for name resolution
2005
    result = \
2006
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
2007
    for to_node, to_result in result.items():
2008
      msg = to_result.fail_msg
2009
      if msg:
2010
        msg = ("Copy of file %s to node %s failed: %s" %
2011
               (self._cfg_file, to_node, msg))
2012
        logging.error(msg)
2013

    
2014
        if feedback_fn:
2015
          feedback_fn(msg)
2016

    
2017
        bad = True
2018

    
2019
    return not bad
2020

    
2021
  def _WriteConfig(self, destination=None, feedback_fn=None):
2022
    """Write the configuration data to persistent storage.
2023

2024
    """
2025
    assert feedback_fn is None or callable(feedback_fn)
2026

    
2027
    # Warn on config errors, but don't abort the save - the
2028
    # configuration has already been modified, and we can't revert;
2029
    # the best we can do is to warn the user and save as is, leaving
2030
    # recovery to the user
2031
    config_errors = self._UnlockedVerifyConfig()
2032
    if config_errors:
2033
      errmsg = ("Configuration data is not consistent: %s" %
2034
                (utils.CommaJoin(config_errors)))
2035
      logging.critical(errmsg)
2036
      if feedback_fn:
2037
        feedback_fn(errmsg)
2038

    
2039
    if destination is None:
2040
      destination = self._cfg_file
2041
    self._BumpSerialNo()
2042
    txt = serializer.Dump(self._config_data.ToDict())
2043

    
2044
    getents = self._getents()
2045
    try:
2046
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
2047
                               close=False, gid=getents.confd_gid, mode=0640)
2048
    except errors.LockError:
2049
      raise errors.ConfigurationError("The configuration file has been"
2050
                                      " modified since the last write, cannot"
2051
                                      " update")
2052
    try:
2053
      self._cfg_id = utils.GetFileID(fd=fd)
2054
    finally:
2055
      os.close(fd)
2056

    
2057
    self.write_count += 1
2058

    
2059
    # and redistribute the config file to master candidates
2060
    self._DistributeConfig(feedback_fn)
2061

    
2062
    # Write ssconf files on all nodes (including locally)
2063
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
2064
      if not self._offline:
2065
        result = self._GetRpc(None).call_write_ssconf_files(
2066
          self._UnlockedGetOnlineNodeList(),
2067
          self._UnlockedGetSsconfValues())
2068

    
2069
        for nname, nresu in result.items():
2070
          msg = nresu.fail_msg
2071
          if msg:
2072
            errmsg = ("Error while uploading ssconf files to"
2073
                      " node %s: %s" % (nname, msg))
2074
            logging.warning(errmsg)
2075

    
2076
            if feedback_fn:
2077
              feedback_fn(errmsg)
2078

    
2079
      self._last_cluster_serial = self._config_data.cluster.serial_no
2080

    
2081
  def _UnlockedGetSsconfValues(self):
2082
    """Return the values needed by ssconf.
2083

2084
    @rtype: dict
2085
    @return: a dictionary with keys the ssconf names and values their
2086
        associated value
2087

2088
    """
2089
    fn = "\n".join
2090
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
2091
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
2092
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
2093
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2094
                    for ninfo in node_info]
2095
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2096
                    for ninfo in node_info]
2097

    
2098
    instance_data = fn(instance_names)
2099
    off_data = fn(node.name for node in node_info if node.offline)
2100
    on_data = fn(node.name for node in node_info if not node.offline)
2101
    mc_data = fn(node.name for node in node_info if node.master_candidate)
2102
    mc_ips_data = fn(node.primary_ip for node in node_info
2103
                     if node.master_candidate)
2104
    node_data = fn(node_names)
2105
    node_pri_ips_data = fn(node_pri_ips)
2106
    node_snd_ips_data = fn(node_snd_ips)
2107

    
2108
    cluster = self._config_data.cluster
2109
    cluster_tags = fn(cluster.GetTags())
2110

    
2111
    hypervisor_list = fn(cluster.enabled_hypervisors)
2112

    
2113
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2114

    
2115
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2116
                  self._config_data.nodegroups.values()]
2117
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2118

    
2119
    ssconf_values = {
2120
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
2121
      constants.SS_CLUSTER_TAGS: cluster_tags,
2122
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2123
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2124
      constants.SS_MASTER_CANDIDATES: mc_data,
2125
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2126
      constants.SS_MASTER_IP: cluster.master_ip,
2127
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
2128
      constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2129
      constants.SS_MASTER_NODE: cluster.master_node,
2130
      constants.SS_NODE_LIST: node_data,
2131
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2132
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2133
      constants.SS_OFFLINE_NODES: off_data,
2134
      constants.SS_ONLINE_NODES: on_data,
2135
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2136
      constants.SS_INSTANCE_LIST: instance_data,
2137
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2138
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
2139
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2140
      constants.SS_UID_POOL: uid_pool,
2141
      constants.SS_NODEGROUPS: nodegroups_data,
2142
      }
2143
    bad_values = [(k, v) for k, v in ssconf_values.items()
2144
                  if not isinstance(v, (str, basestring))]
2145
    if bad_values:
2146
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2147
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2148
                                      " values: %s" % err)
2149
    return ssconf_values
2150

    
2151
  @locking.ssynchronized(_config_lock, shared=1)
2152
  def GetSsconfValues(self):
2153
    """Wrapper using lock around _UnlockedGetSsconf().
2154

2155
    """
2156
    return self._UnlockedGetSsconfValues()
2157

    
2158
  @locking.ssynchronized(_config_lock, shared=1)
2159
  def GetVGName(self):
2160
    """Return the volume group name.
2161

2162
    """
2163
    return self._config_data.cluster.volume_group_name
2164

    
2165
  @locking.ssynchronized(_config_lock)
2166
  def SetVGName(self, vg_name):
2167
    """Set the volume group name.
2168

2169
    """
2170
    self._config_data.cluster.volume_group_name = vg_name
2171
    self._config_data.cluster.serial_no += 1
2172
    self._WriteConfig()
2173

    
2174
  @locking.ssynchronized(_config_lock, shared=1)
2175
  def GetDRBDHelper(self):
2176
    """Return DRBD usermode helper.
2177

2178
    """
2179
    return self._config_data.cluster.drbd_usermode_helper
2180

    
2181
  @locking.ssynchronized(_config_lock)
2182
  def SetDRBDHelper(self, drbd_helper):
2183
    """Set DRBD usermode helper.
2184

2185
    """
2186
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2187
    self._config_data.cluster.serial_no += 1
2188
    self._WriteConfig()
2189

    
2190
  @locking.ssynchronized(_config_lock, shared=1)
2191
  def GetMACPrefix(self):
2192
    """Return the mac prefix.
2193

2194
    """
2195
    return self._config_data.cluster.mac_prefix
2196

    
2197
  @locking.ssynchronized(_config_lock, shared=1)
2198
  def GetClusterInfo(self):
2199
    """Returns information about the cluster
2200

2201
    @rtype: L{objects.Cluster}
2202
    @return: the cluster object
2203

2204
    """
2205
    return self._config_data.cluster
2206

    
2207
  @locking.ssynchronized(_config_lock, shared=1)
2208
  def HasAnyDiskOfType(self, dev_type):
2209
    """Check if in there is at disk of the given type in the configuration.
2210

2211
    """
2212
    return self._config_data.HasAnyDiskOfType(dev_type)
2213

    
2214
  @locking.ssynchronized(_config_lock)
2215
  def Update(self, target, feedback_fn):
2216
    """Notify function to be called after updates.
2217

2218
    This function must be called when an object (as returned by
2219
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2220
    caller wants the modifications saved to the backing store. Note
2221
    that all modified objects will be saved, but the target argument
2222
    is the one the caller wants to ensure that it's saved.
2223

2224
    @param target: an instance of either L{objects.Cluster},
2225
        L{objects.Node} or L{objects.Instance} which is existing in
2226
        the cluster
2227
    @param feedback_fn: Callable feedback function
2228

2229
    """
2230
    if self._config_data is None:
2231
      raise errors.ProgrammerError("Configuration file not read,"
2232
                                   " cannot save.")
2233
    update_serial = False
2234
    if isinstance(target, objects.Cluster):
2235
      test = target == self._config_data.cluster
2236
    elif isinstance(target, objects.Node):
2237
      test = target in self._config_data.nodes.values()
2238
      update_serial = True
2239
    elif isinstance(target, objects.Instance):
2240
      test = target in self._config_data.instances.values()
2241
    elif isinstance(target, objects.NodeGroup):
2242
      test = target in self._config_data.nodegroups.values()
2243
    else:
2244
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2245
                                   " ConfigWriter.Update" % type(target))
2246
    if not test:
2247
      raise errors.ConfigurationError("Configuration updated since object"
2248
                                      " has been read or unknown object")
2249
    target.serial_no += 1
2250
    target.mtime = now = time.time()
2251

    
2252
    if update_serial:
2253
      # for node updates, we need to increase the cluster serial too
2254
      self._config_data.cluster.serial_no += 1
2255
      self._config_data.cluster.mtime = now
2256

    
2257
    if isinstance(target, objects.Instance):
2258
      self._UnlockedReleaseDRBDMinors(target.name)
2259

    
2260
    self._WriteConfig(feedback_fn=feedback_fn)
2261

    
2262
  @locking.ssynchronized(_config_lock)
2263
  def DropECReservations(self, ec_id):
2264
    """Drop per-execution-context reservations
2265

2266
    """
2267
    for rm in self._all_rms:
2268
      rm.DropECReservations(ec_id)