Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 7142485a

History | View | Annotate | Download (72.9 kB)

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

24 319856a9 Michael Hanselmann
This module provides the interface to the Ganeti cluster configuration.
25 a8083063 Iustin Pop

26 319856a9 Michael Hanselmann
The configuration data is stored on every node but is updated on the master
27 319856a9 Michael Hanselmann
only. After each update, the master distributes the data to the other nodes.
28 a8083063 Iustin Pop

29 319856a9 Michael Hanselmann
Currently, the data storage format is JSON. YAML was slow and consuming too
30 319856a9 Michael Hanselmann
much memory.
31 a8083063 Iustin Pop

32 a8083063 Iustin Pop
"""
33 a8083063 Iustin Pop
34 b459a848 Andrea Spadaccini
# pylint: disable=R0904
35 d367b66c Manuel Franceschini
# R0904: Too many public methods
36 d367b66c Manuel Franceschini
37 a8083063 Iustin Pop
import os
38 a8083063 Iustin Pop
import random
39 d8470559 Michael Hanselmann
import logging
40 d693c864 Iustin Pop
import time
41 54c31fd3 Michael Hanselmann
import itertools
42 a8083063 Iustin Pop
43 a8083063 Iustin Pop
from ganeti import errors
44 f78ede4e Guido Trotter
from ganeti import locking
45 a8083063 Iustin Pop
from ganeti import utils
46 a8083063 Iustin Pop
from ganeti import constants
47 a8083063 Iustin Pop
from ganeti import rpc
48 a8083063 Iustin Pop
from ganeti import objects
49 8d14b30d Iustin Pop
from ganeti import serializer
50 0fbae49a Balazs Lecz
from ganeti import uidpool
51 a744b676 Manuel Franceschini
from ganeti import netutils
52 e60c73a1 René Nussbaumer
from ganeti import runtime
53 243cdbcc Michael Hanselmann
54 243cdbcc Michael Hanselmann
55 7f93570a Iustin Pop
_config_lock = locking.SharedLock("ConfigWriter")
56 f78ede4e Guido Trotter
57 4fae38c5 Guido Trotter
# job id used for resource management at config upgrade time
58 8d9c3bef Michael Hanselmann
_UPGRADE_CONFIG_JID = "jid-cfg-upgrade"
59 4fae38c5 Guido Trotter
60 f78ede4e Guido Trotter
61 5b263ed7 Michael Hanselmann
def _ValidateConfig(data):
62 c41eea6e Iustin Pop
  """Verifies that a configuration objects looks valid.
63 c41eea6e Iustin Pop

64 c41eea6e Iustin Pop
  This only verifies the version of the configuration.
65 c41eea6e Iustin Pop

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

69 c41eea6e Iustin Pop
  """
70 5b263ed7 Michael Hanselmann
  if data.version != constants.CONFIG_VERSION:
71 4b63dc7a Iustin Pop
    raise errors.ConfigVersionMismatch(constants.CONFIG_VERSION, data.version)
72 a8083063 Iustin Pop
73 319856a9 Michael Hanselmann
74 013da361 Guido Trotter
class TemporaryReservationManager:
75 013da361 Guido Trotter
  """A temporary resource reservation manager.
76 013da361 Guido Trotter

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

80 013da361 Guido Trotter
  """
81 013da361 Guido Trotter
  def __init__(self):
82 013da361 Guido Trotter
    self._ec_reserved = {}
83 013da361 Guido Trotter
84 013da361 Guido Trotter
  def Reserved(self, resource):
85 a7359d91 David Knowles
    for holder_reserved in self._ec_reserved.values():
86 013da361 Guido Trotter
      if resource in holder_reserved:
87 013da361 Guido Trotter
        return True
88 013da361 Guido Trotter
    return False
89 013da361 Guido Trotter
90 013da361 Guido Trotter
  def Reserve(self, ec_id, resource):
91 013da361 Guido Trotter
    if self.Reserved(resource):
92 28a7318f Iustin Pop
      raise errors.ReservationError("Duplicate reservation for resource '%s'"
93 28a7318f Iustin Pop
                                    % str(resource))
94 013da361 Guido Trotter
    if ec_id not in self._ec_reserved:
95 013da361 Guido Trotter
      self._ec_reserved[ec_id] = set([resource])
96 013da361 Guido Trotter
    else:
97 013da361 Guido Trotter
      self._ec_reserved[ec_id].add(resource)
98 013da361 Guido Trotter
99 013da361 Guido Trotter
  def DropECReservations(self, ec_id):
100 013da361 Guido Trotter
    if ec_id in self._ec_reserved:
101 013da361 Guido Trotter
      del self._ec_reserved[ec_id]
102 013da361 Guido Trotter
103 013da361 Guido Trotter
  def GetReserved(self):
104 013da361 Guido Trotter
    all_reserved = set()
105 013da361 Guido Trotter
    for holder_reserved in self._ec_reserved.values():
106 013da361 Guido Trotter
      all_reserved.update(holder_reserved)
107 013da361 Guido Trotter
    return all_reserved
108 013da361 Guido Trotter
109 013da361 Guido Trotter
  def Generate(self, existing, generate_one_fn, ec_id):
110 013da361 Guido Trotter
    """Generate a new resource of this type
111 013da361 Guido Trotter

112 013da361 Guido Trotter
    """
113 013da361 Guido Trotter
    assert callable(generate_one_fn)
114 013da361 Guido Trotter
115 013da361 Guido Trotter
    all_elems = self.GetReserved()
116 013da361 Guido Trotter
    all_elems.update(existing)
117 013da361 Guido Trotter
    retries = 64
118 013da361 Guido Trotter
    while retries > 0:
119 013da361 Guido Trotter
      new_resource = generate_one_fn()
120 013da361 Guido Trotter
      if new_resource is not None and new_resource not in all_elems:
121 013da361 Guido Trotter
        break
122 013da361 Guido Trotter
    else:
123 013da361 Guido Trotter
      raise errors.ConfigurationError("Not able generate new resource"
124 013da361 Guido Trotter
                                      " (last tried: %s)" % new_resource)
125 013da361 Guido Trotter
    self.Reserve(ec_id, new_resource)
126 013da361 Guido Trotter
    return new_resource
127 013da361 Guido Trotter
128 013da361 Guido Trotter
129 fe698b38 Michael Hanselmann
def _MatchNameComponentIgnoreCase(short_name, names):
130 3a93eebb Michael Hanselmann
  """Wrapper around L{utils.text.MatchNameComponent}.
131 fe698b38 Michael Hanselmann

132 fe698b38 Michael Hanselmann
  """
133 fe698b38 Michael Hanselmann
  return utils.MatchNameComponent(short_name, names, case_sensitive=False)
134 fe698b38 Michael Hanselmann
135 fe698b38 Michael Hanselmann
136 82c54b5b Michael Hanselmann
def _CheckInstanceDiskIvNames(disks):
137 82c54b5b Michael Hanselmann
  """Checks if instance's disks' C{iv_name} attributes are in order.
138 82c54b5b Michael Hanselmann

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

145 82c54b5b Michael Hanselmann
  """
146 82c54b5b Michael Hanselmann
  result = []
147 82c54b5b Michael Hanselmann
148 82c54b5b Michael Hanselmann
  for (idx, disk) in enumerate(disks):
149 82c54b5b Michael Hanselmann
    exp_iv_name = "disk/%s" % idx
150 82c54b5b Michael Hanselmann
    if disk.iv_name != exp_iv_name:
151 82c54b5b Michael Hanselmann
      result.append((idx, exp_iv_name, disk.iv_name))
152 82c54b5b Michael Hanselmann
153 82c54b5b Michael Hanselmann
  return result
154 82c54b5b Michael Hanselmann
155 82c54b5b Michael Hanselmann
156 a8083063 Iustin Pop
class ConfigWriter:
157 098c0958 Michael Hanselmann
  """The interface to the cluster configuration.
158 a8083063 Iustin Pop

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

162 098c0958 Michael Hanselmann
  """
163 eb180fe2 Iustin Pop
  def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts,
164 eb180fe2 Iustin Pop
               accept_foreign=False):
165 14e15659 Iustin Pop
    self.write_count = 0
166 f78ede4e Guido Trotter
    self._lock = _config_lock
167 a8083063 Iustin Pop
    self._config_data = None
168 a8083063 Iustin Pop
    self._offline = offline
169 a8083063 Iustin Pop
    if cfg_file is None:
170 a8083063 Iustin Pop
      self._cfg_file = constants.CLUSTER_CONF_FILE
171 a8083063 Iustin Pop
    else:
172 a8083063 Iustin Pop
      self._cfg_file = cfg_file
173 e60c73a1 René Nussbaumer
    self._getents = _getents
174 4fae38c5 Guido Trotter
    self._temporary_ids = TemporaryReservationManager()
175 a81c53c9 Iustin Pop
    self._temporary_drbds = {}
176 36b66e6e Guido Trotter
    self._temporary_macs = TemporaryReservationManager()
177 afa1386e Guido Trotter
    self._temporary_secrets = TemporaryReservationManager()
178 d8aee57e Iustin Pop
    self._temporary_lvs = TemporaryReservationManager()
179 d8aee57e Iustin Pop
    self._all_rms = [self._temporary_ids, self._temporary_macs,
180 d8aee57e Iustin Pop
                     self._temporary_secrets, self._temporary_lvs]
181 89e1fc26 Iustin Pop
    # Note: in order to prevent errors when resolving our name in
182 89e1fc26 Iustin Pop
    # _DistributeConfig, we compute it here once and reuse it; it's
183 89e1fc26 Iustin Pop
    # better to raise an error before starting to modify the config
184 89e1fc26 Iustin Pop
    # file than after it was modified
185 b705c7a6 Manuel Franceschini
    self._my_hostname = netutils.Hostname.GetSysName()
186 3c7f6c44 Iustin Pop
    self._last_cluster_serial = -1
187 bd407597 Iustin Pop
    self._cfg_id = None
188 b2acdbdc Michael Hanselmann
    self._context = None
189 eb180fe2 Iustin Pop
    self._OpenConfig(accept_foreign)
190 a8083063 Iustin Pop
191 b2acdbdc Michael Hanselmann
  def _GetRpc(self, address_list):
192 b2acdbdc Michael Hanselmann
    """Returns RPC runner for configuration.
193 b2acdbdc Michael Hanselmann

194 b2acdbdc Michael Hanselmann
    """
195 b2acdbdc Michael Hanselmann
    return rpc.ConfigRunner(self._context, address_list)
196 b2acdbdc Michael Hanselmann
197 b2acdbdc Michael Hanselmann
  def SetContext(self, context):
198 b2acdbdc Michael Hanselmann
    """Sets Ganeti context.
199 b2acdbdc Michael Hanselmann

200 b2acdbdc Michael Hanselmann
    """
201 b2acdbdc Michael Hanselmann
    self._context = context
202 b2acdbdc Michael Hanselmann
203 a8083063 Iustin Pop
  # this method needs to be static, so that we can call it on the class
204 a8083063 Iustin Pop
  @staticmethod
205 a8083063 Iustin Pop
  def IsCluster():
206 a8083063 Iustin Pop
    """Check if the cluster is configured.
207 a8083063 Iustin Pop

208 a8083063 Iustin Pop
    """
209 a8083063 Iustin Pop
    return os.path.exists(constants.CLUSTER_CONF_FILE)
210 a8083063 Iustin Pop
211 36b66e6e Guido Trotter
  def _GenerateOneMAC(self):
212 36b66e6e Guido Trotter
    """Generate one mac address
213 36b66e6e Guido Trotter

214 36b66e6e Guido Trotter
    """
215 36b66e6e Guido Trotter
    prefix = self._config_data.cluster.mac_prefix
216 36b66e6e Guido Trotter
    byte1 = random.randrange(0, 256)
217 36b66e6e Guido Trotter
    byte2 = random.randrange(0, 256)
218 36b66e6e Guido Trotter
    byte3 = random.randrange(0, 256)
219 36b66e6e Guido Trotter
    mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
220 36b66e6e Guido Trotter
    return mac
221 36b66e6e Guido Trotter
222 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
223 5768e6a6 René Nussbaumer
  def GetNdParams(self, node):
224 5768e6a6 René Nussbaumer
    """Get the node params populated with cluster defaults.
225 5768e6a6 René Nussbaumer

226 ce523de1 Michael Hanselmann
    @type node: L{objects.Node}
227 5768e6a6 René Nussbaumer
    @param node: The node we want to know the params for
228 5768e6a6 René Nussbaumer
    @return: A dict with the filled in node params
229 5768e6a6 René Nussbaumer

230 5768e6a6 René Nussbaumer
    """
231 5768e6a6 René Nussbaumer
    nodegroup = self._UnlockedGetNodeGroup(node.group)
232 5768e6a6 René Nussbaumer
    return self._config_data.cluster.FillND(node, nodegroup)
233 5768e6a6 René Nussbaumer
234 5768e6a6 René Nussbaumer
  @locking.ssynchronized(_config_lock, shared=1)
235 36b66e6e Guido Trotter
  def GenerateMAC(self, ec_id):
236 a8083063 Iustin Pop
    """Generate a MAC for an instance.
237 a8083063 Iustin Pop

238 a8083063 Iustin Pop
    This should check the current instances for duplicates.
239 a8083063 Iustin Pop

240 a8083063 Iustin Pop
    """
241 36b66e6e Guido Trotter
    existing = self._AllMACs()
242 36b66e6e Guido Trotter
    return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
243 a8083063 Iustin Pop
244 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
245 36b66e6e Guido Trotter
  def ReserveMAC(self, mac, ec_id):
246 36b66e6e Guido Trotter
    """Reserve a MAC for an instance.
247 1862d460 Alexander Schreiber

248 1862d460 Alexander Schreiber
    This only checks instances managed by this cluster, it does not
249 1862d460 Alexander Schreiber
    check for potential collisions elsewhere.
250 1862d460 Alexander Schreiber

251 1862d460 Alexander Schreiber
    """
252 1862d460 Alexander Schreiber
    all_macs = self._AllMACs()
253 36b66e6e Guido Trotter
    if mac in all_macs:
254 36b66e6e Guido Trotter
      raise errors.ReservationError("mac already in use")
255 36b66e6e Guido Trotter
    else:
256 8785b71b Apollon Oikonomopoulos
      self._temporary_macs.Reserve(ec_id, mac)
257 1862d460 Alexander Schreiber
258 f9518d38 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
259 d8aee57e Iustin Pop
  def ReserveLV(self, lv_name, ec_id):
260 d8aee57e Iustin Pop
    """Reserve an VG/LV pair for an instance.
261 d8aee57e Iustin Pop

262 d8aee57e Iustin Pop
    @type lv_name: string
263 d8aee57e Iustin Pop
    @param lv_name: the logical volume name to reserve
264 d8aee57e Iustin Pop

265 d8aee57e Iustin Pop
    """
266 d8aee57e Iustin Pop
    all_lvs = self._AllLVs()
267 d8aee57e Iustin Pop
    if lv_name in all_lvs:
268 d8aee57e Iustin Pop
      raise errors.ReservationError("LV already in use")
269 d8aee57e Iustin Pop
    else:
270 8785b71b Apollon Oikonomopoulos
      self._temporary_lvs.Reserve(ec_id, lv_name)
271 d8aee57e Iustin Pop
272 d8aee57e Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
273 afa1386e Guido Trotter
  def GenerateDRBDSecret(self, ec_id):
274 f9518d38 Iustin Pop
    """Generate a DRBD secret.
275 f9518d38 Iustin Pop

276 f9518d38 Iustin Pop
    This checks the current disks for duplicates.
277 f9518d38 Iustin Pop

278 f9518d38 Iustin Pop
    """
279 afa1386e Guido Trotter
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
280 afa1386e Guido Trotter
                                            utils.GenerateSecret,
281 afa1386e Guido Trotter
                                            ec_id)
282 8d9c3bef Michael Hanselmann
283 34e54ebc Iustin Pop
  def _AllLVs(self):
284 923b1523 Iustin Pop
    """Compute the list of all LVs.
285 923b1523 Iustin Pop

286 923b1523 Iustin Pop
    """
287 923b1523 Iustin Pop
    lvnames = set()
288 923b1523 Iustin Pop
    for instance in self._config_data.instances.values():
289 923b1523 Iustin Pop
      node_data = instance.MapLVsByNode()
290 923b1523 Iustin Pop
      for lv_list in node_data.values():
291 923b1523 Iustin Pop
        lvnames.update(lv_list)
292 923b1523 Iustin Pop
    return lvnames
293 923b1523 Iustin Pop
294 34e54ebc Iustin Pop
  def _AllIDs(self, include_temporary):
295 34e54ebc Iustin Pop
    """Compute the list of all UUIDs and names we have.
296 34e54ebc Iustin Pop

297 34e54ebc Iustin Pop
    @type include_temporary: boolean
298 34e54ebc Iustin Pop
    @param include_temporary: whether to include the _temporary_ids set
299 34e54ebc Iustin Pop
    @rtype: set
300 34e54ebc Iustin Pop
    @return: a set of IDs
301 34e54ebc Iustin Pop

302 34e54ebc Iustin Pop
    """
303 34e54ebc Iustin Pop
    existing = set()
304 34e54ebc Iustin Pop
    if include_temporary:
305 4fae38c5 Guido Trotter
      existing.update(self._temporary_ids.GetReserved())
306 34e54ebc Iustin Pop
    existing.update(self._AllLVs())
307 34e54ebc Iustin Pop
    existing.update(self._config_data.instances.keys())
308 34e54ebc Iustin Pop
    existing.update(self._config_data.nodes.keys())
309 76d5d3a3 Iustin Pop
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
310 34e54ebc Iustin Pop
    return existing
311 34e54ebc Iustin Pop
312 4fae38c5 Guido Trotter
  def _GenerateUniqueID(self, ec_id):
313 430b923c Iustin Pop
    """Generate an unique UUID.
314 923b1523 Iustin Pop

315 923b1523 Iustin Pop
    This checks the current node, instances and disk names for
316 923b1523 Iustin Pop
    duplicates.
317 923b1523 Iustin Pop

318 c41eea6e Iustin Pop
    @rtype: string
319 c41eea6e Iustin Pop
    @return: the unique id
320 923b1523 Iustin Pop

321 923b1523 Iustin Pop
    """
322 4fae38c5 Guido Trotter
    existing = self._AllIDs(include_temporary=False)
323 4fae38c5 Guido Trotter
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
324 923b1523 Iustin Pop
325 430b923c Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
326 4fae38c5 Guido Trotter
  def GenerateUniqueID(self, ec_id):
327 430b923c Iustin Pop
    """Generate an unique ID.
328 430b923c Iustin Pop

329 430b923c Iustin Pop
    This is just a wrapper over the unlocked version.
330 430b923c Iustin Pop

331 4fae38c5 Guido Trotter
    @type ec_id: string
332 4fae38c5 Guido Trotter
    @param ec_id: unique id for the job to reserve the id to
333 34d657ba Iustin Pop

334 34d657ba Iustin Pop
    """
335 4fae38c5 Guido Trotter
    return self._GenerateUniqueID(ec_id)
336 34d657ba Iustin Pop
337 a8083063 Iustin Pop
  def _AllMACs(self):
338 a8083063 Iustin Pop
    """Return all MACs present in the config.
339 a8083063 Iustin Pop

340 c41eea6e Iustin Pop
    @rtype: list
341 c41eea6e Iustin Pop
    @return: the list of all MACs
342 c41eea6e Iustin Pop

343 a8083063 Iustin Pop
    """
344 a8083063 Iustin Pop
    result = []
345 a8083063 Iustin Pop
    for instance in self._config_data.instances.values():
346 a8083063 Iustin Pop
      for nic in instance.nics:
347 a8083063 Iustin Pop
        result.append(nic.mac)
348 a8083063 Iustin Pop
349 a8083063 Iustin Pop
    return result
350 a8083063 Iustin Pop
351 f9518d38 Iustin Pop
  def _AllDRBDSecrets(self):
352 f9518d38 Iustin Pop
    """Return all DRBD secrets present in the config.
353 f9518d38 Iustin Pop

354 c41eea6e Iustin Pop
    @rtype: list
355 c41eea6e Iustin Pop
    @return: the list of all DRBD secrets
356 c41eea6e Iustin Pop

357 f9518d38 Iustin Pop
    """
358 f9518d38 Iustin Pop
    def helper(disk, result):
359 f9518d38 Iustin Pop
      """Recursively gather secrets from this disk."""
360 f9518d38 Iustin Pop
      if disk.dev_type == constants.DT_DRBD8:
361 f9518d38 Iustin Pop
        result.append(disk.logical_id[5])
362 f9518d38 Iustin Pop
      if disk.children:
363 f9518d38 Iustin Pop
        for child in disk.children:
364 f9518d38 Iustin Pop
          helper(child, result)
365 f9518d38 Iustin Pop
366 f9518d38 Iustin Pop
    result = []
367 f9518d38 Iustin Pop
    for instance in self._config_data.instances.values():
368 f9518d38 Iustin Pop
      for disk in instance.disks:
369 f9518d38 Iustin Pop
        helper(disk, result)
370 f9518d38 Iustin Pop
371 f9518d38 Iustin Pop
    return result
372 f9518d38 Iustin Pop
373 4b98ac29 Iustin Pop
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
374 4b98ac29 Iustin Pop
    """Compute duplicate disk IDs
375 4b98ac29 Iustin Pop

376 4b98ac29 Iustin Pop
    @type disk: L{objects.Disk}
377 4b98ac29 Iustin Pop
    @param disk: the disk at which to start searching
378 4b98ac29 Iustin Pop
    @type l_ids: list
379 4b98ac29 Iustin Pop
    @param l_ids: list of current logical ids
380 4b98ac29 Iustin Pop
    @type p_ids: list
381 4b98ac29 Iustin Pop
    @param p_ids: list of current physical ids
382 4b98ac29 Iustin Pop
    @rtype: list
383 4b98ac29 Iustin Pop
    @return: a list of error messages
384 4b98ac29 Iustin Pop

385 4b98ac29 Iustin Pop
    """
386 4b98ac29 Iustin Pop
    result = []
387 25ae22e4 Iustin Pop
    if disk.logical_id is not None:
388 25ae22e4 Iustin Pop
      if disk.logical_id in l_ids:
389 25ae22e4 Iustin Pop
        result.append("duplicate logical id %s" % str(disk.logical_id))
390 25ae22e4 Iustin Pop
      else:
391 25ae22e4 Iustin Pop
        l_ids.append(disk.logical_id)
392 25ae22e4 Iustin Pop
    if disk.physical_id is not None:
393 25ae22e4 Iustin Pop
      if disk.physical_id in p_ids:
394 25ae22e4 Iustin Pop
        result.append("duplicate physical id %s" % str(disk.physical_id))
395 25ae22e4 Iustin Pop
      else:
396 25ae22e4 Iustin Pop
        p_ids.append(disk.physical_id)
397 4b98ac29 Iustin Pop
398 4b98ac29 Iustin Pop
    if disk.children:
399 4b98ac29 Iustin Pop
      for child in disk.children:
400 4b98ac29 Iustin Pop
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
401 4b98ac29 Iustin Pop
    return result
402 4b98ac29 Iustin Pop
403 4a89c54a Iustin Pop
  def _UnlockedVerifyConfig(self):
404 a8efbb40 Iustin Pop
    """Verify function.
405 a8efbb40 Iustin Pop

406 4a89c54a Iustin Pop
    @rtype: list
407 4a89c54a Iustin Pop
    @return: a list of error messages; a non-empty list signifies
408 4a89c54a Iustin Pop
        configuration errors
409 4a89c54a Iustin Pop

410 a8083063 Iustin Pop
    """
411 b459a848 Andrea Spadaccini
    # pylint: disable=R0914
412 a8083063 Iustin Pop
    result = []
413 a8083063 Iustin Pop
    seen_macs = []
414 48ce9fd9 Iustin Pop
    ports = {}
415 a8083063 Iustin Pop
    data = self._config_data
416 7e01d204 Iustin Pop
    cluster = data.cluster
417 4b98ac29 Iustin Pop
    seen_lids = []
418 4b98ac29 Iustin Pop
    seen_pids = []
419 9a5fba23 Guido Trotter
420 9a5fba23 Guido Trotter
    # global cluster checks
421 7e01d204 Iustin Pop
    if not cluster.enabled_hypervisors:
422 9a5fba23 Guido Trotter
      result.append("enabled hypervisors list doesn't have any entries")
423 7e01d204 Iustin Pop
    invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
424 9a5fba23 Guido Trotter
    if invalid_hvs:
425 9a5fba23 Guido Trotter
      result.append("enabled hypervisors contains invalid entries: %s" %
426 9a5fba23 Guido Trotter
                    invalid_hvs)
427 7e01d204 Iustin Pop
    missing_hvp = (set(cluster.enabled_hypervisors) -
428 7e01d204 Iustin Pop
                   set(cluster.hvparams.keys()))
429 9f3ac970 Iustin Pop
    if missing_hvp:
430 9f3ac970 Iustin Pop
      result.append("hypervisor parameters missing for the enabled"
431 9f3ac970 Iustin Pop
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
432 9a5fba23 Guido Trotter
433 7e01d204 Iustin Pop
    if cluster.master_node not in data.nodes:
434 9a5fba23 Guido Trotter
      result.append("cluster has invalid primary node '%s'" %
435 7e01d204 Iustin Pop
                    cluster.master_node)
436 9a5fba23 Guido Trotter
437 26f2fd8d Iustin Pop
    def _helper(owner, attr, value, template):
438 26f2fd8d Iustin Pop
      try:
439 26f2fd8d Iustin Pop
        utils.ForceDictType(value, template)
440 26f2fd8d Iustin Pop
      except errors.GenericError, err:
441 26f2fd8d Iustin Pop
        result.append("%s has invalid %s: %s" % (owner, attr, err))
442 26f2fd8d Iustin Pop
443 26f2fd8d Iustin Pop
    def _helper_nic(owner, params):
444 26f2fd8d Iustin Pop
      try:
445 26f2fd8d Iustin Pop
        objects.NIC.CheckParameterSyntax(params)
446 26f2fd8d Iustin Pop
      except errors.ConfigurationError, err:
447 26f2fd8d Iustin Pop
        result.append("%s has invalid nicparams: %s" % (owner, err))
448 26f2fd8d Iustin Pop
449 918eb80b Agata Murawska
    def _helper_ipolicy(owner, params):
450 918eb80b Agata Murawska
      try:
451 918eb80b Agata Murawska
        objects.InstancePolicy.CheckParameterSyntax(params)
452 918eb80b Agata Murawska
      except errors.ConfigurationError, err:
453 918eb80b Agata Murawska
        result.append("%s has invalid instance policy: %s" % (owner, err))
454 918eb80b Agata Murawska
455 918eb80b Agata Murawska
    def _helper_ispecs(owner, params):
456 2cc673a3 Iustin Pop
      for key, value in params.items():
457 12378fe3 Iustin Pop
        if key in constants.IPOLICY_ISPECS:
458 2cc673a3 Iustin Pop
          fullkey = "ipolicy/" + key
459 2cc673a3 Iustin Pop
          _helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES)
460 2cc673a3 Iustin Pop
        else:
461 2cc673a3 Iustin Pop
          # FIXME: assuming list type
462 ff6c5e55 Iustin Pop
          if key in constants.IPOLICY_PARAMETERS:
463 ff6c5e55 Iustin Pop
            exp_type = float
464 ff6c5e55 Iustin Pop
          else:
465 ff6c5e55 Iustin Pop
            exp_type = list
466 ff6c5e55 Iustin Pop
          if not isinstance(value, exp_type):
467 2cc673a3 Iustin Pop
            result.append("%s has invalid instance policy: for %s,"
468 ff6c5e55 Iustin Pop
                          " expecting %s, got %s" %
469 ff6c5e55 Iustin Pop
                          (owner, key, exp_type.__name__, type(value)))
470 918eb80b Agata Murawska
471 26f2fd8d Iustin Pop
    # check cluster parameters
472 26f2fd8d Iustin Pop
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
473 26f2fd8d Iustin Pop
            constants.BES_PARAMETER_TYPES)
474 26f2fd8d Iustin Pop
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
475 26f2fd8d Iustin Pop
            constants.NICS_PARAMETER_TYPES)
476 26f2fd8d Iustin Pop
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
477 26f2fd8d Iustin Pop
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
478 26f2fd8d Iustin Pop
            constants.NDS_PARAMETER_TYPES)
479 918eb80b Agata Murawska
    _helper_ipolicy("cluster", cluster.SimpleFillIPolicy({}))
480 918eb80b Agata Murawska
    _helper_ispecs("cluster", cluster.SimpleFillIPolicy({}))
481 26f2fd8d Iustin Pop
482 9a5fba23 Guido Trotter
    # per-instance checks
483 a8083063 Iustin Pop
    for instance_name in data.instances:
484 a8083063 Iustin Pop
      instance = data.instances[instance_name]
485 81196341 Iustin Pop
      if instance.name != instance_name:
486 81196341 Iustin Pop
        result.append("instance '%s' is indexed by wrong name '%s'" %
487 81196341 Iustin Pop
                      (instance.name, instance_name))
488 a8083063 Iustin Pop
      if instance.primary_node not in data.nodes:
489 8522ceeb Iustin Pop
        result.append("instance '%s' has invalid primary node '%s'" %
490 a8083063 Iustin Pop
                      (instance_name, instance.primary_node))
491 a8083063 Iustin Pop
      for snode in instance.secondary_nodes:
492 a8083063 Iustin Pop
        if snode not in data.nodes:
493 8522ceeb Iustin Pop
          result.append("instance '%s' has invalid secondary node '%s'" %
494 a8083063 Iustin Pop
                        (instance_name, snode))
495 a8083063 Iustin Pop
      for idx, nic in enumerate(instance.nics):
496 a8083063 Iustin Pop
        if nic.mac in seen_macs:
497 8522ceeb Iustin Pop
          result.append("instance '%s' has NIC %d mac %s duplicate" %
498 a8083063 Iustin Pop
                        (instance_name, idx, nic.mac))
499 a8083063 Iustin Pop
        else:
500 a8083063 Iustin Pop
          seen_macs.append(nic.mac)
501 26f2fd8d Iustin Pop
        if nic.nicparams:
502 26f2fd8d Iustin Pop
          filled = cluster.SimpleFillNIC(nic.nicparams)
503 26f2fd8d Iustin Pop
          owner = "instance %s nic %d" % (instance.name, idx)
504 26f2fd8d Iustin Pop
          _helper(owner, "nicparams",
505 26f2fd8d Iustin Pop
                  filled, constants.NICS_PARAMETER_TYPES)
506 26f2fd8d Iustin Pop
          _helper_nic(owner, filled)
507 26f2fd8d Iustin Pop
508 26f2fd8d Iustin Pop
      # parameter checks
509 26f2fd8d Iustin Pop
      if instance.beparams:
510 26f2fd8d Iustin Pop
        _helper("instance %s" % instance.name, "beparams",
511 26f2fd8d Iustin Pop
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
512 48ce9fd9 Iustin Pop
513 48ce9fd9 Iustin Pop
      # gather the drbd ports for duplicate checks
514 e2569c1d Michael Hanselmann
      for (idx, dsk) in enumerate(instance.disks):
515 48ce9fd9 Iustin Pop
        if dsk.dev_type in constants.LDS_DRBD:
516 48ce9fd9 Iustin Pop
          tcp_port = dsk.logical_id[2]
517 48ce9fd9 Iustin Pop
          if tcp_port not in ports:
518 48ce9fd9 Iustin Pop
            ports[tcp_port] = []
519 e2569c1d Michael Hanselmann
          ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
520 48ce9fd9 Iustin Pop
      # gather network port reservation
521 48ce9fd9 Iustin Pop
      net_port = getattr(instance, "network_port", None)
522 48ce9fd9 Iustin Pop
      if net_port is not None:
523 48ce9fd9 Iustin Pop
        if net_port not in ports:
524 48ce9fd9 Iustin Pop
          ports[net_port] = []
525 48ce9fd9 Iustin Pop
        ports[net_port].append((instance.name, "network port"))
526 48ce9fd9 Iustin Pop
527 332d0e37 Iustin Pop
      # instance disk verify
528 332d0e37 Iustin Pop
      for idx, disk in enumerate(instance.disks):
529 332d0e37 Iustin Pop
        result.extend(["instance '%s' disk %d error: %s" %
530 332d0e37 Iustin Pop
                       (instance.name, idx, msg) for msg in disk.Verify()])
531 4b98ac29 Iustin Pop
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
532 332d0e37 Iustin Pop
533 82c54b5b Michael Hanselmann
      wrong_names = _CheckInstanceDiskIvNames(instance.disks)
534 82c54b5b Michael Hanselmann
      if wrong_names:
535 82c54b5b Michael Hanselmann
        tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" %
536 82c54b5b Michael Hanselmann
                         (idx, exp_name, actual_name))
537 82c54b5b Michael Hanselmann
                        for (idx, exp_name, actual_name) in wrong_names)
538 82c54b5b Michael Hanselmann
539 82c54b5b Michael Hanselmann
        result.append("Instance '%s' has wrongly named disks: %s" %
540 82c54b5b Michael Hanselmann
                      (instance.name, tmp))
541 82c54b5b Michael Hanselmann
542 48ce9fd9 Iustin Pop
    # cluster-wide pool of free ports
543 7e01d204 Iustin Pop
    for free_port in cluster.tcpudp_port_pool:
544 48ce9fd9 Iustin Pop
      if free_port not in ports:
545 48ce9fd9 Iustin Pop
        ports[free_port] = []
546 48ce9fd9 Iustin Pop
      ports[free_port].append(("cluster", "port marked as free"))
547 48ce9fd9 Iustin Pop
548 48ce9fd9 Iustin Pop
    # compute tcp/udp duplicate ports
549 48ce9fd9 Iustin Pop
    keys = ports.keys()
550 48ce9fd9 Iustin Pop
    keys.sort()
551 48ce9fd9 Iustin Pop
    for pnum in keys:
552 48ce9fd9 Iustin Pop
      pdata = ports[pnum]
553 48ce9fd9 Iustin Pop
      if len(pdata) > 1:
554 1f864b60 Iustin Pop
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
555 48ce9fd9 Iustin Pop
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
556 48ce9fd9 Iustin Pop
557 48ce9fd9 Iustin Pop
    # highest used tcp port check
558 48ce9fd9 Iustin Pop
    if keys:
559 7e01d204 Iustin Pop
      if keys[-1] > cluster.highest_used_port:
560 48ce9fd9 Iustin Pop
        result.append("Highest used port mismatch, saved %s, computed %s" %
561 7e01d204 Iustin Pop
                      (cluster.highest_used_port, keys[-1]))
562 a8efbb40 Iustin Pop
563 7e01d204 Iustin Pop
    if not data.nodes[cluster.master_node].master_candidate:
564 3a26773f Iustin Pop
      result.append("Master node is not a master candidate")
565 3a26773f Iustin Pop
566 4a89c54a Iustin Pop
    # master candidate checks
567 e623dbe3 Guido Trotter
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
568 ec0292f1 Iustin Pop
    if mc_now < mc_max:
569 ec0292f1 Iustin Pop
      result.append("Not enough master candidates: actual %d, target %d" %
570 ec0292f1 Iustin Pop
                    (mc_now, mc_max))
571 48ce9fd9 Iustin Pop
572 5bf07049 Iustin Pop
    # node checks
573 81196341 Iustin Pop
    for node_name, node in data.nodes.items():
574 81196341 Iustin Pop
      if node.name != node_name:
575 81196341 Iustin Pop
        result.append("Node '%s' is indexed by wrong name '%s'" %
576 81196341 Iustin Pop
                      (node.name, node_name))
577 5bf07049 Iustin Pop
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
578 5bf07049 Iustin Pop
        result.append("Node %s state is invalid: master_candidate=%s,"
579 5bf07049 Iustin Pop
                      " drain=%s, offline=%s" %
580 3d889a7d Michael Hanselmann
                      (node.name, node.master_candidate, node.drained,
581 5bf07049 Iustin Pop
                       node.offline))
582 26f2fd8d Iustin Pop
      if node.group not in data.nodegroups:
583 26f2fd8d Iustin Pop
        result.append("Node '%s' has invalid group '%s'" %
584 26f2fd8d Iustin Pop
                      (node.name, node.group))
585 26f2fd8d Iustin Pop
      else:
586 26f2fd8d Iustin Pop
        _helper("node %s" % node.name, "ndparams",
587 26f2fd8d Iustin Pop
                cluster.FillND(node, data.nodegroups[node.group]),
588 26f2fd8d Iustin Pop
                constants.NDS_PARAMETER_TYPES)
589 5bf07049 Iustin Pop
590 6520ba14 Guido Trotter
    # nodegroups checks
591 ace16501 Guido Trotter
    nodegroups_names = set()
592 6520ba14 Guido Trotter
    for nodegroup_uuid in data.nodegroups:
593 6520ba14 Guido Trotter
      nodegroup = data.nodegroups[nodegroup_uuid]
594 6520ba14 Guido Trotter
      if nodegroup.uuid != nodegroup_uuid:
595 913cc25e Adeodato Simo
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
596 6520ba14 Guido Trotter
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
597 485ba212 Guido Trotter
      if utils.UUID_RE.match(nodegroup.name.lower()):
598 913cc25e Adeodato Simo
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
599 485ba212 Guido Trotter
                      (nodegroup.name, nodegroup.uuid))
600 ace16501 Guido Trotter
      if nodegroup.name in nodegroups_names:
601 913cc25e Adeodato Simo
        result.append("duplicate node group name '%s'" % nodegroup.name)
602 ace16501 Guido Trotter
      else:
603 ace16501 Guido Trotter
        nodegroups_names.add(nodegroup.name)
604 81e3ab4f Agata Murawska
      group_name = "group %s" % nodegroup.name
605 81e3ab4f Agata Murawska
      _helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy))
606 81e3ab4f Agata Murawska
      _helper_ispecs(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy))
607 26f2fd8d Iustin Pop
      if nodegroup.ndparams:
608 81e3ab4f Agata Murawska
        _helper(group_name, "ndparams",
609 26f2fd8d Iustin Pop
                cluster.SimpleFillND(nodegroup.ndparams),
610 26f2fd8d Iustin Pop
                constants.NDS_PARAMETER_TYPES)
611 26f2fd8d Iustin Pop
612 4a89c54a Iustin Pop
    # drbd minors check
613 1122eb25 Iustin Pop
    _, duplicates = self._UnlockedComputeDRBDMap()
614 4a89c54a Iustin Pop
    for node, minor, instance_a, instance_b in duplicates:
615 4a89c54a Iustin Pop
      result.append("DRBD minor %d on node %s is assigned twice to instances"
616 4a89c54a Iustin Pop
                    " %s and %s" % (minor, node, instance_a, instance_b))
617 4a89c54a Iustin Pop
618 0ce8f948 Iustin Pop
    # IP checks
619 7e01d204 Iustin Pop
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
620 b8716596 Michael Hanselmann
    ips = {}
621 b8716596 Michael Hanselmann
622 b8716596 Michael Hanselmann
    def _AddIpAddress(ip, name):
623 b8716596 Michael Hanselmann
      ips.setdefault(ip, []).append(name)
624 b8716596 Michael Hanselmann
625 7e01d204 Iustin Pop
    _AddIpAddress(cluster.master_ip, "cluster_ip")
626 0ce8f948 Iustin Pop
627 0ce8f948 Iustin Pop
    for node in data.nodes.values():
628 b8716596 Michael Hanselmann
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
629 0ce8f948 Iustin Pop
      if node.secondary_ip != node.primary_ip:
630 b8716596 Michael Hanselmann
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
631 b8716596 Michael Hanselmann
632 b8716596 Michael Hanselmann
    for instance in data.instances.values():
633 b8716596 Michael Hanselmann
      for idx, nic in enumerate(instance.nics):
634 b8716596 Michael Hanselmann
        if nic.ip is None:
635 b8716596 Michael Hanselmann
          continue
636 b8716596 Michael Hanselmann
637 b8716596 Michael Hanselmann
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
638 b8716596 Michael Hanselmann
        nic_mode = nicparams[constants.NIC_MODE]
639 b8716596 Michael Hanselmann
        nic_link = nicparams[constants.NIC_LINK]
640 b8716596 Michael Hanselmann
641 b8716596 Michael Hanselmann
        if nic_mode == constants.NIC_MODE_BRIDGED:
642 b8716596 Michael Hanselmann
          link = "bridge:%s" % nic_link
643 b8716596 Michael Hanselmann
        elif nic_mode == constants.NIC_MODE_ROUTED:
644 b8716596 Michael Hanselmann
          link = "route:%s" % nic_link
645 b8716596 Michael Hanselmann
        else:
646 b8716596 Michael Hanselmann
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
647 b8716596 Michael Hanselmann
648 b8716596 Michael Hanselmann
        _AddIpAddress("%s/%s" % (link, nic.ip),
649 b8716596 Michael Hanselmann
                      "instance:%s/nic:%d" % (instance.name, idx))
650 0ce8f948 Iustin Pop
651 0ce8f948 Iustin Pop
    for ip, owners in ips.items():
652 0ce8f948 Iustin Pop
      if len(owners) > 1:
653 0ce8f948 Iustin Pop
        result.append("IP address %s is used by multiple owners: %s" %
654 1f864b60 Iustin Pop
                      (ip, utils.CommaJoin(owners)))
655 b8716596 Michael Hanselmann
656 a8083063 Iustin Pop
    return result
657 a8083063 Iustin Pop
658 4a89c54a Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
659 4a89c54a Iustin Pop
  def VerifyConfig(self):
660 4a89c54a Iustin Pop
    """Verify function.
661 4a89c54a Iustin Pop

662 4a89c54a Iustin Pop
    This is just a wrapper over L{_UnlockedVerifyConfig}.
663 4a89c54a Iustin Pop

664 4a89c54a Iustin Pop
    @rtype: list
665 4a89c54a Iustin Pop
    @return: a list of error messages; a non-empty list signifies
666 4a89c54a Iustin Pop
        configuration errors
667 4a89c54a Iustin Pop

668 4a89c54a Iustin Pop
    """
669 4a89c54a Iustin Pop
    return self._UnlockedVerifyConfig()
670 4a89c54a Iustin Pop
671 f78ede4e Guido Trotter
  def _UnlockedSetDiskID(self, disk, node_name):
672 a8083063 Iustin Pop
    """Convert the unique ID to the ID needed on the target nodes.
673 a8083063 Iustin Pop

674 a8083063 Iustin Pop
    This is used only for drbd, which needs ip/port configuration.
675 a8083063 Iustin Pop

676 a8083063 Iustin Pop
    The routine descends down and updates its children also, because
677 a8083063 Iustin Pop
    this helps when the only the top device is passed to the remote
678 a8083063 Iustin Pop
    node.
679 a8083063 Iustin Pop

680 f78ede4e Guido Trotter
    This function is for internal use, when the config lock is already held.
681 f78ede4e Guido Trotter

682 a8083063 Iustin Pop
    """
683 a8083063 Iustin Pop
    if disk.children:
684 a8083063 Iustin Pop
      for child in disk.children:
685 f78ede4e Guido Trotter
        self._UnlockedSetDiskID(child, node_name)
686 a8083063 Iustin Pop
687 a8083063 Iustin Pop
    if disk.logical_id is None and disk.physical_id is not None:
688 a8083063 Iustin Pop
      return
689 ffa1c0dc Iustin Pop
    if disk.dev_type == constants.LD_DRBD8:
690 f9518d38 Iustin Pop
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
691 a8083063 Iustin Pop
      if node_name not in (pnode, snode):
692 3ecf6786 Iustin Pop
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
693 3ecf6786 Iustin Pop
                                        node_name)
694 f78ede4e Guido Trotter
      pnode_info = self._UnlockedGetNodeInfo(pnode)
695 f78ede4e Guido Trotter
      snode_info = self._UnlockedGetNodeInfo(snode)
696 a8083063 Iustin Pop
      if pnode_info is None or snode_info is None:
697 a8083063 Iustin Pop
        raise errors.ConfigurationError("Can't find primary or secondary node"
698 a8083063 Iustin Pop
                                        " for %s" % str(disk))
699 ffa1c0dc Iustin Pop
      p_data = (pnode_info.secondary_ip, port)
700 ffa1c0dc Iustin Pop
      s_data = (snode_info.secondary_ip, port)
701 a8083063 Iustin Pop
      if pnode == node_name:
702 f9518d38 Iustin Pop
        disk.physical_id = p_data + s_data + (pminor, secret)
703 a8083063 Iustin Pop
      else: # it must be secondary, we tested above
704 f9518d38 Iustin Pop
        disk.physical_id = s_data + p_data + (sminor, secret)
705 a8083063 Iustin Pop
    else:
706 a8083063 Iustin Pop
      disk.physical_id = disk.logical_id
707 a8083063 Iustin Pop
    return
708 a8083063 Iustin Pop
709 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
710 f78ede4e Guido Trotter
  def SetDiskID(self, disk, node_name):
711 f78ede4e Guido Trotter
    """Convert the unique ID to the ID needed on the target nodes.
712 f78ede4e Guido Trotter

713 f78ede4e Guido Trotter
    This is used only for drbd, which needs ip/port configuration.
714 f78ede4e Guido Trotter

715 f78ede4e Guido Trotter
    The routine descends down and updates its children also, because
716 f78ede4e Guido Trotter
    this helps when the only the top device is passed to the remote
717 f78ede4e Guido Trotter
    node.
718 f78ede4e Guido Trotter

719 f78ede4e Guido Trotter
    """
720 f78ede4e Guido Trotter
    return self._UnlockedSetDiskID(disk, node_name)
721 f78ede4e Guido Trotter
722 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
723 b2fddf63 Iustin Pop
  def AddTcpUdpPort(self, port):
724 b2fddf63 Iustin Pop
    """Adds a new port to the available port pool.
725 b2fddf63 Iustin Pop

726 b2fddf63 Iustin Pop
    """
727 264bb3c5 Michael Hanselmann
    if not isinstance(port, int):
728 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Invalid type passed for port")
729 264bb3c5 Michael Hanselmann
730 b2fddf63 Iustin Pop
    self._config_data.cluster.tcpudp_port_pool.add(port)
731 264bb3c5 Michael Hanselmann
    self._WriteConfig()
732 264bb3c5 Michael Hanselmann
733 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
734 b2fddf63 Iustin Pop
  def GetPortList(self):
735 264bb3c5 Michael Hanselmann
    """Returns a copy of the current port list.
736 264bb3c5 Michael Hanselmann

737 264bb3c5 Michael Hanselmann
    """
738 b2fddf63 Iustin Pop
    return self._config_data.cluster.tcpudp_port_pool.copy()
739 264bb3c5 Michael Hanselmann
740 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
741 a8083063 Iustin Pop
  def AllocatePort(self):
742 a8083063 Iustin Pop
    """Allocate a port.
743 a8083063 Iustin Pop

744 b2fddf63 Iustin Pop
    The port will be taken from the available port pool or from the
745 b2fddf63 Iustin Pop
    default port range (and in this case we increase
746 b2fddf63 Iustin Pop
    highest_used_port).
747 a8083063 Iustin Pop

748 a8083063 Iustin Pop
    """
749 264bb3c5 Michael Hanselmann
    # If there are TCP/IP ports configured, we use them first.
750 b2fddf63 Iustin Pop
    if self._config_data.cluster.tcpudp_port_pool:
751 b2fddf63 Iustin Pop
      port = self._config_data.cluster.tcpudp_port_pool.pop()
752 264bb3c5 Michael Hanselmann
    else:
753 264bb3c5 Michael Hanselmann
      port = self._config_data.cluster.highest_used_port + 1
754 264bb3c5 Michael Hanselmann
      if port >= constants.LAST_DRBD_PORT:
755 3ecf6786 Iustin Pop
        raise errors.ConfigurationError("The highest used port is greater"
756 3ecf6786 Iustin Pop
                                        " than %s. Aborting." %
757 3ecf6786 Iustin Pop
                                        constants.LAST_DRBD_PORT)
758 264bb3c5 Michael Hanselmann
      self._config_data.cluster.highest_used_port = port
759 a8083063 Iustin Pop
760 a8083063 Iustin Pop
    self._WriteConfig()
761 a8083063 Iustin Pop
    return port
762 a8083063 Iustin Pop
763 6d2e83d5 Iustin Pop
  def _UnlockedComputeDRBDMap(self):
764 a81c53c9 Iustin Pop
    """Compute the used DRBD minor/nodes.
765 a81c53c9 Iustin Pop

766 4a89c54a Iustin Pop
    @rtype: (dict, list)
767 c41eea6e Iustin Pop
    @return: dictionary of node_name: dict of minor: instance_name;
768 c41eea6e Iustin Pop
        the returned dict will have all the nodes in it (even if with
769 4a89c54a Iustin Pop
        an empty list), and a list of duplicates; if the duplicates
770 4a89c54a Iustin Pop
        list is not empty, the configuration is corrupted and its caller
771 4a89c54a Iustin Pop
        should raise an exception
772 a81c53c9 Iustin Pop

773 a81c53c9 Iustin Pop
    """
774 a81c53c9 Iustin Pop
    def _AppendUsedPorts(instance_name, disk, used):
775 4a89c54a Iustin Pop
      duplicates = []
776 f9518d38 Iustin Pop
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
777 7c4d6c7b Michael Hanselmann
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
778 7c4d6c7b Michael Hanselmann
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
779 4a89c54a Iustin Pop
          assert node in used, ("Node '%s' of instance '%s' not found"
780 4a89c54a Iustin Pop
                                " in node list" % (node, instance_name))
781 a81c53c9 Iustin Pop
          if port in used[node]:
782 4a89c54a Iustin Pop
            duplicates.append((node, port, instance_name, used[node][port]))
783 4a89c54a Iustin Pop
          else:
784 4a89c54a Iustin Pop
            used[node][port] = instance_name
785 a81c53c9 Iustin Pop
      if disk.children:
786 a81c53c9 Iustin Pop
        for child in disk.children:
787 4a89c54a Iustin Pop
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
788 4a89c54a Iustin Pop
      return duplicates
789 a81c53c9 Iustin Pop
790 4a89c54a Iustin Pop
    duplicates = []
791 a81c53c9 Iustin Pop
    my_dict = dict((node, {}) for node in self._config_data.nodes)
792 79b26a7a Iustin Pop
    for instance in self._config_data.instances.itervalues():
793 79b26a7a Iustin Pop
      for disk in instance.disks:
794 79b26a7a Iustin Pop
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
795 a81c53c9 Iustin Pop
    for (node, minor), instance in self._temporary_drbds.iteritems():
796 79b26a7a Iustin Pop
      if minor in my_dict[node] and my_dict[node][minor] != instance:
797 4a89c54a Iustin Pop
        duplicates.append((node, minor, instance, my_dict[node][minor]))
798 4a89c54a Iustin Pop
      else:
799 4a89c54a Iustin Pop
        my_dict[node][minor] = instance
800 4a89c54a Iustin Pop
    return my_dict, duplicates
801 a81c53c9 Iustin Pop
802 a81c53c9 Iustin Pop
  @locking.ssynchronized(_config_lock)
803 6d2e83d5 Iustin Pop
  def ComputeDRBDMap(self):
804 6d2e83d5 Iustin Pop
    """Compute the used DRBD minor/nodes.
805 6d2e83d5 Iustin Pop

806 6d2e83d5 Iustin Pop
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
807 6d2e83d5 Iustin Pop

808 6d2e83d5 Iustin Pop
    @return: dictionary of node_name: dict of minor: instance_name;
809 6d2e83d5 Iustin Pop
        the returned dict will have all the nodes in it (even if with
810 6d2e83d5 Iustin Pop
        an empty list).
811 6d2e83d5 Iustin Pop

812 6d2e83d5 Iustin Pop
    """
813 4a89c54a Iustin Pop
    d_map, duplicates = self._UnlockedComputeDRBDMap()
814 4a89c54a Iustin Pop
    if duplicates:
815 4a89c54a Iustin Pop
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
816 4a89c54a Iustin Pop
                                      str(duplicates))
817 4a89c54a Iustin Pop
    return d_map
818 6d2e83d5 Iustin Pop
819 6d2e83d5 Iustin Pop
  @locking.ssynchronized(_config_lock)
820 a81c53c9 Iustin Pop
  def AllocateDRBDMinor(self, nodes, instance):
821 a81c53c9 Iustin Pop
    """Allocate a drbd minor.
822 a81c53c9 Iustin Pop

823 a81c53c9 Iustin Pop
    The free minor will be automatically computed from the existing
824 a81c53c9 Iustin Pop
    devices. A node can be given multiple times in order to allocate
825 a81c53c9 Iustin Pop
    multiple minors. The result is the list of minors, in the same
826 a81c53c9 Iustin Pop
    order as the passed nodes.
827 a81c53c9 Iustin Pop

828 32388e6d Iustin Pop
    @type instance: string
829 32388e6d Iustin Pop
    @param instance: the instance for which we allocate minors
830 32388e6d Iustin Pop

831 a81c53c9 Iustin Pop
    """
832 32388e6d Iustin Pop
    assert isinstance(instance, basestring), \
833 4a89c54a Iustin Pop
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
834 32388e6d Iustin Pop
835 4a89c54a Iustin Pop
    d_map, duplicates = self._UnlockedComputeDRBDMap()
836 4a89c54a Iustin Pop
    if duplicates:
837 4a89c54a Iustin Pop
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
838 4a89c54a Iustin Pop
                                      str(duplicates))
839 a81c53c9 Iustin Pop
    result = []
840 a81c53c9 Iustin Pop
    for nname in nodes:
841 a81c53c9 Iustin Pop
      ndata = d_map[nname]
842 a81c53c9 Iustin Pop
      if not ndata:
843 a81c53c9 Iustin Pop
        # no minors used, we can start at 0
844 a81c53c9 Iustin Pop
        result.append(0)
845 a81c53c9 Iustin Pop
        ndata[0] = instance
846 d48663e4 Iustin Pop
        self._temporary_drbds[(nname, 0)] = instance
847 a81c53c9 Iustin Pop
        continue
848 a81c53c9 Iustin Pop
      keys = ndata.keys()
849 a81c53c9 Iustin Pop
      keys.sort()
850 a81c53c9 Iustin Pop
      ffree = utils.FirstFree(keys)
851 a81c53c9 Iustin Pop
      if ffree is None:
852 a81c53c9 Iustin Pop
        # return the next minor
853 a81c53c9 Iustin Pop
        # TODO: implement high-limit check
854 a81c53c9 Iustin Pop
        minor = keys[-1] + 1
855 a81c53c9 Iustin Pop
      else:
856 a81c53c9 Iustin Pop
        minor = ffree
857 4a89c54a Iustin Pop
      # double-check minor against current instances
858 4a89c54a Iustin Pop
      assert minor not in d_map[nname], \
859 4a89c54a Iustin Pop
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
860 4a89c54a Iustin Pop
              " already allocated to instance %s" %
861 4a89c54a Iustin Pop
              (minor, nname, d_map[nname][minor]))
862 a81c53c9 Iustin Pop
      ndata[minor] = instance
863 4a89c54a Iustin Pop
      # double-check minor against reservation
864 4a89c54a Iustin Pop
      r_key = (nname, minor)
865 4a89c54a Iustin Pop
      assert r_key not in self._temporary_drbds, \
866 4a89c54a Iustin Pop
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
867 4a89c54a Iustin Pop
              " reserved for instance %s" %
868 4a89c54a Iustin Pop
              (minor, nname, self._temporary_drbds[r_key]))
869 4a89c54a Iustin Pop
      self._temporary_drbds[r_key] = instance
870 4a89c54a Iustin Pop
      result.append(minor)
871 a81c53c9 Iustin Pop
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
872 a81c53c9 Iustin Pop
                  nodes, result)
873 a81c53c9 Iustin Pop
    return result
874 a81c53c9 Iustin Pop
875 61cf6b5e Iustin Pop
  def _UnlockedReleaseDRBDMinors(self, instance):
876 a81c53c9 Iustin Pop
    """Release temporary drbd minors allocated for a given instance.
877 a81c53c9 Iustin Pop

878 a81c53c9 Iustin Pop
    @type instance: string
879 a81c53c9 Iustin Pop
    @param instance: the instance for which temporary minors should be
880 a81c53c9 Iustin Pop
                     released
881 a81c53c9 Iustin Pop

882 a81c53c9 Iustin Pop
    """
883 32388e6d Iustin Pop
    assert isinstance(instance, basestring), \
884 32388e6d Iustin Pop
           "Invalid argument passed to ReleaseDRBDMinors"
885 a81c53c9 Iustin Pop
    for key, name in self._temporary_drbds.items():
886 a81c53c9 Iustin Pop
      if name == instance:
887 a81c53c9 Iustin Pop
        del self._temporary_drbds[key]
888 a81c53c9 Iustin Pop
889 61cf6b5e Iustin Pop
  @locking.ssynchronized(_config_lock)
890 61cf6b5e Iustin Pop
  def ReleaseDRBDMinors(self, instance):
891 61cf6b5e Iustin Pop
    """Release temporary drbd minors allocated for a given instance.
892 61cf6b5e Iustin Pop

893 61cf6b5e Iustin Pop
    This should be called on the error paths, on the success paths
894 61cf6b5e Iustin Pop
    it's automatically called by the ConfigWriter add and update
895 61cf6b5e Iustin Pop
    functions.
896 61cf6b5e Iustin Pop

897 61cf6b5e Iustin Pop
    This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
898 61cf6b5e Iustin Pop

899 61cf6b5e Iustin Pop
    @type instance: string
900 61cf6b5e Iustin Pop
    @param instance: the instance for which temporary minors should be
901 61cf6b5e Iustin Pop
                     released
902 61cf6b5e Iustin Pop

903 61cf6b5e Iustin Pop
    """
904 61cf6b5e Iustin Pop
    self._UnlockedReleaseDRBDMinors(instance)
905 61cf6b5e Iustin Pop
906 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
907 4a8b186a Michael Hanselmann
  def GetConfigVersion(self):
908 4a8b186a Michael Hanselmann
    """Get the configuration version.
909 4a8b186a Michael Hanselmann

910 4a8b186a Michael Hanselmann
    @return: Config version
911 4a8b186a Michael Hanselmann

912 4a8b186a Michael Hanselmann
    """
913 4a8b186a Michael Hanselmann
    return self._config_data.version
914 4a8b186a Michael Hanselmann
915 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
916 4a8b186a Michael Hanselmann
  def GetClusterName(self):
917 4a8b186a Michael Hanselmann
    """Get cluster name.
918 4a8b186a Michael Hanselmann

919 4a8b186a Michael Hanselmann
    @return: Cluster name
920 4a8b186a Michael Hanselmann

921 4a8b186a Michael Hanselmann
    """
922 4a8b186a Michael Hanselmann
    return self._config_data.cluster.cluster_name
923 4a8b186a Michael Hanselmann
924 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
925 4a8b186a Michael Hanselmann
  def GetMasterNode(self):
926 4a8b186a Michael Hanselmann
    """Get the hostname of the master node for this cluster.
927 4a8b186a Michael Hanselmann

928 4a8b186a Michael Hanselmann
    @return: Master hostname
929 4a8b186a Michael Hanselmann

930 4a8b186a Michael Hanselmann
    """
931 4a8b186a Michael Hanselmann
    return self._config_data.cluster.master_node
932 4a8b186a Michael Hanselmann
933 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
934 4a8b186a Michael Hanselmann
  def GetMasterIP(self):
935 4a8b186a Michael Hanselmann
    """Get the IP of the master node for this cluster.
936 4a8b186a Michael Hanselmann

937 4a8b186a Michael Hanselmann
    @return: Master IP
938 4a8b186a Michael Hanselmann

939 4a8b186a Michael Hanselmann
    """
940 4a8b186a Michael Hanselmann
    return self._config_data.cluster.master_ip
941 4a8b186a Michael Hanselmann
942 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
943 4a8b186a Michael Hanselmann
  def GetMasterNetdev(self):
944 4a8b186a Michael Hanselmann
    """Get the master network device for this cluster.
945 4a8b186a Michael Hanselmann

946 4a8b186a Michael Hanselmann
    """
947 4a8b186a Michael Hanselmann
    return self._config_data.cluster.master_netdev
948 4a8b186a Michael Hanselmann
949 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
950 5a8648eb Andrea Spadaccini
  def GetMasterNetmask(self):
951 5a8648eb Andrea Spadaccini
    """Get the netmask of the master node for this cluster.
952 5a8648eb Andrea Spadaccini

953 5a8648eb Andrea Spadaccini
    """
954 5a8648eb Andrea Spadaccini
    return self._config_data.cluster.master_netmask
955 5a8648eb Andrea Spadaccini
956 5a8648eb Andrea Spadaccini
  @locking.ssynchronized(_config_lock, shared=1)
957 33be7576 Andrea Spadaccini
  def GetUseExternalMipScript(self):
958 33be7576 Andrea Spadaccini
    """Get flag representing whether to use the external master IP setup script.
959 33be7576 Andrea Spadaccini

960 33be7576 Andrea Spadaccini
    """
961 33be7576 Andrea Spadaccini
    return self._config_data.cluster.use_external_mip_script
962 33be7576 Andrea Spadaccini
963 33be7576 Andrea Spadaccini
  @locking.ssynchronized(_config_lock, shared=1)
964 4a8b186a Michael Hanselmann
  def GetFileStorageDir(self):
965 4a8b186a Michael Hanselmann
    """Get the file storage dir for this cluster.
966 4a8b186a Michael Hanselmann

967 4a8b186a Michael Hanselmann
    """
968 4a8b186a Michael Hanselmann
    return self._config_data.cluster.file_storage_dir
969 4a8b186a Michael Hanselmann
970 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
971 4b97f902 Apollon Oikonomopoulos
  def GetSharedFileStorageDir(self):
972 4b97f902 Apollon Oikonomopoulos
    """Get the shared file storage dir for this cluster.
973 4b97f902 Apollon Oikonomopoulos

974 4b97f902 Apollon Oikonomopoulos
    """
975 4b97f902 Apollon Oikonomopoulos
    return self._config_data.cluster.shared_file_storage_dir
976 4b97f902 Apollon Oikonomopoulos
977 4b97f902 Apollon Oikonomopoulos
  @locking.ssynchronized(_config_lock, shared=1)
978 4a8b186a Michael Hanselmann
  def GetHypervisorType(self):
979 4a8b186a Michael Hanselmann
    """Get the hypervisor type for this cluster.
980 4a8b186a Michael Hanselmann

981 4a8b186a Michael Hanselmann
    """
982 066f465d Guido Trotter
    return self._config_data.cluster.enabled_hypervisors[0]
983 4a8b186a Michael Hanselmann
984 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
985 a8083063 Iustin Pop
  def GetHostKey(self):
986 a8083063 Iustin Pop
    """Return the rsa hostkey from the config.
987 a8083063 Iustin Pop

988 c41eea6e Iustin Pop
    @rtype: string
989 c41eea6e Iustin Pop
    @return: the rsa hostkey
990 a8083063 Iustin Pop

991 a8083063 Iustin Pop
    """
992 a8083063 Iustin Pop
    return self._config_data.cluster.rsahostkeypub
993 a8083063 Iustin Pop
994 bf4af505 Apollon Oikonomopoulos
  @locking.ssynchronized(_config_lock, shared=1)
995 bf4af505 Apollon Oikonomopoulos
  def GetDefaultIAllocator(self):
996 bf4af505 Apollon Oikonomopoulos
    """Get the default instance allocator for this cluster.
997 bf4af505 Apollon Oikonomopoulos

998 bf4af505 Apollon Oikonomopoulos
    """
999 bf4af505 Apollon Oikonomopoulos
    return self._config_data.cluster.default_iallocator
1000 bf4af505 Apollon Oikonomopoulos
1001 868a98ca Manuel Franceschini
  @locking.ssynchronized(_config_lock, shared=1)
1002 868a98ca Manuel Franceschini
  def GetPrimaryIPFamily(self):
1003 868a98ca Manuel Franceschini
    """Get cluster primary ip family.
1004 868a98ca Manuel Franceschini

1005 868a98ca Manuel Franceschini
    @return: primary ip family
1006 868a98ca Manuel Franceschini

1007 868a98ca Manuel Franceschini
    """
1008 868a98ca Manuel Franceschini
    return self._config_data.cluster.primary_ip_family
1009 868a98ca Manuel Franceschini
1010 c9f4b8e6 Andrea Spadaccini
  @locking.ssynchronized(_config_lock, shared=1)
1011 c9f4b8e6 Andrea Spadaccini
  def GetMasterNetworkParameters(self):
1012 c9f4b8e6 Andrea Spadaccini
    """Get network parameters of the master node.
1013 c9f4b8e6 Andrea Spadaccini

1014 f9d20654 Andrea Spadaccini
    @rtype: L{object.MasterNetworkParameters}
1015 f9d20654 Andrea Spadaccini
    @return: network parameters of the master node
1016 c9f4b8e6 Andrea Spadaccini

1017 c9f4b8e6 Andrea Spadaccini
    """
1018 c9f4b8e6 Andrea Spadaccini
    cluster = self._config_data.cluster
1019 c79198a0 Andrea Spadaccini
    result = objects.MasterNetworkParameters(name=cluster.master_node,
1020 c79198a0 Andrea Spadaccini
      ip=cluster.master_ip,
1021 c79198a0 Andrea Spadaccini
      netmask=cluster.master_netmask,
1022 c79198a0 Andrea Spadaccini
      netdev=cluster.master_netdev,
1023 c79198a0 Andrea Spadaccini
      ip_family=cluster.primary_ip_family)
1024 c9f4b8e6 Andrea Spadaccini
1025 f9d20654 Andrea Spadaccini
    return result
1026 f9d20654 Andrea Spadaccini
1027 e11a1b77 Adeodato Simo
  @locking.ssynchronized(_config_lock)
1028 e11a1b77 Adeodato Simo
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
1029 e11a1b77 Adeodato Simo
    """Add a node group to the configuration.
1030 e11a1b77 Adeodato Simo

1031 90e99856 Adeodato Simo
    This method calls group.UpgradeConfig() to fill any missing attributes
1032 90e99856 Adeodato Simo
    according to their default values.
1033 90e99856 Adeodato Simo

1034 e11a1b77 Adeodato Simo
    @type group: L{objects.NodeGroup}
1035 e11a1b77 Adeodato Simo
    @param group: the NodeGroup object to add
1036 e11a1b77 Adeodato Simo
    @type ec_id: string
1037 e11a1b77 Adeodato Simo
    @param ec_id: unique id for the job to use when creating a missing UUID
1038 e11a1b77 Adeodato Simo
    @type check_uuid: bool
1039 e11a1b77 Adeodato Simo
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
1040 e11a1b77 Adeodato Simo
                       it does, ensure that it does not exist in the
1041 e11a1b77 Adeodato Simo
                       configuration already
1042 e11a1b77 Adeodato Simo

1043 e11a1b77 Adeodato Simo
    """
1044 e11a1b77 Adeodato Simo
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
1045 e11a1b77 Adeodato Simo
    self._WriteConfig()
1046 e11a1b77 Adeodato Simo
1047 e11a1b77 Adeodato Simo
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
1048 e11a1b77 Adeodato Simo
    """Add a node group to the configuration.
1049 e11a1b77 Adeodato Simo

1050 e11a1b77 Adeodato Simo
    """
1051 e11a1b77 Adeodato Simo
    logging.info("Adding node group %s to configuration", group.name)
1052 e11a1b77 Adeodato Simo
1053 e11a1b77 Adeodato Simo
    # Some code might need to add a node group with a pre-populated UUID
1054 e11a1b77 Adeodato Simo
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
1055 e11a1b77 Adeodato Simo
    # the "does this UUID" exist already check.
1056 e11a1b77 Adeodato Simo
    if check_uuid:
1057 e11a1b77 Adeodato Simo
      self._EnsureUUID(group, ec_id)
1058 e11a1b77 Adeodato Simo
1059 18ffc0fe Stephen Shirley
    try:
1060 18ffc0fe Stephen Shirley
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
1061 18ffc0fe Stephen Shirley
    except errors.OpPrereqError:
1062 18ffc0fe Stephen Shirley
      pass
1063 18ffc0fe Stephen Shirley
    else:
1064 18ffc0fe Stephen Shirley
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
1065 18ffc0fe Stephen Shirley
                                 " node group (UUID: %s)" %
1066 18ffc0fe Stephen Shirley
                                 (group.name, existing_uuid),
1067 18ffc0fe Stephen Shirley
                                 errors.ECODE_EXISTS)
1068 18ffc0fe Stephen Shirley
1069 e11a1b77 Adeodato Simo
    group.serial_no = 1
1070 e11a1b77 Adeodato Simo
    group.ctime = group.mtime = time.time()
1071 90e99856 Adeodato Simo
    group.UpgradeConfig()
1072 e11a1b77 Adeodato Simo
1073 e11a1b77 Adeodato Simo
    self._config_data.nodegroups[group.uuid] = group
1074 e11a1b77 Adeodato Simo
    self._config_data.cluster.serial_no += 1
1075 e11a1b77 Adeodato Simo
1076 e11a1b77 Adeodato Simo
  @locking.ssynchronized(_config_lock)
1077 e11a1b77 Adeodato Simo
  def RemoveNodeGroup(self, group_uuid):
1078 e11a1b77 Adeodato Simo
    """Remove a node group from the configuration.
1079 e11a1b77 Adeodato Simo

1080 e11a1b77 Adeodato Simo
    @type group_uuid: string
1081 e11a1b77 Adeodato Simo
    @param group_uuid: the UUID of the node group to remove
1082 e11a1b77 Adeodato Simo

1083 e11a1b77 Adeodato Simo
    """
1084 e11a1b77 Adeodato Simo
    logging.info("Removing node group %s from configuration", group_uuid)
1085 e11a1b77 Adeodato Simo
1086 e11a1b77 Adeodato Simo
    if group_uuid not in self._config_data.nodegroups:
1087 e11a1b77 Adeodato Simo
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
1088 e11a1b77 Adeodato Simo
1089 0389c42a Stephen Shirley
    assert len(self._config_data.nodegroups) != 1, \
1090 0389c42a Stephen Shirley
            "Group '%s' is the only group, cannot be removed" % group_uuid
1091 0389c42a Stephen Shirley
1092 e11a1b77 Adeodato Simo
    del self._config_data.nodegroups[group_uuid]
1093 e11a1b77 Adeodato Simo
    self._config_data.cluster.serial_no += 1
1094 e11a1b77 Adeodato Simo
    self._WriteConfig()
1095 e11a1b77 Adeodato Simo
1096 e85d8982 Stephen Shirley
  def _UnlockedLookupNodeGroup(self, target):
1097 412b3531 Guido Trotter
    """Lookup a node group's UUID.
1098 eaa98a04 Guido Trotter

1099 eaa98a04 Guido Trotter
    @type target: string or None
1100 412b3531 Guido Trotter
    @param target: group name or UUID or None to look for the default
1101 eaa98a04 Guido Trotter
    @rtype: string
1102 412b3531 Guido Trotter
    @return: nodegroup UUID
1103 eaa98a04 Guido Trotter
    @raises errors.OpPrereqError: when the target group cannot be found
1104 eaa98a04 Guido Trotter

1105 eaa98a04 Guido Trotter
    """
1106 eaa98a04 Guido Trotter
    if target is None:
1107 eaa98a04 Guido Trotter
      if len(self._config_data.nodegroups) != 1:
1108 913cc25e Adeodato Simo
        raise errors.OpPrereqError("More than one node group exists. Target"
1109 eaa98a04 Guido Trotter
                                   " group must be specified explicitely.")
1110 eaa98a04 Guido Trotter
      else:
1111 eaa98a04 Guido Trotter
        return self._config_data.nodegroups.keys()[0]
1112 eaa98a04 Guido Trotter
    if target in self._config_data.nodegroups:
1113 eaa98a04 Guido Trotter
      return target
1114 eaa98a04 Guido Trotter
    for nodegroup in self._config_data.nodegroups.values():
1115 eaa98a04 Guido Trotter
      if nodegroup.name == target:
1116 eaa98a04 Guido Trotter
        return nodegroup.uuid
1117 e0f9ed64 Adeodato Simo
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1118 e0f9ed64 Adeodato Simo
                               errors.ECODE_NOENT)
1119 eaa98a04 Guido Trotter
1120 e85d8982 Stephen Shirley
  @locking.ssynchronized(_config_lock, shared=1)
1121 e85d8982 Stephen Shirley
  def LookupNodeGroup(self, target):
1122 e85d8982 Stephen Shirley
    """Lookup a node group's UUID.
1123 e85d8982 Stephen Shirley

1124 e85d8982 Stephen Shirley
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1125 e85d8982 Stephen Shirley

1126 e85d8982 Stephen Shirley
    @type target: string or None
1127 e85d8982 Stephen Shirley
    @param target: group name or UUID or None to look for the default
1128 e85d8982 Stephen Shirley
    @rtype: string
1129 e85d8982 Stephen Shirley
    @return: nodegroup UUID
1130 e85d8982 Stephen Shirley

1131 e85d8982 Stephen Shirley
    """
1132 e85d8982 Stephen Shirley
    return self._UnlockedLookupNodeGroup(target)
1133 e85d8982 Stephen Shirley
1134 5768e6a6 René Nussbaumer
  def _UnlockedGetNodeGroup(self, uuid):
1135 648e4196 Guido Trotter
    """Lookup a node group.
1136 648e4196 Guido Trotter

1137 648e4196 Guido Trotter
    @type uuid: string
1138 648e4196 Guido Trotter
    @param uuid: group UUID
1139 648e4196 Guido Trotter
    @rtype: L{objects.NodeGroup} or None
1140 648e4196 Guido Trotter
    @return: nodegroup object, or None if not found
1141 648e4196 Guido Trotter

1142 648e4196 Guido Trotter
    """
1143 648e4196 Guido Trotter
    if uuid not in self._config_data.nodegroups:
1144 648e4196 Guido Trotter
      return None
1145 648e4196 Guido Trotter
1146 648e4196 Guido Trotter
    return self._config_data.nodegroups[uuid]
1147 648e4196 Guido Trotter
1148 648e4196 Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1149 5768e6a6 René Nussbaumer
  def GetNodeGroup(self, uuid):
1150 5768e6a6 René Nussbaumer
    """Lookup a node group.
1151 5768e6a6 René Nussbaumer

1152 5768e6a6 René Nussbaumer
    @type uuid: string
1153 5768e6a6 René Nussbaumer
    @param uuid: group UUID
1154 5768e6a6 René Nussbaumer
    @rtype: L{objects.NodeGroup} or None
1155 5768e6a6 René Nussbaumer
    @return: nodegroup object, or None if not found
1156 5768e6a6 René Nussbaumer

1157 5768e6a6 René Nussbaumer
    """
1158 5768e6a6 René Nussbaumer
    return self._UnlockedGetNodeGroup(uuid)
1159 5768e6a6 René Nussbaumer
1160 5768e6a6 René Nussbaumer
  @locking.ssynchronized(_config_lock, shared=1)
1161 622444e5 Iustin Pop
  def GetAllNodeGroupsInfo(self):
1162 622444e5 Iustin Pop
    """Get the configuration of all node groups.
1163 622444e5 Iustin Pop

1164 622444e5 Iustin Pop
    """
1165 622444e5 Iustin Pop
    return dict(self._config_data.nodegroups)
1166 622444e5 Iustin Pop
1167 1ac6f2ad Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1168 1ac6f2ad Guido Trotter
  def GetNodeGroupList(self):
1169 1ac6f2ad Guido Trotter
    """Get a list of node groups.
1170 1ac6f2ad Guido Trotter

1171 1ac6f2ad Guido Trotter
    """
1172 1ac6f2ad Guido Trotter
    return self._config_data.nodegroups.keys()
1173 1ac6f2ad Guido Trotter
1174 dac81741 Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
1175 dac81741 Michael Hanselmann
  def GetNodeGroupMembersByNodes(self, nodes):
1176 dac81741 Michael Hanselmann
    """Get nodes which are member in the same nodegroups as the given nodes.
1177 dac81741 Michael Hanselmann

1178 dac81741 Michael Hanselmann
    """
1179 dac81741 Michael Hanselmann
    ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1180 dac81741 Michael Hanselmann
    return frozenset(member_name
1181 dac81741 Michael Hanselmann
                     for node_name in nodes
1182 dac81741 Michael Hanselmann
                     for member_name in
1183 dac81741 Michael Hanselmann
                       self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1184 dac81741 Michael Hanselmann
1185 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1186 0debfb35 Guido Trotter
  def AddInstance(self, instance, ec_id):
1187 a8083063 Iustin Pop
    """Add an instance to the config.
1188 a8083063 Iustin Pop

1189 a8083063 Iustin Pop
    This should be used after creating a new instance.
1190 a8083063 Iustin Pop

1191 c41eea6e Iustin Pop
    @type instance: L{objects.Instance}
1192 c41eea6e Iustin Pop
    @param instance: the instance object
1193 c41eea6e Iustin Pop

1194 a8083063 Iustin Pop
    """
1195 a8083063 Iustin Pop
    if not isinstance(instance, objects.Instance):
1196 a8083063 Iustin Pop
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1197 a8083063 Iustin Pop
1198 e00fb268 Iustin Pop
    if instance.disk_template != constants.DT_DISKLESS:
1199 e00fb268 Iustin Pop
      all_lvs = instance.MapLVsByNode()
1200 74a48621 Iustin Pop
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1201 923b1523 Iustin Pop
1202 e4640214 Guido Trotter
    all_macs = self._AllMACs()
1203 e4640214 Guido Trotter
    for nic in instance.nics:
1204 e4640214 Guido Trotter
      if nic.mac in all_macs:
1205 e4640214 Guido Trotter
        raise errors.ConfigurationError("Cannot add instance %s:"
1206 430b923c Iustin Pop
                                        " MAC address '%s' already in use." %
1207 430b923c Iustin Pop
                                        (instance.name, nic.mac))
1208 430b923c Iustin Pop
1209 0debfb35 Guido Trotter
    self._EnsureUUID(instance, ec_id)
1210 e4640214 Guido Trotter
1211 b989e85d Iustin Pop
    instance.serial_no = 1
1212 d693c864 Iustin Pop
    instance.ctime = instance.mtime = time.time()
1213 a8083063 Iustin Pop
    self._config_data.instances[instance.name] = instance
1214 81a49123 Iustin Pop
    self._config_data.cluster.serial_no += 1
1215 61cf6b5e Iustin Pop
    self._UnlockedReleaseDRBDMinors(instance.name)
1216 a8083063 Iustin Pop
    self._WriteConfig()
1217 a8083063 Iustin Pop
1218 0debfb35 Guido Trotter
  def _EnsureUUID(self, item, ec_id):
1219 430b923c Iustin Pop
    """Ensures a given object has a valid UUID.
1220 430b923c Iustin Pop

1221 430b923c Iustin Pop
    @param item: the instance or node to be checked
1222 0debfb35 Guido Trotter
    @param ec_id: the execution context id for the uuid reservation
1223 430b923c Iustin Pop

1224 430b923c Iustin Pop
    """
1225 430b923c Iustin Pop
    if not item.uuid:
1226 4fae38c5 Guido Trotter
      item.uuid = self._GenerateUniqueID(ec_id)
1227 be0fc05d Iustin Pop
    elif item.uuid in self._AllIDs(include_temporary=True):
1228 be0fc05d Iustin Pop
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1229 be0fc05d Iustin Pop
                                      " in use" % (item.name, item.uuid))
1230 430b923c Iustin Pop
1231 6a408fb2 Iustin Pop
  def _SetInstanceStatus(self, instance_name, status):
1232 6a408fb2 Iustin Pop
    """Set the instance's status to a given value.
1233 a8083063 Iustin Pop

1234 a8083063 Iustin Pop
    """
1235 2e04d454 Agata Murawska
    assert status in constants.ADMINST_ALL, \
1236 0d68c45d Iustin Pop
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1237 a8083063 Iustin Pop
1238 a8083063 Iustin Pop
    if instance_name not in self._config_data.instances:
1239 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Unknown instance '%s'" %
1240 3ecf6786 Iustin Pop
                                      instance_name)
1241 a8083063 Iustin Pop
    instance = self._config_data.instances[instance_name]
1242 9ca8a7c5 Agata Murawska
    if instance.admin_state != status:
1243 9ca8a7c5 Agata Murawska
      instance.admin_state = status
1244 b989e85d Iustin Pop
      instance.serial_no += 1
1245 d693c864 Iustin Pop
      instance.mtime = time.time()
1246 455a3445 Iustin Pop
      self._WriteConfig()
1247 a8083063 Iustin Pop
1248 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1249 6a408fb2 Iustin Pop
  def MarkInstanceUp(self, instance_name):
1250 6a408fb2 Iustin Pop
    """Mark the instance status to up in the config.
1251 6a408fb2 Iustin Pop

1252 6a408fb2 Iustin Pop
    """
1253 57de31c0 Agata Murawska
    self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
1254 57de31c0 Agata Murawska
1255 57de31c0 Agata Murawska
  @locking.ssynchronized(_config_lock)
1256 57de31c0 Agata Murawska
  def MarkInstanceOffline(self, instance_name):
1257 57de31c0 Agata Murawska
    """Mark the instance status to down in the config.
1258 57de31c0 Agata Murawska

1259 57de31c0 Agata Murawska
    """
1260 57de31c0 Agata Murawska
    self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
1261 6a408fb2 Iustin Pop
1262 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1263 a8083063 Iustin Pop
  def RemoveInstance(self, instance_name):
1264 a8083063 Iustin Pop
    """Remove the instance from the configuration.
1265 a8083063 Iustin Pop

1266 a8083063 Iustin Pop
    """
1267 a8083063 Iustin Pop
    if instance_name not in self._config_data.instances:
1268 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1269 f396ad8c Vangelis Koukis
1270 f396ad8c Vangelis Koukis
    # If a network port has been allocated to the instance,
1271 f396ad8c Vangelis Koukis
    # return it to the pool of free ports.
1272 f396ad8c Vangelis Koukis
    inst = self._config_data.instances[instance_name]
1273 f396ad8c Vangelis Koukis
    network_port = getattr(inst, "network_port", None)
1274 f396ad8c Vangelis Koukis
    if network_port is not None:
1275 f396ad8c Vangelis Koukis
      self._config_data.cluster.tcpudp_port_pool.add(network_port)
1276 f396ad8c Vangelis Koukis
1277 a8083063 Iustin Pop
    del self._config_data.instances[instance_name]
1278 81a49123 Iustin Pop
    self._config_data.cluster.serial_no += 1
1279 a8083063 Iustin Pop
    self._WriteConfig()
1280 a8083063 Iustin Pop
1281 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1282 fc95f88f Iustin Pop
  def RenameInstance(self, old_name, new_name):
1283 fc95f88f Iustin Pop
    """Rename an instance.
1284 fc95f88f Iustin Pop

1285 fc95f88f Iustin Pop
    This needs to be done in ConfigWriter and not by RemoveInstance
1286 fc95f88f Iustin Pop
    combined with AddInstance as only we can guarantee an atomic
1287 fc95f88f Iustin Pop
    rename.
1288 fc95f88f Iustin Pop

1289 fc95f88f Iustin Pop
    """
1290 fc95f88f Iustin Pop
    if old_name not in self._config_data.instances:
1291 fc95f88f Iustin Pop
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1292 ea642319 Michael Hanselmann
1293 ea642319 Michael Hanselmann
    # Operate on a copy to not loose instance object in case of a failure
1294 ea642319 Michael Hanselmann
    inst = self._config_data.instances[old_name].Copy()
1295 fc95f88f Iustin Pop
    inst.name = new_name
1296 b23c4333 Manuel Franceschini
1297 ea642319 Michael Hanselmann
    for (idx, disk) in enumerate(inst.disks):
1298 b23c4333 Manuel Franceschini
      if disk.dev_type == constants.LD_FILE:
1299 b23c4333 Manuel Franceschini
        # rename the file paths in logical and physical id
1300 b23c4333 Manuel Franceschini
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1301 ea642319 Michael Hanselmann
        disk.logical_id = (disk.logical_id[0],
1302 ea642319 Michael Hanselmann
                           utils.PathJoin(file_storage_dir, inst.name,
1303 ea642319 Michael Hanselmann
                                          "disk%s" % idx))
1304 ea642319 Michael Hanselmann
        disk.physical_id = disk.logical_id
1305 ea642319 Michael Hanselmann
1306 ea642319 Michael Hanselmann
    # Actually replace instance object
1307 ea642319 Michael Hanselmann
    del self._config_data.instances[old_name]
1308 ea642319 Michael Hanselmann
    self._config_data.instances[inst.name] = inst
1309 b23c4333 Manuel Franceschini
1310 1fc34c48 Michael Hanselmann
    # Force update of ssconf files
1311 1fc34c48 Michael Hanselmann
    self._config_data.cluster.serial_no += 1
1312 1fc34c48 Michael Hanselmann
1313 fc95f88f Iustin Pop
    self._WriteConfig()
1314 fc95f88f Iustin Pop
1315 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1316 a8083063 Iustin Pop
  def MarkInstanceDown(self, instance_name):
1317 a8083063 Iustin Pop
    """Mark the status of an instance to down in the configuration.
1318 a8083063 Iustin Pop

1319 a8083063 Iustin Pop
    """
1320 2e04d454 Agata Murawska
    self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
1321 a8083063 Iustin Pop
1322 94bbfece Iustin Pop
  def _UnlockedGetInstanceList(self):
1323 94bbfece Iustin Pop
    """Get the list of instances.
1324 94bbfece Iustin Pop

1325 94bbfece Iustin Pop
    This function is for internal use, when the config lock is already held.
1326 94bbfece Iustin Pop

1327 94bbfece Iustin Pop
    """
1328 94bbfece Iustin Pop
    return self._config_data.instances.keys()
1329 94bbfece Iustin Pop
1330 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1331 a8083063 Iustin Pop
  def GetInstanceList(self):
1332 a8083063 Iustin Pop
    """Get the list of instances.
1333 a8083063 Iustin Pop

1334 c41eea6e Iustin Pop
    @return: array of instances, ex. ['instance2.example.com',
1335 c41eea6e Iustin Pop
        'instance1.example.com']
1336 a8083063 Iustin Pop

1337 a8083063 Iustin Pop
    """
1338 94bbfece Iustin Pop
    return self._UnlockedGetInstanceList()
1339 a8083063 Iustin Pop
1340 a8083063 Iustin Pop
  def ExpandInstanceName(self, short_name):
1341 a8083063 Iustin Pop
    """Attempt to expand an incomplete instance name.
1342 a8083063 Iustin Pop

1343 a8083063 Iustin Pop
    """
1344 fe698b38 Michael Hanselmann
    # Locking is done in L{ConfigWriter.GetInstanceList}
1345 fe698b38 Michael Hanselmann
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1346 a8083063 Iustin Pop
1347 94bbfece Iustin Pop
  def _UnlockedGetInstanceInfo(self, instance_name):
1348 5bbd3f7f Michael Hanselmann
    """Returns information about an instance.
1349 94bbfece Iustin Pop

1350 94bbfece Iustin Pop
    This function is for internal use, when the config lock is already held.
1351 94bbfece Iustin Pop

1352 94bbfece Iustin Pop
    """
1353 94bbfece Iustin Pop
    if instance_name not in self._config_data.instances:
1354 94bbfece Iustin Pop
      return None
1355 94bbfece Iustin Pop
1356 94bbfece Iustin Pop
    return self._config_data.instances[instance_name]
1357 94bbfece Iustin Pop
1358 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1359 a8083063 Iustin Pop
  def GetInstanceInfo(self, instance_name):
1360 5bbd3f7f Michael Hanselmann
    """Returns information about an instance.
1361 a8083063 Iustin Pop

1362 5bbd3f7f Michael Hanselmann
    It takes the information from the configuration file. Other information of
1363 a8083063 Iustin Pop
    an instance are taken from the live systems.
1364 a8083063 Iustin Pop

1365 c41eea6e Iustin Pop
    @param instance_name: name of the instance, e.g.
1366 c41eea6e Iustin Pop
        I{instance1.example.com}
1367 a8083063 Iustin Pop

1368 c41eea6e Iustin Pop
    @rtype: L{objects.Instance}
1369 c41eea6e Iustin Pop
    @return: the instance object
1370 a8083063 Iustin Pop

1371 a8083063 Iustin Pop
    """
1372 94bbfece Iustin Pop
    return self._UnlockedGetInstanceInfo(instance_name)
1373 a8083063 Iustin Pop
1374 0b2de758 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1375 2674690b Michael Hanselmann
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1376 2674690b Michael Hanselmann
    """Returns set of node group UUIDs for instance's nodes.
1377 2674690b Michael Hanselmann

1378 2674690b Michael Hanselmann
    @rtype: frozenset
1379 2674690b Michael Hanselmann

1380 2674690b Michael Hanselmann
    """
1381 2674690b Michael Hanselmann
    instance = self._UnlockedGetInstanceInfo(instance_name)
1382 2674690b Michael Hanselmann
    if not instance:
1383 2674690b Michael Hanselmann
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1384 2674690b Michael Hanselmann
1385 2674690b Michael Hanselmann
    if primary_only:
1386 2674690b Michael Hanselmann
      nodes = [instance.primary_node]
1387 2674690b Michael Hanselmann
    else:
1388 2674690b Michael Hanselmann
      nodes = instance.all_nodes
1389 2674690b Michael Hanselmann
1390 2674690b Michael Hanselmann
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1391 2674690b Michael Hanselmann
                     for node_name in nodes)
1392 2674690b Michael Hanselmann
1393 2674690b Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
1394 71333cb9 Iustin Pop
  def GetMultiInstanceInfo(self, instances):
1395 71333cb9 Iustin Pop
    """Get the configuration of multiple instances.
1396 71333cb9 Iustin Pop

1397 71333cb9 Iustin Pop
    @param instances: list of instance names
1398 71333cb9 Iustin Pop
    @rtype: list
1399 71333cb9 Iustin Pop
    @return: list of tuples (instance, instance_info), where
1400 71333cb9 Iustin Pop
        instance_info is what would GetInstanceInfo return for the
1401 71333cb9 Iustin Pop
        node, while keeping the original order
1402 71333cb9 Iustin Pop

1403 71333cb9 Iustin Pop
    """
1404 71333cb9 Iustin Pop
    return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances]
1405 71333cb9 Iustin Pop
1406 71333cb9 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1407 0b2de758 Iustin Pop
  def GetAllInstancesInfo(self):
1408 0b2de758 Iustin Pop
    """Get the configuration of all instances.
1409 0b2de758 Iustin Pop

1410 0b2de758 Iustin Pop
    @rtype: dict
1411 5fcc718f Iustin Pop
    @return: dict of (instance, instance_info), where instance_info is what
1412 0b2de758 Iustin Pop
              would GetInstanceInfo return for the node
1413 0b2de758 Iustin Pop

1414 0b2de758 Iustin Pop
    """
1415 64d3bd52 Guido Trotter
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1416 64d3bd52 Guido Trotter
                    for instance in self._UnlockedGetInstanceList()])
1417 0b2de758 Iustin Pop
    return my_dict
1418 0b2de758 Iustin Pop
1419 cc19798f Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
1420 cc19798f Michael Hanselmann
  def GetInstancesInfoByFilter(self, filter_fn):
1421 cc19798f Michael Hanselmann
    """Get instance configuration with a filter.
1422 cc19798f Michael Hanselmann

1423 cc19798f Michael Hanselmann
    @type filter_fn: callable
1424 cc19798f Michael Hanselmann
    @param filter_fn: Filter function receiving instance object as parameter,
1425 cc19798f Michael Hanselmann
      returning boolean. Important: this function is called while the
1426 cc19798f Michael Hanselmann
      configuration locks is held. It must not do any complex work or call
1427 cc19798f Michael Hanselmann
      functions potentially leading to a deadlock. Ideally it doesn't call any
1428 cc19798f Michael Hanselmann
      other functions and just compares instance attributes.
1429 cc19798f Michael Hanselmann

1430 cc19798f Michael Hanselmann
    """
1431 cc19798f Michael Hanselmann
    return dict((name, inst)
1432 cc19798f Michael Hanselmann
                for (name, inst) in self._config_data.instances.items()
1433 cc19798f Michael Hanselmann
                if filter_fn(inst))
1434 cc19798f Michael Hanselmann
1435 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1436 0debfb35 Guido Trotter
  def AddNode(self, node, ec_id):
1437 a8083063 Iustin Pop
    """Add a node to the configuration.
1438 a8083063 Iustin Pop

1439 c41eea6e Iustin Pop
    @type node: L{objects.Node}
1440 c41eea6e Iustin Pop
    @param node: a Node instance
1441 a8083063 Iustin Pop

1442 a8083063 Iustin Pop
    """
1443 099c52ad Iustin Pop
    logging.info("Adding node %s to configuration", node.name)
1444 d8470559 Michael Hanselmann
1445 0debfb35 Guido Trotter
    self._EnsureUUID(node, ec_id)
1446 430b923c Iustin Pop
1447 b989e85d Iustin Pop
    node.serial_no = 1
1448 d693c864 Iustin Pop
    node.ctime = node.mtime = time.time()
1449 f936c153 Iustin Pop
    self._UnlockedAddNodeToGroup(node.name, node.group)
1450 a8083063 Iustin Pop
    self._config_data.nodes[node.name] = node
1451 b9f72b4e Iustin Pop
    self._config_data.cluster.serial_no += 1
1452 a8083063 Iustin Pop
    self._WriteConfig()
1453 a8083063 Iustin Pop
1454 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1455 a8083063 Iustin Pop
  def RemoveNode(self, node_name):
1456 a8083063 Iustin Pop
    """Remove a node from the configuration.
1457 a8083063 Iustin Pop

1458 a8083063 Iustin Pop
    """
1459 099c52ad Iustin Pop
    logging.info("Removing node %s from configuration", node_name)
1460 d8470559 Michael Hanselmann
1461 a8083063 Iustin Pop
    if node_name not in self._config_data.nodes:
1462 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1463 a8083063 Iustin Pop
1464 190e3cb6 Guido Trotter
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1465 a8083063 Iustin Pop
    del self._config_data.nodes[node_name]
1466 b9f72b4e Iustin Pop
    self._config_data.cluster.serial_no += 1
1467 a8083063 Iustin Pop
    self._WriteConfig()
1468 a8083063 Iustin Pop
1469 a8083063 Iustin Pop
  def ExpandNodeName(self, short_name):
1470 fe698b38 Michael Hanselmann
    """Attempt to expand an incomplete node name.
1471 a8083063 Iustin Pop

1472 a8083063 Iustin Pop
    """
1473 fe698b38 Michael Hanselmann
    # Locking is done in L{ConfigWriter.GetNodeList}
1474 fe698b38 Michael Hanselmann
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1475 a8083063 Iustin Pop
1476 f78ede4e Guido Trotter
  def _UnlockedGetNodeInfo(self, node_name):
1477 a8083063 Iustin Pop
    """Get the configuration of a node, as stored in the config.
1478 a8083063 Iustin Pop

1479 c41eea6e Iustin Pop
    This function is for internal use, when the config lock is already
1480 c41eea6e Iustin Pop
    held.
1481 f78ede4e Guido Trotter

1482 c41eea6e Iustin Pop
    @param node_name: the node name, e.g. I{node1.example.com}
1483 a8083063 Iustin Pop

1484 c41eea6e Iustin Pop
    @rtype: L{objects.Node}
1485 c41eea6e Iustin Pop
    @return: the node object
1486 a8083063 Iustin Pop

1487 a8083063 Iustin Pop
    """
1488 a8083063 Iustin Pop
    if node_name not in self._config_data.nodes:
1489 a8083063 Iustin Pop
      return None
1490 a8083063 Iustin Pop
1491 a8083063 Iustin Pop
    return self._config_data.nodes[node_name]
1492 a8083063 Iustin Pop
1493 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1494 f78ede4e Guido Trotter
  def GetNodeInfo(self, node_name):
1495 f78ede4e Guido Trotter
    """Get the configuration of a node, as stored in the config.
1496 f78ede4e Guido Trotter

1497 c41eea6e Iustin Pop
    This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
1498 f78ede4e Guido Trotter

1499 c41eea6e Iustin Pop
    @param node_name: the node name, e.g. I{node1.example.com}
1500 c41eea6e Iustin Pop

1501 c41eea6e Iustin Pop
    @rtype: L{objects.Node}
1502 c41eea6e Iustin Pop
    @return: the node object
1503 f78ede4e Guido Trotter

1504 f78ede4e Guido Trotter
    """
1505 f78ede4e Guido Trotter
    return self._UnlockedGetNodeInfo(node_name)
1506 f78ede4e Guido Trotter
1507 8bf9e9a5 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1508 8bf9e9a5 Iustin Pop
  def GetNodeInstances(self, node_name):
1509 8bf9e9a5 Iustin Pop
    """Get the instances of a node, as stored in the config.
1510 8bf9e9a5 Iustin Pop

1511 8bf9e9a5 Iustin Pop
    @param node_name: the node name, e.g. I{node1.example.com}
1512 8bf9e9a5 Iustin Pop

1513 8bf9e9a5 Iustin Pop
    @rtype: (list, list)
1514 8bf9e9a5 Iustin Pop
    @return: a tuple with two lists: the primary and the secondary instances
1515 8bf9e9a5 Iustin Pop

1516 8bf9e9a5 Iustin Pop
    """
1517 8bf9e9a5 Iustin Pop
    pri = []
1518 8bf9e9a5 Iustin Pop
    sec = []
1519 8bf9e9a5 Iustin Pop
    for inst in self._config_data.instances.values():
1520 8bf9e9a5 Iustin Pop
      if inst.primary_node == node_name:
1521 8bf9e9a5 Iustin Pop
        pri.append(inst.name)
1522 8bf9e9a5 Iustin Pop
      if node_name in inst.secondary_nodes:
1523 8bf9e9a5 Iustin Pop
        sec.append(inst.name)
1524 8bf9e9a5 Iustin Pop
    return (pri, sec)
1525 8bf9e9a5 Iustin Pop
1526 c71b049c Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
1527 c71b049c Michael Hanselmann
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1528 c71b049c Michael Hanselmann
    """Get the instances of a node group.
1529 c71b049c Michael Hanselmann

1530 c71b049c Michael Hanselmann
    @param uuid: Node group UUID
1531 c71b049c Michael Hanselmann
    @param primary_only: Whether to only consider primary nodes
1532 c71b049c Michael Hanselmann
    @rtype: frozenset
1533 c71b049c Michael Hanselmann
    @return: List of instance names in node group
1534 c71b049c Michael Hanselmann

1535 c71b049c Michael Hanselmann
    """
1536 c71b049c Michael Hanselmann
    if primary_only:
1537 c71b049c Michael Hanselmann
      nodes_fn = lambda inst: [inst.primary_node]
1538 c71b049c Michael Hanselmann
    else:
1539 c71b049c Michael Hanselmann
      nodes_fn = lambda inst: inst.all_nodes
1540 c71b049c Michael Hanselmann
1541 c71b049c Michael Hanselmann
    return frozenset(inst.name
1542 c71b049c Michael Hanselmann
                     for inst in self._config_data.instances.values()
1543 c71b049c Michael Hanselmann
                     for node_name in nodes_fn(inst)
1544 c71b049c Michael Hanselmann
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1545 c71b049c Michael Hanselmann
1546 f78ede4e Guido Trotter
  def _UnlockedGetNodeList(self):
1547 a8083063 Iustin Pop
    """Return the list of nodes which are in the configuration.
1548 a8083063 Iustin Pop

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

1552 c41eea6e Iustin Pop
    @rtype: list
1553 f78ede4e Guido Trotter

1554 a8083063 Iustin Pop
    """
1555 a8083063 Iustin Pop
    return self._config_data.nodes.keys()
1556 a8083063 Iustin Pop
1557 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1558 f78ede4e Guido Trotter
  def GetNodeList(self):
1559 f78ede4e Guido Trotter
    """Return the list of nodes which are in the configuration.
1560 f78ede4e Guido Trotter

1561 f78ede4e Guido Trotter
    """
1562 f78ede4e Guido Trotter
    return self._UnlockedGetNodeList()
1563 f78ede4e Guido Trotter
1564 6819dc49 Iustin Pop
  def _UnlockedGetOnlineNodeList(self):
1565 94a02bb5 Iustin Pop
    """Return the list of nodes which are online.
1566 94a02bb5 Iustin Pop

1567 94a02bb5 Iustin Pop
    """
1568 94a02bb5 Iustin Pop
    all_nodes = [self._UnlockedGetNodeInfo(node)
1569 94a02bb5 Iustin Pop
                 for node in self._UnlockedGetNodeList()]
1570 94a02bb5 Iustin Pop
    return [node.name for node in all_nodes if not node.offline]
1571 94a02bb5 Iustin Pop
1572 94a02bb5 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1573 6819dc49 Iustin Pop
  def GetOnlineNodeList(self):
1574 6819dc49 Iustin Pop
    """Return the list of nodes which are online.
1575 6819dc49 Iustin Pop

1576 6819dc49 Iustin Pop
    """
1577 6819dc49 Iustin Pop
    return self._UnlockedGetOnlineNodeList()
1578 6819dc49 Iustin Pop
1579 6819dc49 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1580 075b62ca Iustin Pop
  def GetVmCapableNodeList(self):
1581 075b62ca Iustin Pop
    """Return the list of nodes which are not vm capable.
1582 075b62ca Iustin Pop

1583 075b62ca Iustin Pop
    """
1584 075b62ca Iustin Pop
    all_nodes = [self._UnlockedGetNodeInfo(node)
1585 075b62ca Iustin Pop
                 for node in self._UnlockedGetNodeList()]
1586 075b62ca Iustin Pop
    return [node.name for node in all_nodes if node.vm_capable]
1587 075b62ca Iustin Pop
1588 075b62ca Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1589 8bf9e9a5 Iustin Pop
  def GetNonVmCapableNodeList(self):
1590 8bf9e9a5 Iustin Pop
    """Return the list of nodes which are not vm capable.
1591 8bf9e9a5 Iustin Pop

1592 8bf9e9a5 Iustin Pop
    """
1593 8bf9e9a5 Iustin Pop
    all_nodes = [self._UnlockedGetNodeInfo(node)
1594 8bf9e9a5 Iustin Pop
                 for node in self._UnlockedGetNodeList()]
1595 8bf9e9a5 Iustin Pop
    return [node.name for node in all_nodes if not node.vm_capable]
1596 8bf9e9a5 Iustin Pop
1597 8bf9e9a5 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1598 f5eaa3c1 Iustin Pop
  def GetMultiNodeInfo(self, nodes):
1599 f5eaa3c1 Iustin Pop
    """Get the configuration of multiple nodes.
1600 f5eaa3c1 Iustin Pop

1601 f5eaa3c1 Iustin Pop
    @param nodes: list of node names
1602 f5eaa3c1 Iustin Pop
    @rtype: list
1603 f5eaa3c1 Iustin Pop
    @return: list of tuples of (node, node_info), where node_info is
1604 f5eaa3c1 Iustin Pop
        what would GetNodeInfo return for the node, in the original
1605 f5eaa3c1 Iustin Pop
        order
1606 f5eaa3c1 Iustin Pop

1607 f5eaa3c1 Iustin Pop
    """
1608 f5eaa3c1 Iustin Pop
    return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes]
1609 f5eaa3c1 Iustin Pop
1610 f5eaa3c1 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1611 d65e5776 Iustin Pop
  def GetAllNodesInfo(self):
1612 d65e5776 Iustin Pop
    """Get the configuration of all nodes.
1613 d65e5776 Iustin Pop

1614 d65e5776 Iustin Pop
    @rtype: dict
1615 ec0292f1 Iustin Pop
    @return: dict of (node, node_info), where node_info is what
1616 d65e5776 Iustin Pop
              would GetNodeInfo return for the node
1617 d65e5776 Iustin Pop

1618 d65e5776 Iustin Pop
    """
1619 ee14d800 Michael Hanselmann
    return self._UnlockedGetAllNodesInfo()
1620 ee14d800 Michael Hanselmann
1621 ee14d800 Michael Hanselmann
  def _UnlockedGetAllNodesInfo(self):
1622 ee14d800 Michael Hanselmann
    """Gets configuration of all nodes.
1623 ee14d800 Michael Hanselmann

1624 ee14d800 Michael Hanselmann
    @note: See L{GetAllNodesInfo}
1625 ee14d800 Michael Hanselmann

1626 ee14d800 Michael Hanselmann
    """
1627 ee14d800 Michael Hanselmann
    return dict([(node, self._UnlockedGetNodeInfo(node))
1628 ee14d800 Michael Hanselmann
                 for node in self._UnlockedGetNodeList()])
1629 d65e5776 Iustin Pop
1630 9d5b1371 Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
1631 9d5b1371 Michael Hanselmann
  def GetNodeGroupsFromNodes(self, nodes):
1632 9d5b1371 Michael Hanselmann
    """Returns groups for a list of nodes.
1633 9d5b1371 Michael Hanselmann

1634 9d5b1371 Michael Hanselmann
    @type nodes: list of string
1635 9d5b1371 Michael Hanselmann
    @param nodes: List of node names
1636 9d5b1371 Michael Hanselmann
    @rtype: frozenset
1637 9d5b1371 Michael Hanselmann

1638 9d5b1371 Michael Hanselmann
    """
1639 9d5b1371 Michael Hanselmann
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1640 9d5b1371 Michael Hanselmann
1641 23f06b2b Iustin Pop
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1642 ec0292f1 Iustin Pop
    """Get the number of current and maximum desired and possible candidates.
1643 ec0292f1 Iustin Pop

1644 23f06b2b Iustin Pop
    @type exceptions: list
1645 23f06b2b Iustin Pop
    @param exceptions: if passed, list of nodes that should be ignored
1646 ec0292f1 Iustin Pop
    @rtype: tuple
1647 e623dbe3 Guido Trotter
    @return: tuple of (current, desired and possible, possible)
1648 ec0292f1 Iustin Pop

1649 ec0292f1 Iustin Pop
    """
1650 e623dbe3 Guido Trotter
    mc_now = mc_should = mc_max = 0
1651 23f06b2b Iustin Pop
    for node in self._config_data.nodes.values():
1652 23f06b2b Iustin Pop
      if exceptions and node.name in exceptions:
1653 23f06b2b Iustin Pop
        continue
1654 490acd18 Iustin Pop
      if not (node.offline or node.drained) and node.master_capable:
1655 ec0292f1 Iustin Pop
        mc_max += 1
1656 ec0292f1 Iustin Pop
      if node.master_candidate:
1657 ec0292f1 Iustin Pop
        mc_now += 1
1658 e623dbe3 Guido Trotter
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1659 e623dbe3 Guido Trotter
    return (mc_now, mc_should, mc_max)
1660 ec0292f1 Iustin Pop
1661 ec0292f1 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1662 23f06b2b Iustin Pop
  def GetMasterCandidateStats(self, exceptions=None):
1663 ec0292f1 Iustin Pop
    """Get the number of current and maximum possible candidates.
1664 ec0292f1 Iustin Pop

1665 ec0292f1 Iustin Pop
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1666 ec0292f1 Iustin Pop

1667 23f06b2b Iustin Pop
    @type exceptions: list
1668 23f06b2b Iustin Pop
    @param exceptions: if passed, list of nodes that should be ignored
1669 ec0292f1 Iustin Pop
    @rtype: tuple
1670 ec0292f1 Iustin Pop
    @return: tuple of (current, max)
1671 ec0292f1 Iustin Pop

1672 ec0292f1 Iustin Pop
    """
1673 23f06b2b Iustin Pop
    return self._UnlockedGetMasterCandidateStats(exceptions)
1674 ec0292f1 Iustin Pop
1675 ec0292f1 Iustin Pop
  @locking.ssynchronized(_config_lock)
1676 44485f49 Guido Trotter
  def MaintainCandidatePool(self, exceptions):
1677 ec0292f1 Iustin Pop
    """Try to grow the candidate pool to the desired size.
1678 ec0292f1 Iustin Pop

1679 44485f49 Guido Trotter
    @type exceptions: list
1680 44485f49 Guido Trotter
    @param exceptions: if passed, list of nodes that should be ignored
1681 ec0292f1 Iustin Pop
    @rtype: list
1682 ee513a66 Iustin Pop
    @return: list with the adjusted nodes (L{objects.Node} instances)
1683 ec0292f1 Iustin Pop

1684 ec0292f1 Iustin Pop
    """
1685 44485f49 Guido Trotter
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1686 ec0292f1 Iustin Pop
    mod_list = []
1687 ec0292f1 Iustin Pop
    if mc_now < mc_max:
1688 ec0292f1 Iustin Pop
      node_list = self._config_data.nodes.keys()
1689 ec0292f1 Iustin Pop
      random.shuffle(node_list)
1690 ec0292f1 Iustin Pop
      for name in node_list:
1691 ec0292f1 Iustin Pop
        if mc_now >= mc_max:
1692 ec0292f1 Iustin Pop
          break
1693 ec0292f1 Iustin Pop
        node = self._config_data.nodes[name]
1694 44485f49 Guido Trotter
        if (node.master_candidate or node.offline or node.drained or
1695 490acd18 Iustin Pop
            node.name in exceptions or not node.master_capable):
1696 ec0292f1 Iustin Pop
          continue
1697 ee513a66 Iustin Pop
        mod_list.append(node)
1698 ec0292f1 Iustin Pop
        node.master_candidate = True
1699 ec0292f1 Iustin Pop
        node.serial_no += 1
1700 ec0292f1 Iustin Pop
        mc_now += 1
1701 ec0292f1 Iustin Pop
      if mc_now != mc_max:
1702 ec0292f1 Iustin Pop
        # this should not happen
1703 ec0292f1 Iustin Pop
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1704 ec0292f1 Iustin Pop
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1705 ec0292f1 Iustin Pop
      if mod_list:
1706 ec0292f1 Iustin Pop
        self._config_data.cluster.serial_no += 1
1707 ec0292f1 Iustin Pop
        self._WriteConfig()
1708 ec0292f1 Iustin Pop
1709 ec0292f1 Iustin Pop
    return mod_list
1710 ec0292f1 Iustin Pop
1711 190e3cb6 Guido Trotter
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1712 190e3cb6 Guido Trotter
    """Add a given node to the specified group.
1713 190e3cb6 Guido Trotter

1714 190e3cb6 Guido Trotter
    """
1715 190e3cb6 Guido Trotter
    if nodegroup_uuid not in self._config_data.nodegroups:
1716 190e3cb6 Guido Trotter
      # This can happen if a node group gets deleted between its lookup and
1717 190e3cb6 Guido Trotter
      # when we're adding the first node to it, since we don't keep a lock in
1718 190e3cb6 Guido Trotter
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1719 190e3cb6 Guido Trotter
      # is not found anymore.
1720 f936c153 Iustin Pop
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1721 190e3cb6 Guido Trotter
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1722 190e3cb6 Guido Trotter
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1723 190e3cb6 Guido Trotter
1724 190e3cb6 Guido Trotter
  def _UnlockedRemoveNodeFromGroup(self, node):
1725 190e3cb6 Guido Trotter
    """Remove a given node from its group.
1726 190e3cb6 Guido Trotter

1727 190e3cb6 Guido Trotter
    """
1728 f936c153 Iustin Pop
    nodegroup = node.group
1729 190e3cb6 Guido Trotter
    if nodegroup not in self._config_data.nodegroups:
1730 f936c153 Iustin Pop
      logging.warning("Warning: node '%s' has unknown node group '%s'"
1731 190e3cb6 Guido Trotter
                      " (while being removed from it)", node.name, nodegroup)
1732 190e3cb6 Guido Trotter
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1733 190e3cb6 Guido Trotter
    if node.name not in nodegroup_obj.members:
1734 f936c153 Iustin Pop
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
1735 190e3cb6 Guido Trotter
                      " (while being removed from it)", node.name, nodegroup)
1736 190e3cb6 Guido Trotter
    else:
1737 190e3cb6 Guido Trotter
      nodegroup_obj.members.remove(node.name)
1738 190e3cb6 Guido Trotter
1739 54c31fd3 Michael Hanselmann
  @locking.ssynchronized(_config_lock)
1740 54c31fd3 Michael Hanselmann
  def AssignGroupNodes(self, mods):
1741 54c31fd3 Michael Hanselmann
    """Changes the group of a number of nodes.
1742 54c31fd3 Michael Hanselmann

1743 54c31fd3 Michael Hanselmann
    @type mods: list of tuples; (node name, new group UUID)
1744 1d4930b9 Michael Hanselmann
    @param mods: Node membership modifications
1745 54c31fd3 Michael Hanselmann

1746 54c31fd3 Michael Hanselmann
    """
1747 54c31fd3 Michael Hanselmann
    groups = self._config_data.nodegroups
1748 54c31fd3 Michael Hanselmann
    nodes = self._config_data.nodes
1749 54c31fd3 Michael Hanselmann
1750 54c31fd3 Michael Hanselmann
    resmod = []
1751 54c31fd3 Michael Hanselmann
1752 54c31fd3 Michael Hanselmann
    # Try to resolve names/UUIDs first
1753 54c31fd3 Michael Hanselmann
    for (node_name, new_group_uuid) in mods:
1754 54c31fd3 Michael Hanselmann
      try:
1755 54c31fd3 Michael Hanselmann
        node = nodes[node_name]
1756 54c31fd3 Michael Hanselmann
      except KeyError:
1757 54c31fd3 Michael Hanselmann
        raise errors.ConfigurationError("Unable to find node '%s'" % node_name)
1758 54c31fd3 Michael Hanselmann
1759 54c31fd3 Michael Hanselmann
      if node.group == new_group_uuid:
1760 54c31fd3 Michael Hanselmann
        # Node is being assigned to its current group
1761 54c31fd3 Michael Hanselmann
        logging.debug("Node '%s' was assigned to its current group (%s)",
1762 54c31fd3 Michael Hanselmann
                      node_name, node.group)
1763 54c31fd3 Michael Hanselmann
        continue
1764 54c31fd3 Michael Hanselmann
1765 54c31fd3 Michael Hanselmann
      # Try to find current group of node
1766 54c31fd3 Michael Hanselmann
      try:
1767 54c31fd3 Michael Hanselmann
        old_group = groups[node.group]
1768 54c31fd3 Michael Hanselmann
      except KeyError:
1769 54c31fd3 Michael Hanselmann
        raise errors.ConfigurationError("Unable to find old group '%s'" %
1770 54c31fd3 Michael Hanselmann
                                        node.group)
1771 54c31fd3 Michael Hanselmann
1772 54c31fd3 Michael Hanselmann
      # Try to find new group for node
1773 54c31fd3 Michael Hanselmann
      try:
1774 54c31fd3 Michael Hanselmann
        new_group = groups[new_group_uuid]
1775 54c31fd3 Michael Hanselmann
      except KeyError:
1776 54c31fd3 Michael Hanselmann
        raise errors.ConfigurationError("Unable to find new group '%s'" %
1777 54c31fd3 Michael Hanselmann
                                        new_group_uuid)
1778 54c31fd3 Michael Hanselmann
1779 54c31fd3 Michael Hanselmann
      assert node.name in old_group.members, \
1780 54c31fd3 Michael Hanselmann
        ("Inconsistent configuration: node '%s' not listed in members for its"
1781 54c31fd3 Michael Hanselmann
         " old group '%s'" % (node.name, old_group.uuid))
1782 54c31fd3 Michael Hanselmann
      assert node.name not in new_group.members, \
1783 54c31fd3 Michael Hanselmann
        ("Inconsistent configuration: node '%s' already listed in members for"
1784 54c31fd3 Michael Hanselmann
         " its new group '%s'" % (node.name, new_group.uuid))
1785 54c31fd3 Michael Hanselmann
1786 54c31fd3 Michael Hanselmann
      resmod.append((node, old_group, new_group))
1787 54c31fd3 Michael Hanselmann
1788 54c31fd3 Michael Hanselmann
    # Apply changes
1789 54c31fd3 Michael Hanselmann
    for (node, old_group, new_group) in resmod:
1790 54c31fd3 Michael Hanselmann
      assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \
1791 54c31fd3 Michael Hanselmann
        "Assigning to current group is not possible"
1792 54c31fd3 Michael Hanselmann
1793 54c31fd3 Michael Hanselmann
      node.group = new_group.uuid
1794 54c31fd3 Michael Hanselmann
1795 54c31fd3 Michael Hanselmann
      # Update members of involved groups
1796 54c31fd3 Michael Hanselmann
      if node.name in old_group.members:
1797 54c31fd3 Michael Hanselmann
        old_group.members.remove(node.name)
1798 54c31fd3 Michael Hanselmann
      if node.name not in new_group.members:
1799 54c31fd3 Michael Hanselmann
        new_group.members.append(node.name)
1800 54c31fd3 Michael Hanselmann
1801 54c31fd3 Michael Hanselmann
    # Update timestamps and serials (only once per node/group object)
1802 54c31fd3 Michael Hanselmann
    now = time.time()
1803 75191077 Michael Hanselmann
    for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142
1804 54c31fd3 Michael Hanselmann
      obj.serial_no += 1
1805 54c31fd3 Michael Hanselmann
      obj.mtime = now
1806 54c31fd3 Michael Hanselmann
1807 54c31fd3 Michael Hanselmann
    # Force ssconf update
1808 54c31fd3 Michael Hanselmann
    self._config_data.cluster.serial_no += 1
1809 54c31fd3 Michael Hanselmann
1810 54c31fd3 Michael Hanselmann
    self._WriteConfig()
1811 54c31fd3 Michael Hanselmann
1812 a8083063 Iustin Pop
  def _BumpSerialNo(self):
1813 a8083063 Iustin Pop
    """Bump up the serial number of the config.
1814 a8083063 Iustin Pop

1815 a8083063 Iustin Pop
    """
1816 9d38c6e1 Iustin Pop
    self._config_data.serial_no += 1
1817 d693c864 Iustin Pop
    self._config_data.mtime = time.time()
1818 a8083063 Iustin Pop
1819 76d5d3a3 Iustin Pop
  def _AllUUIDObjects(self):
1820 76d5d3a3 Iustin Pop
    """Returns all objects with uuid attributes.
1821 76d5d3a3 Iustin Pop

1822 76d5d3a3 Iustin Pop
    """
1823 76d5d3a3 Iustin Pop
    return (self._config_data.instances.values() +
1824 76d5d3a3 Iustin Pop
            self._config_data.nodes.values() +
1825 3df43542 Guido Trotter
            self._config_data.nodegroups.values() +
1826 76d5d3a3 Iustin Pop
            [self._config_data.cluster])
1827 76d5d3a3 Iustin Pop
1828 eb180fe2 Iustin Pop
  def _OpenConfig(self, accept_foreign):
1829 a8083063 Iustin Pop
    """Read the config data from disk.
1830 a8083063 Iustin Pop

1831 a8083063 Iustin Pop
    """
1832 13998ef2 Michael Hanselmann
    raw_data = utils.ReadFile(self._cfg_file)
1833 13998ef2 Michael Hanselmann
1834 a8083063 Iustin Pop
    try:
1835 13998ef2 Michael Hanselmann
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1836 13998ef2 Michael Hanselmann
    except Exception, err:
1837 13998ef2 Michael Hanselmann
      raise errors.ConfigurationError(err)
1838 5b263ed7 Michael Hanselmann
1839 5b263ed7 Michael Hanselmann
    # Make sure the configuration has the right version
1840 5b263ed7 Michael Hanselmann
    _ValidateConfig(data)
1841 5b263ed7 Michael Hanselmann
1842 3ccb3a64 Michael Hanselmann
    if (not hasattr(data, "cluster") or
1843 3ccb3a64 Michael Hanselmann
        not hasattr(data.cluster, "rsahostkeypub")):
1844 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Incomplete configuration"
1845 243cdbcc Michael Hanselmann
                                      " (missing cluster.rsahostkeypub)")
1846 90d726a8 Iustin Pop
1847 eb180fe2 Iustin Pop
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
1848 eb180fe2 Iustin Pop
      msg = ("The configuration denotes node %s as master, while my"
1849 eb180fe2 Iustin Pop
             " hostname is %s; opening a foreign configuration is only"
1850 eb180fe2 Iustin Pop
             " possible in accept_foreign mode" %
1851 eb180fe2 Iustin Pop
             (data.cluster.master_node, self._my_hostname))
1852 eb180fe2 Iustin Pop
      raise errors.ConfigurationError(msg)
1853 eb180fe2 Iustin Pop
1854 90d726a8 Iustin Pop
    # Upgrade configuration if needed
1855 90d726a8 Iustin Pop
    data.UpgradeConfig()
1856 90d726a8 Iustin Pop
1857 a8083063 Iustin Pop
    self._config_data = data
1858 3c7f6c44 Iustin Pop
    # reset the last serial as -1 so that the next write will cause
1859 0779e3aa Iustin Pop
    # ssconf update
1860 0779e3aa Iustin Pop
    self._last_cluster_serial = -1
1861 a8083063 Iustin Pop
1862 76d5d3a3 Iustin Pop
    # And finally run our (custom) config upgrade sequence
1863 76d5d3a3 Iustin Pop
    self._UpgradeConfig()
1864 76d5d3a3 Iustin Pop
1865 bd407597 Iustin Pop
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
1866 bd407597 Iustin Pop
1867 76d5d3a3 Iustin Pop
  def _UpgradeConfig(self):
1868 76d5d3a3 Iustin Pop
    """Run upgrade steps that cannot be done purely in the objects.
1869 76d5d3a3 Iustin Pop

1870 76d5d3a3 Iustin Pop
    This is because some data elements need uniqueness across the
1871 76d5d3a3 Iustin Pop
    whole configuration, etc.
1872 76d5d3a3 Iustin Pop

1873 111c4e2f Guido Trotter
    @warning: this function will call L{_WriteConfig()}, but also
1874 111c4e2f Guido Trotter
        L{DropECReservations} so it needs to be called only from a
1875 111c4e2f Guido Trotter
        "safe" place (the constructor). If one wanted to call it with
1876 111c4e2f Guido Trotter
        the lock held, a DropECReservationUnlocked would need to be
1877 111c4e2f Guido Trotter
        created first, to avoid causing deadlock.
1878 76d5d3a3 Iustin Pop

1879 76d5d3a3 Iustin Pop
    """
1880 76d5d3a3 Iustin Pop
    modified = False
1881 76d5d3a3 Iustin Pop
    for item in self._AllUUIDObjects():
1882 76d5d3a3 Iustin Pop
      if item.uuid is None:
1883 4fae38c5 Guido Trotter
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1884 76d5d3a3 Iustin Pop
        modified = True
1885 f9e81396 Guido Trotter
    if not self._config_data.nodegroups:
1886 75cf411a Adeodato Simo
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
1887 75cf411a Adeodato Simo
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
1888 75cf411a Adeodato Simo
                                            members=[])
1889 e11a1b77 Adeodato Simo
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
1890 f9e81396 Guido Trotter
      modified = True
1891 190e3cb6 Guido Trotter
    for node in self._config_data.nodes.values():
1892 f936c153 Iustin Pop
      if not node.group:
1893 f936c153 Iustin Pop
        node.group = self.LookupNodeGroup(None)
1894 190e3cb6 Guido Trotter
        modified = True
1895 190e3cb6 Guido Trotter
      # This is technically *not* an upgrade, but needs to be done both when
1896 190e3cb6 Guido Trotter
      # nodegroups are being added, and upon normally loading the config,
1897 190e3cb6 Guido Trotter
      # because the members list of a node group is discarded upon
1898 190e3cb6 Guido Trotter
      # serializing/deserializing the object.
1899 f936c153 Iustin Pop
      self._UnlockedAddNodeToGroup(node.name, node.group)
1900 76d5d3a3 Iustin Pop
    if modified:
1901 76d5d3a3 Iustin Pop
      self._WriteConfig()
1902 4fae38c5 Guido Trotter
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
1903 4fae38c5 Guido Trotter
      # only called at config init time, without the lock held
1904 4fae38c5 Guido Trotter
      self.DropECReservations(_UPGRADE_CONFIG_JID)
1905 4fae38c5 Guido Trotter
1906 a4eae71f Michael Hanselmann
  def _DistributeConfig(self, feedback_fn):
1907 a8083063 Iustin Pop
    """Distribute the configuration to the other nodes.
1908 a8083063 Iustin Pop

1909 a8083063 Iustin Pop
    Currently, this only copies the configuration file. In the future,
1910 a8083063 Iustin Pop
    it could be used to encapsulate the 2/3-phase update mechanism.
1911 a8083063 Iustin Pop

1912 a8083063 Iustin Pop
    """
1913 a8083063 Iustin Pop
    if self._offline:
1914 a8083063 Iustin Pop
      return True
1915 a4eae71f Michael Hanselmann
1916 a8083063 Iustin Pop
    bad = False
1917 a8083063 Iustin Pop
1918 6a5b8b4b Iustin Pop
    node_list = []
1919 6a5b8b4b Iustin Pop
    addr_list = []
1920 6a5b8b4b Iustin Pop
    myhostname = self._my_hostname
1921 6b294c53 Iustin Pop
    # we can skip checking whether _UnlockedGetNodeInfo returns None
1922 6b294c53 Iustin Pop
    # since the node list comes from _UnlocketGetNodeList, and we are
1923 6b294c53 Iustin Pop
    # called with the lock held, so no modifications should take place
1924 6b294c53 Iustin Pop
    # in between
1925 6a5b8b4b Iustin Pop
    for node_name in self._UnlockedGetNodeList():
1926 6a5b8b4b Iustin Pop
      if node_name == myhostname:
1927 6a5b8b4b Iustin Pop
        continue
1928 6a5b8b4b Iustin Pop
      node_info = self._UnlockedGetNodeInfo(node_name)
1929 6a5b8b4b Iustin Pop
      if not node_info.master_candidate:
1930 6a5b8b4b Iustin Pop
        continue
1931 6a5b8b4b Iustin Pop
      node_list.append(node_info.name)
1932 6a5b8b4b Iustin Pop
      addr_list.append(node_info.primary_ip)
1933 6b294c53 Iustin Pop
1934 415a7304 Michael Hanselmann
    # TODO: Use dedicated resolver talking to config writer for name resolution
1935 415a7304 Michael Hanselmann
    result = \
1936 b2acdbdc Michael Hanselmann
      self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file)
1937 1b54fc6c Guido Trotter
    for to_node, to_result in result.items():
1938 3cebe102 Michael Hanselmann
      msg = to_result.fail_msg
1939 1b54fc6c Guido Trotter
      if msg:
1940 1b54fc6c Guido Trotter
        msg = ("Copy of file %s to node %s failed: %s" %
1941 dd7db360 Iustin Pop
               (self._cfg_file, to_node, msg))
1942 1b54fc6c Guido Trotter
        logging.error(msg)
1943 a4eae71f Michael Hanselmann
1944 a4eae71f Michael Hanselmann
        if feedback_fn:
1945 a4eae71f Michael Hanselmann
          feedback_fn(msg)
1946 a4eae71f Michael Hanselmann
1947 a8083063 Iustin Pop
        bad = True
1948 a4eae71f Michael Hanselmann
1949 a8083063 Iustin Pop
    return not bad
1950 a8083063 Iustin Pop
1951 a4eae71f Michael Hanselmann
  def _WriteConfig(self, destination=None, feedback_fn=None):
1952 a8083063 Iustin Pop
    """Write the configuration data to persistent storage.
1953 a8083063 Iustin Pop

1954 a8083063 Iustin Pop
    """
1955 a4eae71f Michael Hanselmann
    assert feedback_fn is None or callable(feedback_fn)
1956 a4eae71f Michael Hanselmann
1957 d2231b8c Iustin Pop
    # Warn on config errors, but don't abort the save - the
1958 d2231b8c Iustin Pop
    # configuration has already been modified, and we can't revert;
1959 d2231b8c Iustin Pop
    # the best we can do is to warn the user and save as is, leaving
1960 d2231b8c Iustin Pop
    # recovery to the user
1961 4a89c54a Iustin Pop
    config_errors = self._UnlockedVerifyConfig()
1962 4a89c54a Iustin Pop
    if config_errors:
1963 d2231b8c Iustin Pop
      errmsg = ("Configuration data is not consistent: %s" %
1964 1f864b60 Iustin Pop
                (utils.CommaJoin(config_errors)))
1965 d2231b8c Iustin Pop
      logging.critical(errmsg)
1966 d2231b8c Iustin Pop
      if feedback_fn:
1967 d2231b8c Iustin Pop
        feedback_fn(errmsg)
1968 d2231b8c Iustin Pop
1969 a8083063 Iustin Pop
    if destination is None:
1970 a8083063 Iustin Pop
      destination = self._cfg_file
1971 a8083063 Iustin Pop
    self._BumpSerialNo()
1972 8d14b30d Iustin Pop
    txt = serializer.Dump(self._config_data.ToDict())
1973 13998ef2 Michael Hanselmann
1974 e60c73a1 René Nussbaumer
    getents = self._getents()
1975 bd407597 Iustin Pop
    try:
1976 bd407597 Iustin Pop
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
1977 bd407597 Iustin Pop
                               close=False, gid=getents.confd_gid, mode=0640)
1978 bd407597 Iustin Pop
    except errors.LockError:
1979 bd407597 Iustin Pop
      raise errors.ConfigurationError("The configuration file has been"
1980 bd407597 Iustin Pop
                                      " modified since the last write, cannot"
1981 bd407597 Iustin Pop
                                      " update")
1982 bd407597 Iustin Pop
    try:
1983 bd407597 Iustin Pop
      self._cfg_id = utils.GetFileID(fd=fd)
1984 bd407597 Iustin Pop
    finally:
1985 bd407597 Iustin Pop
      os.close(fd)
1986 13998ef2 Michael Hanselmann
1987 14e15659 Iustin Pop
    self.write_count += 1
1988 3d3a04bc Iustin Pop
1989 f56618e0 Iustin Pop
    # and redistribute the config file to master candidates
1990 a4eae71f Michael Hanselmann
    self._DistributeConfig(feedback_fn)
1991 a8083063 Iustin Pop
1992 54d1a06e Michael Hanselmann
    # Write ssconf files on all nodes (including locally)
1993 0779e3aa Iustin Pop
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
1994 d9a855f1 Michael Hanselmann
      if not self._offline:
1995 b2acdbdc Michael Hanselmann
        result = self._GetRpc(None).call_write_ssconf_files(
1996 6819dc49 Iustin Pop
          self._UnlockedGetOnlineNodeList(),
1997 e1e75d00 Iustin Pop
          self._UnlockedGetSsconfValues())
1998 a4eae71f Michael Hanselmann
1999 e1e75d00 Iustin Pop
        for nname, nresu in result.items():
2000 3cebe102 Michael Hanselmann
          msg = nresu.fail_msg
2001 e1e75d00 Iustin Pop
          if msg:
2002 a4eae71f Michael Hanselmann
            errmsg = ("Error while uploading ssconf files to"
2003 a4eae71f Michael Hanselmann
                      " node %s: %s" % (nname, msg))
2004 a4eae71f Michael Hanselmann
            logging.warning(errmsg)
2005 a4eae71f Michael Hanselmann
2006 a4eae71f Michael Hanselmann
            if feedback_fn:
2007 a4eae71f Michael Hanselmann
              feedback_fn(errmsg)
2008 a4eae71f Michael Hanselmann
2009 0779e3aa Iustin Pop
      self._last_cluster_serial = self._config_data.cluster.serial_no
2010 54d1a06e Michael Hanselmann
2011 03d1dba2 Michael Hanselmann
  def _UnlockedGetSsconfValues(self):
2012 054596f0 Iustin Pop
    """Return the values needed by ssconf.
2013 054596f0 Iustin Pop

2014 054596f0 Iustin Pop
    @rtype: dict
2015 054596f0 Iustin Pop
    @return: a dictionary with keys the ssconf names and values their
2016 054596f0 Iustin Pop
        associated value
2017 054596f0 Iustin Pop

2018 054596f0 Iustin Pop
    """
2019 a3316e4a Iustin Pop
    fn = "\n".join
2020 81a49123 Iustin Pop
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
2021 a3316e4a Iustin Pop
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
2022 a3316e4a Iustin Pop
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
2023 c3029d0a Luca Bigliardi
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
2024 5909fb97 Luca Bigliardi
                    for ninfo in node_info]
2025 c3029d0a Luca Bigliardi
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
2026 5909fb97 Luca Bigliardi
                    for ninfo in node_info]
2027 a3316e4a Iustin Pop
2028 81a49123 Iustin Pop
    instance_data = fn(instance_names)
2029 a3316e4a Iustin Pop
    off_data = fn(node.name for node in node_info if node.offline)
2030 81a49123 Iustin Pop
    on_data = fn(node.name for node in node_info if not node.offline)
2031 a3316e4a Iustin Pop
    mc_data = fn(node.name for node in node_info if node.master_candidate)
2032 8113a52e Luca Bigliardi
    mc_ips_data = fn(node.primary_ip for node in node_info
2033 8113a52e Luca Bigliardi
                     if node.master_candidate)
2034 a3316e4a Iustin Pop
    node_data = fn(node_names)
2035 f9780ccd Luca Bigliardi
    node_pri_ips_data = fn(node_pri_ips)
2036 f9780ccd Luca Bigliardi
    node_snd_ips_data = fn(node_snd_ips)
2037 f56618e0 Iustin Pop
2038 054596f0 Iustin Pop
    cluster = self._config_data.cluster
2039 5d60b3bd Iustin Pop
    cluster_tags = fn(cluster.GetTags())
2040 4f7a6a10 Iustin Pop
2041 4f7a6a10 Iustin Pop
    hypervisor_list = fn(cluster.enabled_hypervisors)
2042 4f7a6a10 Iustin Pop
2043 0fbae49a Balazs Lecz
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
2044 0fbae49a Balazs Lecz
2045 6f076453 Guido Trotter
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
2046 6f076453 Guido Trotter
                  self._config_data.nodegroups.values()]
2047 6f076453 Guido Trotter
    nodegroups_data = fn(utils.NiceSort(nodegroups))
2048 6f076453 Guido Trotter
2049 2afc9238 Iustin Pop
    ssconf_values = {
2050 054596f0 Iustin Pop
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
2051 5d60b3bd Iustin Pop
      constants.SS_CLUSTER_TAGS: cluster_tags,
2052 054596f0 Iustin Pop
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
2053 4b97f902 Apollon Oikonomopoulos
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
2054 a3316e4a Iustin Pop
      constants.SS_MASTER_CANDIDATES: mc_data,
2055 8113a52e Luca Bigliardi
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
2056 054596f0 Iustin Pop
      constants.SS_MASTER_IP: cluster.master_ip,
2057 054596f0 Iustin Pop
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
2058 5a8648eb Andrea Spadaccini
      constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
2059 054596f0 Iustin Pop
      constants.SS_MASTER_NODE: cluster.master_node,
2060 a3316e4a Iustin Pop
      constants.SS_NODE_LIST: node_data,
2061 f9780ccd Luca Bigliardi
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
2062 f9780ccd Luca Bigliardi
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
2063 a3316e4a Iustin Pop
      constants.SS_OFFLINE_NODES: off_data,
2064 81a49123 Iustin Pop
      constants.SS_ONLINE_NODES: on_data,
2065 868a98ca Manuel Franceschini
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
2066 81a49123 Iustin Pop
      constants.SS_INSTANCE_LIST: instance_data,
2067 8a113c7a Iustin Pop
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
2068 4f7a6a10 Iustin Pop
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
2069 5c465a95 Iustin Pop
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
2070 0fbae49a Balazs Lecz
      constants.SS_UID_POOL: uid_pool,
2071 6f076453 Guido Trotter
      constants.SS_NODEGROUPS: nodegroups_data,
2072 03d1dba2 Michael Hanselmann
      }
2073 2afc9238 Iustin Pop
    bad_values = [(k, v) for k, v in ssconf_values.items()
2074 2afc9238 Iustin Pop
                  if not isinstance(v, (str, basestring))]
2075 2afc9238 Iustin Pop
    if bad_values:
2076 2afc9238 Iustin Pop
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
2077 2afc9238 Iustin Pop
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
2078 2afc9238 Iustin Pop
                                      " values: %s" % err)
2079 2afc9238 Iustin Pop
    return ssconf_values
2080 03d1dba2 Michael Hanselmann
2081 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
2082 d367b66c Manuel Franceschini
  def GetSsconfValues(self):
2083 d367b66c Manuel Franceschini
    """Wrapper using lock around _UnlockedGetSsconf().
2084 d367b66c Manuel Franceschini

2085 d367b66c Manuel Franceschini
    """
2086 d367b66c Manuel Franceschini
    return self._UnlockedGetSsconfValues()
2087 d367b66c Manuel Franceschini
2088 d367b66c Manuel Franceschini
  @locking.ssynchronized(_config_lock, shared=1)
2089 a8083063 Iustin Pop
  def GetVGName(self):
2090 a8083063 Iustin Pop
    """Return the volume group name.
2091 a8083063 Iustin Pop

2092 a8083063 Iustin Pop
    """
2093 a8083063 Iustin Pop
    return self._config_data.cluster.volume_group_name
2094 a8083063 Iustin Pop
2095 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
2096 89ff8e15 Manuel Franceschini
  def SetVGName(self, vg_name):
2097 89ff8e15 Manuel Franceschini
    """Set the volume group name.
2098 89ff8e15 Manuel Franceschini

2099 89ff8e15 Manuel Franceschini
    """
2100 2d4011cd Manuel Franceschini
    self._config_data.cluster.volume_group_name = vg_name
2101 b9f72b4e Iustin Pop
    self._config_data.cluster.serial_no += 1
2102 89ff8e15 Manuel Franceschini
    self._WriteConfig()
2103 89ff8e15 Manuel Franceschini
2104 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
2105 9e33896b Luca Bigliardi
  def GetDRBDHelper(self):
2106 9e33896b Luca Bigliardi
    """Return DRBD usermode helper.
2107 9e33896b Luca Bigliardi

2108 9e33896b Luca Bigliardi
    """
2109 9e33896b Luca Bigliardi
    return self._config_data.cluster.drbd_usermode_helper
2110 9e33896b Luca Bigliardi
2111 9e33896b Luca Bigliardi
  @locking.ssynchronized(_config_lock)
2112 9e33896b Luca Bigliardi
  def SetDRBDHelper(self, drbd_helper):
2113 9e33896b Luca Bigliardi
    """Set DRBD usermode helper.
2114 9e33896b Luca Bigliardi

2115 9e33896b Luca Bigliardi
    """
2116 9e33896b Luca Bigliardi
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
2117 9e33896b Luca Bigliardi
    self._config_data.cluster.serial_no += 1
2118 9e33896b Luca Bigliardi
    self._WriteConfig()
2119 9e33896b Luca Bigliardi
2120 9e33896b Luca Bigliardi
  @locking.ssynchronized(_config_lock, shared=1)
2121 a8083063 Iustin Pop
  def GetMACPrefix(self):
2122 a8083063 Iustin Pop
    """Return the mac prefix.
2123 a8083063 Iustin Pop

2124 a8083063 Iustin Pop
    """
2125 a8083063 Iustin Pop
    return self._config_data.cluster.mac_prefix
2126 62779dd0 Iustin Pop
2127 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
2128 62779dd0 Iustin Pop
  def GetClusterInfo(self):
2129 5bbd3f7f Michael Hanselmann
    """Returns information about the cluster
2130 62779dd0 Iustin Pop

2131 c41eea6e Iustin Pop
    @rtype: L{objects.Cluster}
2132 c41eea6e Iustin Pop
    @return: the cluster object
2133 62779dd0 Iustin Pop

2134 62779dd0 Iustin Pop
    """
2135 62779dd0 Iustin Pop
    return self._config_data.cluster
2136 e00fb268 Iustin Pop
2137 51cb1581 Luca Bigliardi
  @locking.ssynchronized(_config_lock, shared=1)
2138 51cb1581 Luca Bigliardi
  def HasAnyDiskOfType(self, dev_type):
2139 51cb1581 Luca Bigliardi
    """Check if in there is at disk of the given type in the configuration.
2140 51cb1581 Luca Bigliardi

2141 51cb1581 Luca Bigliardi
    """
2142 51cb1581 Luca Bigliardi
    return self._config_data.HasAnyDiskOfType(dev_type)
2143 51cb1581 Luca Bigliardi
2144 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
2145 a4eae71f Michael Hanselmann
  def Update(self, target, feedback_fn):
2146 e00fb268 Iustin Pop
    """Notify function to be called after updates.
2147 e00fb268 Iustin Pop

2148 e00fb268 Iustin Pop
    This function must be called when an object (as returned by
2149 e00fb268 Iustin Pop
    GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
2150 e00fb268 Iustin Pop
    caller wants the modifications saved to the backing store. Note
2151 e00fb268 Iustin Pop
    that all modified objects will be saved, but the target argument
2152 e00fb268 Iustin Pop
    is the one the caller wants to ensure that it's saved.
2153 e00fb268 Iustin Pop

2154 c41eea6e Iustin Pop
    @param target: an instance of either L{objects.Cluster},
2155 c41eea6e Iustin Pop
        L{objects.Node} or L{objects.Instance} which is existing in
2156 c41eea6e Iustin Pop
        the cluster
2157 a4eae71f Michael Hanselmann
    @param feedback_fn: Callable feedback function
2158 c41eea6e Iustin Pop

2159 e00fb268 Iustin Pop
    """
2160 e00fb268 Iustin Pop
    if self._config_data is None:
2161 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Configuration file not read,"
2162 3ecf6786 Iustin Pop
                                   " cannot save.")
2163 f34901f8 Iustin Pop
    update_serial = False
2164 e00fb268 Iustin Pop
    if isinstance(target, objects.Cluster):
2165 e00fb268 Iustin Pop
      test = target == self._config_data.cluster
2166 e00fb268 Iustin Pop
    elif isinstance(target, objects.Node):
2167 e00fb268 Iustin Pop
      test = target in self._config_data.nodes.values()
2168 f34901f8 Iustin Pop
      update_serial = True
2169 e00fb268 Iustin Pop
    elif isinstance(target, objects.Instance):
2170 e00fb268 Iustin Pop
      test = target in self._config_data.instances.values()
2171 e11a1b77 Adeodato Simo
    elif isinstance(target, objects.NodeGroup):
2172 e11a1b77 Adeodato Simo
      test = target in self._config_data.nodegroups.values()
2173 e00fb268 Iustin Pop
    else:
2174 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
2175 3ecf6786 Iustin Pop
                                   " ConfigWriter.Update" % type(target))
2176 e00fb268 Iustin Pop
    if not test:
2177 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Configuration updated since object"
2178 3ecf6786 Iustin Pop
                                      " has been read or unknown object")
2179 f34901f8 Iustin Pop
    target.serial_no += 1
2180 d693c864 Iustin Pop
    target.mtime = now = time.time()
2181 f34901f8 Iustin Pop
2182 cff4c037 Iustin Pop
    if update_serial:
2183 f34901f8 Iustin Pop
      # for node updates, we need to increase the cluster serial too
2184 f34901f8 Iustin Pop
      self._config_data.cluster.serial_no += 1
2185 d693c864 Iustin Pop
      self._config_data.cluster.mtime = now
2186 b989e85d Iustin Pop
2187 61cf6b5e Iustin Pop
    if isinstance(target, objects.Instance):
2188 61cf6b5e Iustin Pop
      self._UnlockedReleaseDRBDMinors(target.name)
2189 61cf6b5e Iustin Pop
2190 a4eae71f Michael Hanselmann
    self._WriteConfig(feedback_fn=feedback_fn)
2191 73064714 Guido Trotter
2192 73064714 Guido Trotter
  @locking.ssynchronized(_config_lock)
2193 73064714 Guido Trotter
  def DropECReservations(self, ec_id):
2194 73064714 Guido Trotter
    """Drop per-execution-context reservations
2195 73064714 Guido Trotter

2196 73064714 Guido Trotter
    """
2197 d8aee57e Iustin Pop
    for rm in self._all_rms:
2198 d8aee57e Iustin Pop
      rm.DropECReservations(ec_id)