Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 45df0793

History | View | Annotate | Download (64.8 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 075b62ca Iustin Pop
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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 d367b66c Manuel Franceschini
# pylint: disable-msg=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 a8083063 Iustin Pop
42 a8083063 Iustin Pop
from ganeti import errors
43 f78ede4e Guido Trotter
from ganeti import locking
44 a8083063 Iustin Pop
from ganeti import utils
45 a8083063 Iustin Pop
from ganeti import constants
46 a8083063 Iustin Pop
from ganeti import rpc
47 a8083063 Iustin Pop
from ganeti import objects
48 8d14b30d Iustin Pop
from ganeti import serializer
49 0fbae49a Balazs Lecz
from ganeti import uidpool
50 a744b676 Manuel Franceschini
from ganeti import netutils
51 e60c73a1 René Nussbaumer
from ganeti import runtime
52 243cdbcc Michael Hanselmann
53 243cdbcc Michael Hanselmann
54 7f93570a Iustin Pop
_config_lock = locking.SharedLock("ConfigWriter")
55 f78ede4e Guido Trotter
56 4fae38c5 Guido Trotter
# job id used for resource management at config upgrade time
57 8d9c3bef Michael Hanselmann
_UPGRADE_CONFIG_JID = "jid-cfg-upgrade"
58 4fae38c5 Guido Trotter
59 f78ede4e Guido Trotter
60 5b263ed7 Michael Hanselmann
def _ValidateConfig(data):
61 c41eea6e Iustin Pop
  """Verifies that a configuration objects looks valid.
62 c41eea6e Iustin Pop

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

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

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

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

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

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

131 fe698b38 Michael Hanselmann
  """
132 fe698b38 Michael Hanselmann
  return utils.MatchNameComponent(short_name, names, case_sensitive=False)
133 fe698b38 Michael Hanselmann
134 fe698b38 Michael Hanselmann
135 a8083063 Iustin Pop
class ConfigWriter:
136 098c0958 Michael Hanselmann
  """The interface to the cluster configuration.
137 a8083063 Iustin Pop

138 d8aee57e Iustin Pop
  @ivar _temporary_lvs: reservation manager for temporary LVs
139 d8aee57e Iustin Pop
  @ivar _all_rms: a list of all temporary reservation managers
140 d8aee57e Iustin Pop

141 098c0958 Michael Hanselmann
  """
142 eb180fe2 Iustin Pop
  def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts,
143 eb180fe2 Iustin Pop
               accept_foreign=False):
144 14e15659 Iustin Pop
    self.write_count = 0
145 f78ede4e Guido Trotter
    self._lock = _config_lock
146 a8083063 Iustin Pop
    self._config_data = None
147 a8083063 Iustin Pop
    self._offline = offline
148 a8083063 Iustin Pop
    if cfg_file is None:
149 a8083063 Iustin Pop
      self._cfg_file = constants.CLUSTER_CONF_FILE
150 a8083063 Iustin Pop
    else:
151 a8083063 Iustin Pop
      self._cfg_file = cfg_file
152 e60c73a1 René Nussbaumer
    self._getents = _getents
153 4fae38c5 Guido Trotter
    self._temporary_ids = TemporaryReservationManager()
154 a81c53c9 Iustin Pop
    self._temporary_drbds = {}
155 36b66e6e Guido Trotter
    self._temporary_macs = TemporaryReservationManager()
156 afa1386e Guido Trotter
    self._temporary_secrets = TemporaryReservationManager()
157 d8aee57e Iustin Pop
    self._temporary_lvs = TemporaryReservationManager()
158 d8aee57e Iustin Pop
    self._all_rms = [self._temporary_ids, self._temporary_macs,
159 d8aee57e Iustin Pop
                     self._temporary_secrets, self._temporary_lvs]
160 89e1fc26 Iustin Pop
    # Note: in order to prevent errors when resolving our name in
161 89e1fc26 Iustin Pop
    # _DistributeConfig, we compute it here once and reuse it; it's
162 89e1fc26 Iustin Pop
    # better to raise an error before starting to modify the config
163 89e1fc26 Iustin Pop
    # file than after it was modified
164 b705c7a6 Manuel Franceschini
    self._my_hostname = netutils.Hostname.GetSysName()
165 3c7f6c44 Iustin Pop
    self._last_cluster_serial = -1
166 bd407597 Iustin Pop
    self._cfg_id = None
167 eb180fe2 Iustin Pop
    self._OpenConfig(accept_foreign)
168 a8083063 Iustin Pop
169 a8083063 Iustin Pop
  # this method needs to be static, so that we can call it on the class
170 a8083063 Iustin Pop
  @staticmethod
171 a8083063 Iustin Pop
  def IsCluster():
172 a8083063 Iustin Pop
    """Check if the cluster is configured.
173 a8083063 Iustin Pop

174 a8083063 Iustin Pop
    """
175 a8083063 Iustin Pop
    return os.path.exists(constants.CLUSTER_CONF_FILE)
176 a8083063 Iustin Pop
177 36b66e6e Guido Trotter
  def _GenerateOneMAC(self):
178 36b66e6e Guido Trotter
    """Generate one mac address
179 36b66e6e Guido Trotter

180 36b66e6e Guido Trotter
    """
181 36b66e6e Guido Trotter
    prefix = self._config_data.cluster.mac_prefix
182 36b66e6e Guido Trotter
    byte1 = random.randrange(0, 256)
183 36b66e6e Guido Trotter
    byte2 = random.randrange(0, 256)
184 36b66e6e Guido Trotter
    byte3 = random.randrange(0, 256)
185 36b66e6e Guido Trotter
    mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
186 36b66e6e Guido Trotter
    return mac
187 36b66e6e Guido Trotter
188 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
189 5768e6a6 René Nussbaumer
  def GetNdParams(self, node):
190 5768e6a6 René Nussbaumer
    """Get the node params populated with cluster defaults.
191 5768e6a6 René Nussbaumer

192 5768e6a6 René Nussbaumer
    @type node: L{object.Node}
193 5768e6a6 René Nussbaumer
    @param node: The node we want to know the params for
194 5768e6a6 René Nussbaumer
    @return: A dict with the filled in node params
195 5768e6a6 René Nussbaumer

196 5768e6a6 René Nussbaumer
    """
197 5768e6a6 René Nussbaumer
    nodegroup = self._UnlockedGetNodeGroup(node.group)
198 5768e6a6 René Nussbaumer
    return self._config_data.cluster.FillND(node, nodegroup)
199 5768e6a6 René Nussbaumer
200 5768e6a6 René Nussbaumer
  @locking.ssynchronized(_config_lock, shared=1)
201 36b66e6e Guido Trotter
  def GenerateMAC(self, ec_id):
202 a8083063 Iustin Pop
    """Generate a MAC for an instance.
203 a8083063 Iustin Pop

204 a8083063 Iustin Pop
    This should check the current instances for duplicates.
205 a8083063 Iustin Pop

206 a8083063 Iustin Pop
    """
207 36b66e6e Guido Trotter
    existing = self._AllMACs()
208 36b66e6e Guido Trotter
    return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id)
209 a8083063 Iustin Pop
210 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
211 36b66e6e Guido Trotter
  def ReserveMAC(self, mac, ec_id):
212 36b66e6e Guido Trotter
    """Reserve a MAC for an instance.
213 1862d460 Alexander Schreiber

214 1862d460 Alexander Schreiber
    This only checks instances managed by this cluster, it does not
215 1862d460 Alexander Schreiber
    check for potential collisions elsewhere.
216 1862d460 Alexander Schreiber

217 1862d460 Alexander Schreiber
    """
218 1862d460 Alexander Schreiber
    all_macs = self._AllMACs()
219 36b66e6e Guido Trotter
    if mac in all_macs:
220 36b66e6e Guido Trotter
      raise errors.ReservationError("mac already in use")
221 36b66e6e Guido Trotter
    else:
222 8785b71b Apollon Oikonomopoulos
      self._temporary_macs.Reserve(ec_id, mac)
223 1862d460 Alexander Schreiber
224 f9518d38 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
225 d8aee57e Iustin Pop
  def ReserveLV(self, lv_name, ec_id):
226 d8aee57e Iustin Pop
    """Reserve an VG/LV pair for an instance.
227 d8aee57e Iustin Pop

228 d8aee57e Iustin Pop
    @type lv_name: string
229 d8aee57e Iustin Pop
    @param lv_name: the logical volume name to reserve
230 d8aee57e Iustin Pop

231 d8aee57e Iustin Pop
    """
232 d8aee57e Iustin Pop
    all_lvs = self._AllLVs()
233 d8aee57e Iustin Pop
    if lv_name in all_lvs:
234 d8aee57e Iustin Pop
      raise errors.ReservationError("LV already in use")
235 d8aee57e Iustin Pop
    else:
236 8785b71b Apollon Oikonomopoulos
      self._temporary_lvs.Reserve(ec_id, lv_name)
237 d8aee57e Iustin Pop
238 d8aee57e Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
239 afa1386e Guido Trotter
  def GenerateDRBDSecret(self, ec_id):
240 f9518d38 Iustin Pop
    """Generate a DRBD secret.
241 f9518d38 Iustin Pop

242 f9518d38 Iustin Pop
    This checks the current disks for duplicates.
243 f9518d38 Iustin Pop

244 f9518d38 Iustin Pop
    """
245 afa1386e Guido Trotter
    return self._temporary_secrets.Generate(self._AllDRBDSecrets(),
246 afa1386e Guido Trotter
                                            utils.GenerateSecret,
247 afa1386e Guido Trotter
                                            ec_id)
248 8d9c3bef Michael Hanselmann
249 34e54ebc Iustin Pop
  def _AllLVs(self):
250 923b1523 Iustin Pop
    """Compute the list of all LVs.
251 923b1523 Iustin Pop

252 923b1523 Iustin Pop
    """
253 923b1523 Iustin Pop
    lvnames = set()
254 923b1523 Iustin Pop
    for instance in self._config_data.instances.values():
255 923b1523 Iustin Pop
      node_data = instance.MapLVsByNode()
256 923b1523 Iustin Pop
      for lv_list in node_data.values():
257 923b1523 Iustin Pop
        lvnames.update(lv_list)
258 923b1523 Iustin Pop
    return lvnames
259 923b1523 Iustin Pop
260 34e54ebc Iustin Pop
  def _AllIDs(self, include_temporary):
261 34e54ebc Iustin Pop
    """Compute the list of all UUIDs and names we have.
262 34e54ebc Iustin Pop

263 34e54ebc Iustin Pop
    @type include_temporary: boolean
264 34e54ebc Iustin Pop
    @param include_temporary: whether to include the _temporary_ids set
265 34e54ebc Iustin Pop
    @rtype: set
266 34e54ebc Iustin Pop
    @return: a set of IDs
267 34e54ebc Iustin Pop

268 34e54ebc Iustin Pop
    """
269 34e54ebc Iustin Pop
    existing = set()
270 34e54ebc Iustin Pop
    if include_temporary:
271 4fae38c5 Guido Trotter
      existing.update(self._temporary_ids.GetReserved())
272 34e54ebc Iustin Pop
    existing.update(self._AllLVs())
273 34e54ebc Iustin Pop
    existing.update(self._config_data.instances.keys())
274 34e54ebc Iustin Pop
    existing.update(self._config_data.nodes.keys())
275 76d5d3a3 Iustin Pop
    existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid])
276 34e54ebc Iustin Pop
    return existing
277 34e54ebc Iustin Pop
278 4fae38c5 Guido Trotter
  def _GenerateUniqueID(self, ec_id):
279 430b923c Iustin Pop
    """Generate an unique UUID.
280 923b1523 Iustin Pop

281 923b1523 Iustin Pop
    This checks the current node, instances and disk names for
282 923b1523 Iustin Pop
    duplicates.
283 923b1523 Iustin Pop

284 c41eea6e Iustin Pop
    @rtype: string
285 c41eea6e Iustin Pop
    @return: the unique id
286 923b1523 Iustin Pop

287 923b1523 Iustin Pop
    """
288 4fae38c5 Guido Trotter
    existing = self._AllIDs(include_temporary=False)
289 4fae38c5 Guido Trotter
    return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id)
290 923b1523 Iustin Pop
291 430b923c Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
292 4fae38c5 Guido Trotter
  def GenerateUniqueID(self, ec_id):
293 430b923c Iustin Pop
    """Generate an unique ID.
294 430b923c Iustin Pop

295 430b923c Iustin Pop
    This is just a wrapper over the unlocked version.
296 430b923c Iustin Pop

297 4fae38c5 Guido Trotter
    @type ec_id: string
298 4fae38c5 Guido Trotter
    @param ec_id: unique id for the job to reserve the id to
299 34d657ba Iustin Pop

300 34d657ba Iustin Pop
    """
301 4fae38c5 Guido Trotter
    return self._GenerateUniqueID(ec_id)
302 34d657ba Iustin Pop
303 a8083063 Iustin Pop
  def _AllMACs(self):
304 a8083063 Iustin Pop
    """Return all MACs present in the config.
305 a8083063 Iustin Pop

306 c41eea6e Iustin Pop
    @rtype: list
307 c41eea6e Iustin Pop
    @return: the list of all MACs
308 c41eea6e Iustin Pop

309 a8083063 Iustin Pop
    """
310 a8083063 Iustin Pop
    result = []
311 a8083063 Iustin Pop
    for instance in self._config_data.instances.values():
312 a8083063 Iustin Pop
      for nic in instance.nics:
313 a8083063 Iustin Pop
        result.append(nic.mac)
314 a8083063 Iustin Pop
315 a8083063 Iustin Pop
    return result
316 a8083063 Iustin Pop
317 f9518d38 Iustin Pop
  def _AllDRBDSecrets(self):
318 f9518d38 Iustin Pop
    """Return all DRBD secrets present in the config.
319 f9518d38 Iustin Pop

320 c41eea6e Iustin Pop
    @rtype: list
321 c41eea6e Iustin Pop
    @return: the list of all DRBD secrets
322 c41eea6e Iustin Pop

323 f9518d38 Iustin Pop
    """
324 f9518d38 Iustin Pop
    def helper(disk, result):
325 f9518d38 Iustin Pop
      """Recursively gather secrets from this disk."""
326 f9518d38 Iustin Pop
      if disk.dev_type == constants.DT_DRBD8:
327 f9518d38 Iustin Pop
        result.append(disk.logical_id[5])
328 f9518d38 Iustin Pop
      if disk.children:
329 f9518d38 Iustin Pop
        for child in disk.children:
330 f9518d38 Iustin Pop
          helper(child, result)
331 f9518d38 Iustin Pop
332 f9518d38 Iustin Pop
    result = []
333 f9518d38 Iustin Pop
    for instance in self._config_data.instances.values():
334 f9518d38 Iustin Pop
      for disk in instance.disks:
335 f9518d38 Iustin Pop
        helper(disk, result)
336 f9518d38 Iustin Pop
337 f9518d38 Iustin Pop
    return result
338 f9518d38 Iustin Pop
339 4b98ac29 Iustin Pop
  def _CheckDiskIDs(self, disk, l_ids, p_ids):
340 4b98ac29 Iustin Pop
    """Compute duplicate disk IDs
341 4b98ac29 Iustin Pop

342 4b98ac29 Iustin Pop
    @type disk: L{objects.Disk}
343 4b98ac29 Iustin Pop
    @param disk: the disk at which to start searching
344 4b98ac29 Iustin Pop
    @type l_ids: list
345 4b98ac29 Iustin Pop
    @param l_ids: list of current logical ids
346 4b98ac29 Iustin Pop
    @type p_ids: list
347 4b98ac29 Iustin Pop
    @param p_ids: list of current physical ids
348 4b98ac29 Iustin Pop
    @rtype: list
349 4b98ac29 Iustin Pop
    @return: a list of error messages
350 4b98ac29 Iustin Pop

351 4b98ac29 Iustin Pop
    """
352 4b98ac29 Iustin Pop
    result = []
353 25ae22e4 Iustin Pop
    if disk.logical_id is not None:
354 25ae22e4 Iustin Pop
      if disk.logical_id in l_ids:
355 25ae22e4 Iustin Pop
        result.append("duplicate logical id %s" % str(disk.logical_id))
356 25ae22e4 Iustin Pop
      else:
357 25ae22e4 Iustin Pop
        l_ids.append(disk.logical_id)
358 25ae22e4 Iustin Pop
    if disk.physical_id is not None:
359 25ae22e4 Iustin Pop
      if disk.physical_id in p_ids:
360 25ae22e4 Iustin Pop
        result.append("duplicate physical id %s" % str(disk.physical_id))
361 25ae22e4 Iustin Pop
      else:
362 25ae22e4 Iustin Pop
        p_ids.append(disk.physical_id)
363 4b98ac29 Iustin Pop
364 4b98ac29 Iustin Pop
    if disk.children:
365 4b98ac29 Iustin Pop
      for child in disk.children:
366 4b98ac29 Iustin Pop
        result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
367 4b98ac29 Iustin Pop
    return result
368 4b98ac29 Iustin Pop
369 4a89c54a Iustin Pop
  def _UnlockedVerifyConfig(self):
370 a8efbb40 Iustin Pop
    """Verify function.
371 a8efbb40 Iustin Pop

372 4a89c54a Iustin Pop
    @rtype: list
373 4a89c54a Iustin Pop
    @return: a list of error messages; a non-empty list signifies
374 4a89c54a Iustin Pop
        configuration errors
375 4a89c54a Iustin Pop

376 a8083063 Iustin Pop
    """
377 26f2fd8d Iustin Pop
    # pylint: disable-msg=R0914
378 a8083063 Iustin Pop
    result = []
379 a8083063 Iustin Pop
    seen_macs = []
380 48ce9fd9 Iustin Pop
    ports = {}
381 a8083063 Iustin Pop
    data = self._config_data
382 7e01d204 Iustin Pop
    cluster = data.cluster
383 4b98ac29 Iustin Pop
    seen_lids = []
384 4b98ac29 Iustin Pop
    seen_pids = []
385 9a5fba23 Guido Trotter
386 9a5fba23 Guido Trotter
    # global cluster checks
387 7e01d204 Iustin Pop
    if not cluster.enabled_hypervisors:
388 9a5fba23 Guido Trotter
      result.append("enabled hypervisors list doesn't have any entries")
389 7e01d204 Iustin Pop
    invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
390 9a5fba23 Guido Trotter
    if invalid_hvs:
391 9a5fba23 Guido Trotter
      result.append("enabled hypervisors contains invalid entries: %s" %
392 9a5fba23 Guido Trotter
                    invalid_hvs)
393 7e01d204 Iustin Pop
    missing_hvp = (set(cluster.enabled_hypervisors) -
394 7e01d204 Iustin Pop
                   set(cluster.hvparams.keys()))
395 9f3ac970 Iustin Pop
    if missing_hvp:
396 9f3ac970 Iustin Pop
      result.append("hypervisor parameters missing for the enabled"
397 9f3ac970 Iustin Pop
                    " hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
398 9a5fba23 Guido Trotter
399 7e01d204 Iustin Pop
    if cluster.master_node not in data.nodes:
400 9a5fba23 Guido Trotter
      result.append("cluster has invalid primary node '%s'" %
401 7e01d204 Iustin Pop
                    cluster.master_node)
402 9a5fba23 Guido Trotter
403 26f2fd8d Iustin Pop
    def _helper(owner, attr, value, template):
404 26f2fd8d Iustin Pop
      try:
405 26f2fd8d Iustin Pop
        utils.ForceDictType(value, template)
406 26f2fd8d Iustin Pop
      except errors.GenericError, err:
407 26f2fd8d Iustin Pop
        result.append("%s has invalid %s: %s" % (owner, attr, err))
408 26f2fd8d Iustin Pop
409 26f2fd8d Iustin Pop
    def _helper_nic(owner, params):
410 26f2fd8d Iustin Pop
      try:
411 26f2fd8d Iustin Pop
        objects.NIC.CheckParameterSyntax(params)
412 26f2fd8d Iustin Pop
      except errors.ConfigurationError, err:
413 26f2fd8d Iustin Pop
        result.append("%s has invalid nicparams: %s" % (owner, err))
414 26f2fd8d Iustin Pop
415 26f2fd8d Iustin Pop
    # check cluster parameters
416 26f2fd8d Iustin Pop
    _helper("cluster", "beparams", cluster.SimpleFillBE({}),
417 26f2fd8d Iustin Pop
            constants.BES_PARAMETER_TYPES)
418 26f2fd8d Iustin Pop
    _helper("cluster", "nicparams", cluster.SimpleFillNIC({}),
419 26f2fd8d Iustin Pop
            constants.NICS_PARAMETER_TYPES)
420 26f2fd8d Iustin Pop
    _helper_nic("cluster", cluster.SimpleFillNIC({}))
421 26f2fd8d Iustin Pop
    _helper("cluster", "ndparams", cluster.SimpleFillND({}),
422 26f2fd8d Iustin Pop
            constants.NDS_PARAMETER_TYPES)
423 26f2fd8d Iustin Pop
424 9a5fba23 Guido Trotter
    # per-instance checks
425 a8083063 Iustin Pop
    for instance_name in data.instances:
426 a8083063 Iustin Pop
      instance = data.instances[instance_name]
427 81196341 Iustin Pop
      if instance.name != instance_name:
428 81196341 Iustin Pop
        result.append("instance '%s' is indexed by wrong name '%s'" %
429 81196341 Iustin Pop
                      (instance.name, instance_name))
430 a8083063 Iustin Pop
      if instance.primary_node not in data.nodes:
431 8522ceeb Iustin Pop
        result.append("instance '%s' has invalid primary node '%s'" %
432 a8083063 Iustin Pop
                      (instance_name, instance.primary_node))
433 a8083063 Iustin Pop
      for snode in instance.secondary_nodes:
434 a8083063 Iustin Pop
        if snode not in data.nodes:
435 8522ceeb Iustin Pop
          result.append("instance '%s' has invalid secondary node '%s'" %
436 a8083063 Iustin Pop
                        (instance_name, snode))
437 a8083063 Iustin Pop
      for idx, nic in enumerate(instance.nics):
438 a8083063 Iustin Pop
        if nic.mac in seen_macs:
439 8522ceeb Iustin Pop
          result.append("instance '%s' has NIC %d mac %s duplicate" %
440 a8083063 Iustin Pop
                        (instance_name, idx, nic.mac))
441 a8083063 Iustin Pop
        else:
442 a8083063 Iustin Pop
          seen_macs.append(nic.mac)
443 26f2fd8d Iustin Pop
        if nic.nicparams:
444 26f2fd8d Iustin Pop
          filled = cluster.SimpleFillNIC(nic.nicparams)
445 26f2fd8d Iustin Pop
          owner = "instance %s nic %d" % (instance.name, idx)
446 26f2fd8d Iustin Pop
          _helper(owner, "nicparams",
447 26f2fd8d Iustin Pop
                  filled, constants.NICS_PARAMETER_TYPES)
448 26f2fd8d Iustin Pop
          _helper_nic(owner, filled)
449 26f2fd8d Iustin Pop
450 26f2fd8d Iustin Pop
      # parameter checks
451 26f2fd8d Iustin Pop
      if instance.beparams:
452 26f2fd8d Iustin Pop
        _helper("instance %s" % instance.name, "beparams",
453 26f2fd8d Iustin Pop
                cluster.FillBE(instance), constants.BES_PARAMETER_TYPES)
454 48ce9fd9 Iustin Pop
455 48ce9fd9 Iustin Pop
      # gather the drbd ports for duplicate checks
456 48ce9fd9 Iustin Pop
      for dsk in instance.disks:
457 48ce9fd9 Iustin Pop
        if dsk.dev_type in constants.LDS_DRBD:
458 48ce9fd9 Iustin Pop
          tcp_port = dsk.logical_id[2]
459 48ce9fd9 Iustin Pop
          if tcp_port not in ports:
460 48ce9fd9 Iustin Pop
            ports[tcp_port] = []
461 48ce9fd9 Iustin Pop
          ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
462 48ce9fd9 Iustin Pop
      # gather network port reservation
463 48ce9fd9 Iustin Pop
      net_port = getattr(instance, "network_port", None)
464 48ce9fd9 Iustin Pop
      if net_port is not None:
465 48ce9fd9 Iustin Pop
        if net_port not in ports:
466 48ce9fd9 Iustin Pop
          ports[net_port] = []
467 48ce9fd9 Iustin Pop
        ports[net_port].append((instance.name, "network port"))
468 48ce9fd9 Iustin Pop
469 332d0e37 Iustin Pop
      # instance disk verify
470 332d0e37 Iustin Pop
      for idx, disk in enumerate(instance.disks):
471 332d0e37 Iustin Pop
        result.extend(["instance '%s' disk %d error: %s" %
472 332d0e37 Iustin Pop
                       (instance.name, idx, msg) for msg in disk.Verify()])
473 4b98ac29 Iustin Pop
        result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
474 332d0e37 Iustin Pop
475 48ce9fd9 Iustin Pop
    # cluster-wide pool of free ports
476 7e01d204 Iustin Pop
    for free_port in cluster.tcpudp_port_pool:
477 48ce9fd9 Iustin Pop
      if free_port not in ports:
478 48ce9fd9 Iustin Pop
        ports[free_port] = []
479 48ce9fd9 Iustin Pop
      ports[free_port].append(("cluster", "port marked as free"))
480 48ce9fd9 Iustin Pop
481 48ce9fd9 Iustin Pop
    # compute tcp/udp duplicate ports
482 48ce9fd9 Iustin Pop
    keys = ports.keys()
483 48ce9fd9 Iustin Pop
    keys.sort()
484 48ce9fd9 Iustin Pop
    for pnum in keys:
485 48ce9fd9 Iustin Pop
      pdata = ports[pnum]
486 48ce9fd9 Iustin Pop
      if len(pdata) > 1:
487 1f864b60 Iustin Pop
        txt = utils.CommaJoin(["%s/%s" % val for val in pdata])
488 48ce9fd9 Iustin Pop
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
489 48ce9fd9 Iustin Pop
490 48ce9fd9 Iustin Pop
    # highest used tcp port check
491 48ce9fd9 Iustin Pop
    if keys:
492 7e01d204 Iustin Pop
      if keys[-1] > cluster.highest_used_port:
493 48ce9fd9 Iustin Pop
        result.append("Highest used port mismatch, saved %s, computed %s" %
494 7e01d204 Iustin Pop
                      (cluster.highest_used_port, keys[-1]))
495 a8efbb40 Iustin Pop
496 7e01d204 Iustin Pop
    if not data.nodes[cluster.master_node].master_candidate:
497 3a26773f Iustin Pop
      result.append("Master node is not a master candidate")
498 3a26773f Iustin Pop
499 4a89c54a Iustin Pop
    # master candidate checks
500 e623dbe3 Guido Trotter
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
501 ec0292f1 Iustin Pop
    if mc_now < mc_max:
502 ec0292f1 Iustin Pop
      result.append("Not enough master candidates: actual %d, target %d" %
503 ec0292f1 Iustin Pop
                    (mc_now, mc_max))
504 48ce9fd9 Iustin Pop
505 5bf07049 Iustin Pop
    # node checks
506 81196341 Iustin Pop
    for node_name, node in data.nodes.items():
507 81196341 Iustin Pop
      if node.name != node_name:
508 81196341 Iustin Pop
        result.append("Node '%s' is indexed by wrong name '%s'" %
509 81196341 Iustin Pop
                      (node.name, node_name))
510 5bf07049 Iustin Pop
      if [node.master_candidate, node.drained, node.offline].count(True) > 1:
511 5bf07049 Iustin Pop
        result.append("Node %s state is invalid: master_candidate=%s,"
512 5bf07049 Iustin Pop
                      " drain=%s, offline=%s" %
513 3d889a7d Michael Hanselmann
                      (node.name, node.master_candidate, node.drained,
514 5bf07049 Iustin Pop
                       node.offline))
515 26f2fd8d Iustin Pop
      if node.group not in data.nodegroups:
516 26f2fd8d Iustin Pop
        result.append("Node '%s' has invalid group '%s'" %
517 26f2fd8d Iustin Pop
                      (node.name, node.group))
518 26f2fd8d Iustin Pop
      else:
519 26f2fd8d Iustin Pop
        _helper("node %s" % node.name, "ndparams",
520 26f2fd8d Iustin Pop
                cluster.FillND(node, data.nodegroups[node.group]),
521 26f2fd8d Iustin Pop
                constants.NDS_PARAMETER_TYPES)
522 5bf07049 Iustin Pop
523 6520ba14 Guido Trotter
    # nodegroups checks
524 ace16501 Guido Trotter
    nodegroups_names = set()
525 6520ba14 Guido Trotter
    for nodegroup_uuid in data.nodegroups:
526 6520ba14 Guido Trotter
      nodegroup = data.nodegroups[nodegroup_uuid]
527 6520ba14 Guido Trotter
      if nodegroup.uuid != nodegroup_uuid:
528 913cc25e Adeodato Simo
        result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
529 6520ba14 Guido Trotter
                      % (nodegroup.name, nodegroup.uuid, nodegroup_uuid))
530 485ba212 Guido Trotter
      if utils.UUID_RE.match(nodegroup.name.lower()):
531 913cc25e Adeodato Simo
        result.append("node group '%s' (uuid: '%s') has uuid-like name" %
532 485ba212 Guido Trotter
                      (nodegroup.name, nodegroup.uuid))
533 ace16501 Guido Trotter
      if nodegroup.name in nodegroups_names:
534 913cc25e Adeodato Simo
        result.append("duplicate node group name '%s'" % nodegroup.name)
535 ace16501 Guido Trotter
      else:
536 ace16501 Guido Trotter
        nodegroups_names.add(nodegroup.name)
537 26f2fd8d Iustin Pop
      if nodegroup.ndparams:
538 26f2fd8d Iustin Pop
        _helper("group %s" % nodegroup.name, "ndparams",
539 26f2fd8d Iustin Pop
                cluster.SimpleFillND(nodegroup.ndparams),
540 26f2fd8d Iustin Pop
                constants.NDS_PARAMETER_TYPES)
541 26f2fd8d Iustin Pop
542 6520ba14 Guido Trotter
543 4a89c54a Iustin Pop
    # drbd minors check
544 1122eb25 Iustin Pop
    _, duplicates = self._UnlockedComputeDRBDMap()
545 4a89c54a Iustin Pop
    for node, minor, instance_a, instance_b in duplicates:
546 4a89c54a Iustin Pop
      result.append("DRBD minor %d on node %s is assigned twice to instances"
547 4a89c54a Iustin Pop
                    " %s and %s" % (minor, node, instance_a, instance_b))
548 4a89c54a Iustin Pop
549 0ce8f948 Iustin Pop
    # IP checks
550 7e01d204 Iustin Pop
    default_nicparams = cluster.nicparams[constants.PP_DEFAULT]
551 b8716596 Michael Hanselmann
    ips = {}
552 b8716596 Michael Hanselmann
553 b8716596 Michael Hanselmann
    def _AddIpAddress(ip, name):
554 b8716596 Michael Hanselmann
      ips.setdefault(ip, []).append(name)
555 b8716596 Michael Hanselmann
556 7e01d204 Iustin Pop
    _AddIpAddress(cluster.master_ip, "cluster_ip")
557 0ce8f948 Iustin Pop
558 0ce8f948 Iustin Pop
    for node in data.nodes.values():
559 b8716596 Michael Hanselmann
      _AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
560 0ce8f948 Iustin Pop
      if node.secondary_ip != node.primary_ip:
561 b8716596 Michael Hanselmann
        _AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
562 b8716596 Michael Hanselmann
563 b8716596 Michael Hanselmann
    for instance in data.instances.values():
564 b8716596 Michael Hanselmann
      for idx, nic in enumerate(instance.nics):
565 b8716596 Michael Hanselmann
        if nic.ip is None:
566 b8716596 Michael Hanselmann
          continue
567 b8716596 Michael Hanselmann
568 b8716596 Michael Hanselmann
        nicparams = objects.FillDict(default_nicparams, nic.nicparams)
569 b8716596 Michael Hanselmann
        nic_mode = nicparams[constants.NIC_MODE]
570 b8716596 Michael Hanselmann
        nic_link = nicparams[constants.NIC_LINK]
571 b8716596 Michael Hanselmann
572 b8716596 Michael Hanselmann
        if nic_mode == constants.NIC_MODE_BRIDGED:
573 b8716596 Michael Hanselmann
          link = "bridge:%s" % nic_link
574 b8716596 Michael Hanselmann
        elif nic_mode == constants.NIC_MODE_ROUTED:
575 b8716596 Michael Hanselmann
          link = "route:%s" % nic_link
576 b8716596 Michael Hanselmann
        else:
577 b8716596 Michael Hanselmann
          raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode)
578 b8716596 Michael Hanselmann
579 b8716596 Michael Hanselmann
        _AddIpAddress("%s/%s" % (link, nic.ip),
580 b8716596 Michael Hanselmann
                      "instance:%s/nic:%d" % (instance.name, idx))
581 0ce8f948 Iustin Pop
582 0ce8f948 Iustin Pop
    for ip, owners in ips.items():
583 0ce8f948 Iustin Pop
      if len(owners) > 1:
584 0ce8f948 Iustin Pop
        result.append("IP address %s is used by multiple owners: %s" %
585 1f864b60 Iustin Pop
                      (ip, utils.CommaJoin(owners)))
586 b8716596 Michael Hanselmann
587 a8083063 Iustin Pop
    return result
588 a8083063 Iustin Pop
589 4a89c54a Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
590 4a89c54a Iustin Pop
  def VerifyConfig(self):
591 4a89c54a Iustin Pop
    """Verify function.
592 4a89c54a Iustin Pop

593 4a89c54a Iustin Pop
    This is just a wrapper over L{_UnlockedVerifyConfig}.
594 4a89c54a Iustin Pop

595 4a89c54a Iustin Pop
    @rtype: list
596 4a89c54a Iustin Pop
    @return: a list of error messages; a non-empty list signifies
597 4a89c54a Iustin Pop
        configuration errors
598 4a89c54a Iustin Pop

599 4a89c54a Iustin Pop
    """
600 4a89c54a Iustin Pop
    return self._UnlockedVerifyConfig()
601 4a89c54a Iustin Pop
602 f78ede4e Guido Trotter
  def _UnlockedSetDiskID(self, disk, node_name):
603 a8083063 Iustin Pop
    """Convert the unique ID to the ID needed on the target nodes.
604 a8083063 Iustin Pop

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

607 a8083063 Iustin Pop
    The routine descends down and updates its children also, because
608 a8083063 Iustin Pop
    this helps when the only the top device is passed to the remote
609 a8083063 Iustin Pop
    node.
610 a8083063 Iustin Pop

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

613 a8083063 Iustin Pop
    """
614 a8083063 Iustin Pop
    if disk.children:
615 a8083063 Iustin Pop
      for child in disk.children:
616 f78ede4e Guido Trotter
        self._UnlockedSetDiskID(child, node_name)
617 a8083063 Iustin Pop
618 a8083063 Iustin Pop
    if disk.logical_id is None and disk.physical_id is not None:
619 a8083063 Iustin Pop
      return
620 ffa1c0dc Iustin Pop
    if disk.dev_type == constants.LD_DRBD8:
621 f9518d38 Iustin Pop
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
622 a8083063 Iustin Pop
      if node_name not in (pnode, snode):
623 3ecf6786 Iustin Pop
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
624 3ecf6786 Iustin Pop
                                        node_name)
625 f78ede4e Guido Trotter
      pnode_info = self._UnlockedGetNodeInfo(pnode)
626 f78ede4e Guido Trotter
      snode_info = self._UnlockedGetNodeInfo(snode)
627 a8083063 Iustin Pop
      if pnode_info is None or snode_info is None:
628 a8083063 Iustin Pop
        raise errors.ConfigurationError("Can't find primary or secondary node"
629 a8083063 Iustin Pop
                                        " for %s" % str(disk))
630 ffa1c0dc Iustin Pop
      p_data = (pnode_info.secondary_ip, port)
631 ffa1c0dc Iustin Pop
      s_data = (snode_info.secondary_ip, port)
632 a8083063 Iustin Pop
      if pnode == node_name:
633 f9518d38 Iustin Pop
        disk.physical_id = p_data + s_data + (pminor, secret)
634 a8083063 Iustin Pop
      else: # it must be secondary, we tested above
635 f9518d38 Iustin Pop
        disk.physical_id = s_data + p_data + (sminor, secret)
636 a8083063 Iustin Pop
    else:
637 a8083063 Iustin Pop
      disk.physical_id = disk.logical_id
638 a8083063 Iustin Pop
    return
639 a8083063 Iustin Pop
640 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
641 f78ede4e Guido Trotter
  def SetDiskID(self, disk, node_name):
642 f78ede4e Guido Trotter
    """Convert the unique ID to the ID needed on the target nodes.
643 f78ede4e Guido Trotter

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

646 f78ede4e Guido Trotter
    The routine descends down and updates its children also, because
647 f78ede4e Guido Trotter
    this helps when the only the top device is passed to the remote
648 f78ede4e Guido Trotter
    node.
649 f78ede4e Guido Trotter

650 f78ede4e Guido Trotter
    """
651 f78ede4e Guido Trotter
    return self._UnlockedSetDiskID(disk, node_name)
652 f78ede4e Guido Trotter
653 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
654 b2fddf63 Iustin Pop
  def AddTcpUdpPort(self, port):
655 b2fddf63 Iustin Pop
    """Adds a new port to the available port pool.
656 b2fddf63 Iustin Pop

657 b2fddf63 Iustin Pop
    """
658 264bb3c5 Michael Hanselmann
    if not isinstance(port, int):
659 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Invalid type passed for port")
660 264bb3c5 Michael Hanselmann
661 b2fddf63 Iustin Pop
    self._config_data.cluster.tcpudp_port_pool.add(port)
662 264bb3c5 Michael Hanselmann
    self._WriteConfig()
663 264bb3c5 Michael Hanselmann
664 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
665 b2fddf63 Iustin Pop
  def GetPortList(self):
666 264bb3c5 Michael Hanselmann
    """Returns a copy of the current port list.
667 264bb3c5 Michael Hanselmann

668 264bb3c5 Michael Hanselmann
    """
669 b2fddf63 Iustin Pop
    return self._config_data.cluster.tcpudp_port_pool.copy()
670 264bb3c5 Michael Hanselmann
671 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
672 a8083063 Iustin Pop
  def AllocatePort(self):
673 a8083063 Iustin Pop
    """Allocate a port.
674 a8083063 Iustin Pop

675 b2fddf63 Iustin Pop
    The port will be taken from the available port pool or from the
676 b2fddf63 Iustin Pop
    default port range (and in this case we increase
677 b2fddf63 Iustin Pop
    highest_used_port).
678 a8083063 Iustin Pop

679 a8083063 Iustin Pop
    """
680 264bb3c5 Michael Hanselmann
    # If there are TCP/IP ports configured, we use them first.
681 b2fddf63 Iustin Pop
    if self._config_data.cluster.tcpudp_port_pool:
682 b2fddf63 Iustin Pop
      port = self._config_data.cluster.tcpudp_port_pool.pop()
683 264bb3c5 Michael Hanselmann
    else:
684 264bb3c5 Michael Hanselmann
      port = self._config_data.cluster.highest_used_port + 1
685 264bb3c5 Michael Hanselmann
      if port >= constants.LAST_DRBD_PORT:
686 3ecf6786 Iustin Pop
        raise errors.ConfigurationError("The highest used port is greater"
687 3ecf6786 Iustin Pop
                                        " than %s. Aborting." %
688 3ecf6786 Iustin Pop
                                        constants.LAST_DRBD_PORT)
689 264bb3c5 Michael Hanselmann
      self._config_data.cluster.highest_used_port = port
690 a8083063 Iustin Pop
691 a8083063 Iustin Pop
    self._WriteConfig()
692 a8083063 Iustin Pop
    return port
693 a8083063 Iustin Pop
694 6d2e83d5 Iustin Pop
  def _UnlockedComputeDRBDMap(self):
695 a81c53c9 Iustin Pop
    """Compute the used DRBD minor/nodes.
696 a81c53c9 Iustin Pop

697 4a89c54a Iustin Pop
    @rtype: (dict, list)
698 c41eea6e Iustin Pop
    @return: dictionary of node_name: dict of minor: instance_name;
699 c41eea6e Iustin Pop
        the returned dict will have all the nodes in it (even if with
700 4a89c54a Iustin Pop
        an empty list), and a list of duplicates; if the duplicates
701 4a89c54a Iustin Pop
        list is not empty, the configuration is corrupted and its caller
702 4a89c54a Iustin Pop
        should raise an exception
703 a81c53c9 Iustin Pop

704 a81c53c9 Iustin Pop
    """
705 a81c53c9 Iustin Pop
    def _AppendUsedPorts(instance_name, disk, used):
706 4a89c54a Iustin Pop
      duplicates = []
707 f9518d38 Iustin Pop
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
708 7c4d6c7b Michael Hanselmann
        node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
709 7c4d6c7b Michael Hanselmann
        for node, port in ((node_a, minor_a), (node_b, minor_b)):
710 4a89c54a Iustin Pop
          assert node in used, ("Node '%s' of instance '%s' not found"
711 4a89c54a Iustin Pop
                                " in node list" % (node, instance_name))
712 a81c53c9 Iustin Pop
          if port in used[node]:
713 4a89c54a Iustin Pop
            duplicates.append((node, port, instance_name, used[node][port]))
714 4a89c54a Iustin Pop
          else:
715 4a89c54a Iustin Pop
            used[node][port] = instance_name
716 a81c53c9 Iustin Pop
      if disk.children:
717 a81c53c9 Iustin Pop
        for child in disk.children:
718 4a89c54a Iustin Pop
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
719 4a89c54a Iustin Pop
      return duplicates
720 a81c53c9 Iustin Pop
721 4a89c54a Iustin Pop
    duplicates = []
722 a81c53c9 Iustin Pop
    my_dict = dict((node, {}) for node in self._config_data.nodes)
723 79b26a7a Iustin Pop
    for instance in self._config_data.instances.itervalues():
724 79b26a7a Iustin Pop
      for disk in instance.disks:
725 79b26a7a Iustin Pop
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
726 a81c53c9 Iustin Pop
    for (node, minor), instance in self._temporary_drbds.iteritems():
727 79b26a7a Iustin Pop
      if minor in my_dict[node] and my_dict[node][minor] != instance:
728 4a89c54a Iustin Pop
        duplicates.append((node, minor, instance, my_dict[node][minor]))
729 4a89c54a Iustin Pop
      else:
730 4a89c54a Iustin Pop
        my_dict[node][minor] = instance
731 4a89c54a Iustin Pop
    return my_dict, duplicates
732 a81c53c9 Iustin Pop
733 a81c53c9 Iustin Pop
  @locking.ssynchronized(_config_lock)
734 6d2e83d5 Iustin Pop
  def ComputeDRBDMap(self):
735 6d2e83d5 Iustin Pop
    """Compute the used DRBD minor/nodes.
736 6d2e83d5 Iustin Pop

737 6d2e83d5 Iustin Pop
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
738 6d2e83d5 Iustin Pop

739 6d2e83d5 Iustin Pop
    @return: dictionary of node_name: dict of minor: instance_name;
740 6d2e83d5 Iustin Pop
        the returned dict will have all the nodes in it (even if with
741 6d2e83d5 Iustin Pop
        an empty list).
742 6d2e83d5 Iustin Pop

743 6d2e83d5 Iustin Pop
    """
744 4a89c54a Iustin Pop
    d_map, duplicates = self._UnlockedComputeDRBDMap()
745 4a89c54a Iustin Pop
    if duplicates:
746 4a89c54a Iustin Pop
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
747 4a89c54a Iustin Pop
                                      str(duplicates))
748 4a89c54a Iustin Pop
    return d_map
749 6d2e83d5 Iustin Pop
750 6d2e83d5 Iustin Pop
  @locking.ssynchronized(_config_lock)
751 a81c53c9 Iustin Pop
  def AllocateDRBDMinor(self, nodes, instance):
752 a81c53c9 Iustin Pop
    """Allocate a drbd minor.
753 a81c53c9 Iustin Pop

754 a81c53c9 Iustin Pop
    The free minor will be automatically computed from the existing
755 a81c53c9 Iustin Pop
    devices. A node can be given multiple times in order to allocate
756 a81c53c9 Iustin Pop
    multiple minors. The result is the list of minors, in the same
757 a81c53c9 Iustin Pop
    order as the passed nodes.
758 a81c53c9 Iustin Pop

759 32388e6d Iustin Pop
    @type instance: string
760 32388e6d Iustin Pop
    @param instance: the instance for which we allocate minors
761 32388e6d Iustin Pop

762 a81c53c9 Iustin Pop
    """
763 32388e6d Iustin Pop
    assert isinstance(instance, basestring), \
764 4a89c54a Iustin Pop
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
765 32388e6d Iustin Pop
766 4a89c54a Iustin Pop
    d_map, duplicates = self._UnlockedComputeDRBDMap()
767 4a89c54a Iustin Pop
    if duplicates:
768 4a89c54a Iustin Pop
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
769 4a89c54a Iustin Pop
                                      str(duplicates))
770 a81c53c9 Iustin Pop
    result = []
771 a81c53c9 Iustin Pop
    for nname in nodes:
772 a81c53c9 Iustin Pop
      ndata = d_map[nname]
773 a81c53c9 Iustin Pop
      if not ndata:
774 a81c53c9 Iustin Pop
        # no minors used, we can start at 0
775 a81c53c9 Iustin Pop
        result.append(0)
776 a81c53c9 Iustin Pop
        ndata[0] = instance
777 d48663e4 Iustin Pop
        self._temporary_drbds[(nname, 0)] = instance
778 a81c53c9 Iustin Pop
        continue
779 a81c53c9 Iustin Pop
      keys = ndata.keys()
780 a81c53c9 Iustin Pop
      keys.sort()
781 a81c53c9 Iustin Pop
      ffree = utils.FirstFree(keys)
782 a81c53c9 Iustin Pop
      if ffree is None:
783 a81c53c9 Iustin Pop
        # return the next minor
784 a81c53c9 Iustin Pop
        # TODO: implement high-limit check
785 a81c53c9 Iustin Pop
        minor = keys[-1] + 1
786 a81c53c9 Iustin Pop
      else:
787 a81c53c9 Iustin Pop
        minor = ffree
788 4a89c54a Iustin Pop
      # double-check minor against current instances
789 4a89c54a Iustin Pop
      assert minor not in d_map[nname], \
790 4a89c54a Iustin Pop
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
791 4a89c54a Iustin Pop
              " already allocated to instance %s" %
792 4a89c54a Iustin Pop
              (minor, nname, d_map[nname][minor]))
793 a81c53c9 Iustin Pop
      ndata[minor] = instance
794 4a89c54a Iustin Pop
      # double-check minor against reservation
795 4a89c54a Iustin Pop
      r_key = (nname, minor)
796 4a89c54a Iustin Pop
      assert r_key not in self._temporary_drbds, \
797 4a89c54a Iustin Pop
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
798 4a89c54a Iustin Pop
              " reserved for instance %s" %
799 4a89c54a Iustin Pop
              (minor, nname, self._temporary_drbds[r_key]))
800 4a89c54a Iustin Pop
      self._temporary_drbds[r_key] = instance
801 4a89c54a Iustin Pop
      result.append(minor)
802 a81c53c9 Iustin Pop
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
803 a81c53c9 Iustin Pop
                  nodes, result)
804 a81c53c9 Iustin Pop
    return result
805 a81c53c9 Iustin Pop
806 61cf6b5e Iustin Pop
  def _UnlockedReleaseDRBDMinors(self, instance):
807 a81c53c9 Iustin Pop
    """Release temporary drbd minors allocated for a given instance.
808 a81c53c9 Iustin Pop

809 a81c53c9 Iustin Pop
    @type instance: string
810 a81c53c9 Iustin Pop
    @param instance: the instance for which temporary minors should be
811 a81c53c9 Iustin Pop
                     released
812 a81c53c9 Iustin Pop

813 a81c53c9 Iustin Pop
    """
814 32388e6d Iustin Pop
    assert isinstance(instance, basestring), \
815 32388e6d Iustin Pop
           "Invalid argument passed to ReleaseDRBDMinors"
816 a81c53c9 Iustin Pop
    for key, name in self._temporary_drbds.items():
817 a81c53c9 Iustin Pop
      if name == instance:
818 a81c53c9 Iustin Pop
        del self._temporary_drbds[key]
819 a81c53c9 Iustin Pop
820 61cf6b5e Iustin Pop
  @locking.ssynchronized(_config_lock)
821 61cf6b5e Iustin Pop
  def ReleaseDRBDMinors(self, instance):
822 61cf6b5e Iustin Pop
    """Release temporary drbd minors allocated for a given instance.
823 61cf6b5e Iustin Pop

824 61cf6b5e Iustin Pop
    This should be called on the error paths, on the success paths
825 61cf6b5e Iustin Pop
    it's automatically called by the ConfigWriter add and update
826 61cf6b5e Iustin Pop
    functions.
827 61cf6b5e Iustin Pop

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

830 61cf6b5e Iustin Pop
    @type instance: string
831 61cf6b5e Iustin Pop
    @param instance: the instance for which temporary minors should be
832 61cf6b5e Iustin Pop
                     released
833 61cf6b5e Iustin Pop

834 61cf6b5e Iustin Pop
    """
835 61cf6b5e Iustin Pop
    self._UnlockedReleaseDRBDMinors(instance)
836 61cf6b5e Iustin Pop
837 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
838 4a8b186a Michael Hanselmann
  def GetConfigVersion(self):
839 4a8b186a Michael Hanselmann
    """Get the configuration version.
840 4a8b186a Michael Hanselmann

841 4a8b186a Michael Hanselmann
    @return: Config version
842 4a8b186a Michael Hanselmann

843 4a8b186a Michael Hanselmann
    """
844 4a8b186a Michael Hanselmann
    return self._config_data.version
845 4a8b186a Michael Hanselmann
846 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
847 4a8b186a Michael Hanselmann
  def GetClusterName(self):
848 4a8b186a Michael Hanselmann
    """Get cluster name.
849 4a8b186a Michael Hanselmann

850 4a8b186a Michael Hanselmann
    @return: Cluster name
851 4a8b186a Michael Hanselmann

852 4a8b186a Michael Hanselmann
    """
853 4a8b186a Michael Hanselmann
    return self._config_data.cluster.cluster_name
854 4a8b186a Michael Hanselmann
855 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
856 4a8b186a Michael Hanselmann
  def GetMasterNode(self):
857 4a8b186a Michael Hanselmann
    """Get the hostname of the master node for this cluster.
858 4a8b186a Michael Hanselmann

859 4a8b186a Michael Hanselmann
    @return: Master hostname
860 4a8b186a Michael Hanselmann

861 4a8b186a Michael Hanselmann
    """
862 4a8b186a Michael Hanselmann
    return self._config_data.cluster.master_node
863 4a8b186a Michael Hanselmann
864 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
865 4a8b186a Michael Hanselmann
  def GetMasterIP(self):
866 4a8b186a Michael Hanselmann
    """Get the IP of the master node for this cluster.
867 4a8b186a Michael Hanselmann

868 4a8b186a Michael Hanselmann
    @return: Master IP
869 4a8b186a Michael Hanselmann

870 4a8b186a Michael Hanselmann
    """
871 4a8b186a Michael Hanselmann
    return self._config_data.cluster.master_ip
872 4a8b186a Michael Hanselmann
873 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
874 4a8b186a Michael Hanselmann
  def GetMasterNetdev(self):
875 4a8b186a Michael Hanselmann
    """Get the master network device for this cluster.
876 4a8b186a Michael Hanselmann

877 4a8b186a Michael Hanselmann
    """
878 4a8b186a Michael Hanselmann
    return self._config_data.cluster.master_netdev
879 4a8b186a Michael Hanselmann
880 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
881 4a8b186a Michael Hanselmann
  def GetFileStorageDir(self):
882 4a8b186a Michael Hanselmann
    """Get the file storage dir for this cluster.
883 4a8b186a Michael Hanselmann

884 4a8b186a Michael Hanselmann
    """
885 4a8b186a Michael Hanselmann
    return self._config_data.cluster.file_storage_dir
886 4a8b186a Michael Hanselmann
887 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
888 4b97f902 Apollon Oikonomopoulos
  def GetSharedFileStorageDir(self):
889 4b97f902 Apollon Oikonomopoulos
    """Get the shared file storage dir for this cluster.
890 4b97f902 Apollon Oikonomopoulos

891 4b97f902 Apollon Oikonomopoulos
    """
892 4b97f902 Apollon Oikonomopoulos
    return self._config_data.cluster.shared_file_storage_dir
893 4b97f902 Apollon Oikonomopoulos
894 4b97f902 Apollon Oikonomopoulos
  @locking.ssynchronized(_config_lock, shared=1)
895 4a8b186a Michael Hanselmann
  def GetHypervisorType(self):
896 4a8b186a Michael Hanselmann
    """Get the hypervisor type for this cluster.
897 4a8b186a Michael Hanselmann

898 4a8b186a Michael Hanselmann
    """
899 066f465d Guido Trotter
    return self._config_data.cluster.enabled_hypervisors[0]
900 4a8b186a Michael Hanselmann
901 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
902 a8083063 Iustin Pop
  def GetHostKey(self):
903 a8083063 Iustin Pop
    """Return the rsa hostkey from the config.
904 a8083063 Iustin Pop

905 c41eea6e Iustin Pop
    @rtype: string
906 c41eea6e Iustin Pop
    @return: the rsa hostkey
907 a8083063 Iustin Pop

908 a8083063 Iustin Pop
    """
909 a8083063 Iustin Pop
    return self._config_data.cluster.rsahostkeypub
910 a8083063 Iustin Pop
911 bf4af505 Apollon Oikonomopoulos
  @locking.ssynchronized(_config_lock, shared=1)
912 bf4af505 Apollon Oikonomopoulos
  def GetDefaultIAllocator(self):
913 bf4af505 Apollon Oikonomopoulos
    """Get the default instance allocator for this cluster.
914 bf4af505 Apollon Oikonomopoulos

915 bf4af505 Apollon Oikonomopoulos
    """
916 bf4af505 Apollon Oikonomopoulos
    return self._config_data.cluster.default_iallocator
917 bf4af505 Apollon Oikonomopoulos
918 868a98ca Manuel Franceschini
  @locking.ssynchronized(_config_lock, shared=1)
919 868a98ca Manuel Franceschini
  def GetPrimaryIPFamily(self):
920 868a98ca Manuel Franceschini
    """Get cluster primary ip family.
921 868a98ca Manuel Franceschini

922 868a98ca Manuel Franceschini
    @return: primary ip family
923 868a98ca Manuel Franceschini

924 868a98ca Manuel Franceschini
    """
925 868a98ca Manuel Franceschini
    return self._config_data.cluster.primary_ip_family
926 868a98ca Manuel Franceschini
927 e11a1b77 Adeodato Simo
  @locking.ssynchronized(_config_lock)
928 e11a1b77 Adeodato Simo
  def AddNodeGroup(self, group, ec_id, check_uuid=True):
929 e11a1b77 Adeodato Simo
    """Add a node group to the configuration.
930 e11a1b77 Adeodato Simo

931 90e99856 Adeodato Simo
    This method calls group.UpgradeConfig() to fill any missing attributes
932 90e99856 Adeodato Simo
    according to their default values.
933 90e99856 Adeodato Simo

934 e11a1b77 Adeodato Simo
    @type group: L{objects.NodeGroup}
935 e11a1b77 Adeodato Simo
    @param group: the NodeGroup object to add
936 e11a1b77 Adeodato Simo
    @type ec_id: string
937 e11a1b77 Adeodato Simo
    @param ec_id: unique id for the job to use when creating a missing UUID
938 e11a1b77 Adeodato Simo
    @type check_uuid: bool
939 e11a1b77 Adeodato Simo
    @param check_uuid: add an UUID to the group if it doesn't have one or, if
940 e11a1b77 Adeodato Simo
                       it does, ensure that it does not exist in the
941 e11a1b77 Adeodato Simo
                       configuration already
942 e11a1b77 Adeodato Simo

943 e11a1b77 Adeodato Simo
    """
944 e11a1b77 Adeodato Simo
    self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
945 e11a1b77 Adeodato Simo
    self._WriteConfig()
946 e11a1b77 Adeodato Simo
947 e11a1b77 Adeodato Simo
  def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid):
948 e11a1b77 Adeodato Simo
    """Add a node group to the configuration.
949 e11a1b77 Adeodato Simo

950 e11a1b77 Adeodato Simo
    """
951 e11a1b77 Adeodato Simo
    logging.info("Adding node group %s to configuration", group.name)
952 e11a1b77 Adeodato Simo
953 e11a1b77 Adeodato Simo
    # Some code might need to add a node group with a pre-populated UUID
954 e11a1b77 Adeodato Simo
    # generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
955 e11a1b77 Adeodato Simo
    # the "does this UUID" exist already check.
956 e11a1b77 Adeodato Simo
    if check_uuid:
957 e11a1b77 Adeodato Simo
      self._EnsureUUID(group, ec_id)
958 e11a1b77 Adeodato Simo
959 18ffc0fe Stephen Shirley
    try:
960 18ffc0fe Stephen Shirley
      existing_uuid = self._UnlockedLookupNodeGroup(group.name)
961 18ffc0fe Stephen Shirley
    except errors.OpPrereqError:
962 18ffc0fe Stephen Shirley
      pass
963 18ffc0fe Stephen Shirley
    else:
964 18ffc0fe Stephen Shirley
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
965 18ffc0fe Stephen Shirley
                                 " node group (UUID: %s)" %
966 18ffc0fe Stephen Shirley
                                 (group.name, existing_uuid),
967 18ffc0fe Stephen Shirley
                                 errors.ECODE_EXISTS)
968 18ffc0fe Stephen Shirley
969 e11a1b77 Adeodato Simo
    group.serial_no = 1
970 e11a1b77 Adeodato Simo
    group.ctime = group.mtime = time.time()
971 90e99856 Adeodato Simo
    group.UpgradeConfig()
972 e11a1b77 Adeodato Simo
973 e11a1b77 Adeodato Simo
    self._config_data.nodegroups[group.uuid] = group
974 e11a1b77 Adeodato Simo
    self._config_data.cluster.serial_no += 1
975 e11a1b77 Adeodato Simo
976 e11a1b77 Adeodato Simo
  @locking.ssynchronized(_config_lock)
977 e11a1b77 Adeodato Simo
  def RemoveNodeGroup(self, group_uuid):
978 e11a1b77 Adeodato Simo
    """Remove a node group from the configuration.
979 e11a1b77 Adeodato Simo

980 e11a1b77 Adeodato Simo
    @type group_uuid: string
981 e11a1b77 Adeodato Simo
    @param group_uuid: the UUID of the node group to remove
982 e11a1b77 Adeodato Simo

983 e11a1b77 Adeodato Simo
    """
984 e11a1b77 Adeodato Simo
    logging.info("Removing node group %s from configuration", group_uuid)
985 e11a1b77 Adeodato Simo
986 e11a1b77 Adeodato Simo
    if group_uuid not in self._config_data.nodegroups:
987 e11a1b77 Adeodato Simo
      raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid)
988 e11a1b77 Adeodato Simo
989 0389c42a Stephen Shirley
    assert len(self._config_data.nodegroups) != 1, \
990 0389c42a Stephen Shirley
            "Group '%s' is the only group, cannot be removed" % group_uuid
991 0389c42a Stephen Shirley
992 e11a1b77 Adeodato Simo
    del self._config_data.nodegroups[group_uuid]
993 e11a1b77 Adeodato Simo
    self._config_data.cluster.serial_no += 1
994 e11a1b77 Adeodato Simo
    self._WriteConfig()
995 e11a1b77 Adeodato Simo
996 e85d8982 Stephen Shirley
  def _UnlockedLookupNodeGroup(self, target):
997 412b3531 Guido Trotter
    """Lookup a node group's UUID.
998 eaa98a04 Guido Trotter

999 eaa98a04 Guido Trotter
    @type target: string or None
1000 412b3531 Guido Trotter
    @param target: group name or UUID or None to look for the default
1001 eaa98a04 Guido Trotter
    @rtype: string
1002 412b3531 Guido Trotter
    @return: nodegroup UUID
1003 eaa98a04 Guido Trotter
    @raises errors.OpPrereqError: when the target group cannot be found
1004 eaa98a04 Guido Trotter

1005 eaa98a04 Guido Trotter
    """
1006 eaa98a04 Guido Trotter
    if target is None:
1007 eaa98a04 Guido Trotter
      if len(self._config_data.nodegroups) != 1:
1008 913cc25e Adeodato Simo
        raise errors.OpPrereqError("More than one node group exists. Target"
1009 eaa98a04 Guido Trotter
                                   " group must be specified explicitely.")
1010 eaa98a04 Guido Trotter
      else:
1011 eaa98a04 Guido Trotter
        return self._config_data.nodegroups.keys()[0]
1012 eaa98a04 Guido Trotter
    if target in self._config_data.nodegroups:
1013 eaa98a04 Guido Trotter
      return target
1014 eaa98a04 Guido Trotter
    for nodegroup in self._config_data.nodegroups.values():
1015 eaa98a04 Guido Trotter
      if nodegroup.name == target:
1016 eaa98a04 Guido Trotter
        return nodegroup.uuid
1017 e0f9ed64 Adeodato Simo
    raise errors.OpPrereqError("Node group '%s' not found" % target,
1018 e0f9ed64 Adeodato Simo
                               errors.ECODE_NOENT)
1019 eaa98a04 Guido Trotter
1020 e85d8982 Stephen Shirley
  @locking.ssynchronized(_config_lock, shared=1)
1021 e85d8982 Stephen Shirley
  def LookupNodeGroup(self, target):
1022 e85d8982 Stephen Shirley
    """Lookup a node group's UUID.
1023 e85d8982 Stephen Shirley

1024 e85d8982 Stephen Shirley
    This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
1025 e85d8982 Stephen Shirley

1026 e85d8982 Stephen Shirley
    @type target: string or None
1027 e85d8982 Stephen Shirley
    @param target: group name or UUID or None to look for the default
1028 e85d8982 Stephen Shirley
    @rtype: string
1029 e85d8982 Stephen Shirley
    @return: nodegroup UUID
1030 e85d8982 Stephen Shirley

1031 e85d8982 Stephen Shirley
    """
1032 e85d8982 Stephen Shirley
    return self._UnlockedLookupNodeGroup(target)
1033 e85d8982 Stephen Shirley
1034 5768e6a6 René Nussbaumer
  def _UnlockedGetNodeGroup(self, uuid):
1035 648e4196 Guido Trotter
    """Lookup a node group.
1036 648e4196 Guido Trotter

1037 648e4196 Guido Trotter
    @type uuid: string
1038 648e4196 Guido Trotter
    @param uuid: group UUID
1039 648e4196 Guido Trotter
    @rtype: L{objects.NodeGroup} or None
1040 648e4196 Guido Trotter
    @return: nodegroup object, or None if not found
1041 648e4196 Guido Trotter

1042 648e4196 Guido Trotter
    """
1043 648e4196 Guido Trotter
    if uuid not in self._config_data.nodegroups:
1044 648e4196 Guido Trotter
      return None
1045 648e4196 Guido Trotter
1046 648e4196 Guido Trotter
    return self._config_data.nodegroups[uuid]
1047 648e4196 Guido Trotter
1048 648e4196 Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1049 5768e6a6 René Nussbaumer
  def GetNodeGroup(self, uuid):
1050 5768e6a6 René Nussbaumer
    """Lookup a node group.
1051 5768e6a6 René Nussbaumer

1052 5768e6a6 René Nussbaumer
    @type uuid: string
1053 5768e6a6 René Nussbaumer
    @param uuid: group UUID
1054 5768e6a6 René Nussbaumer
    @rtype: L{objects.NodeGroup} or None
1055 5768e6a6 René Nussbaumer
    @return: nodegroup object, or None if not found
1056 5768e6a6 René Nussbaumer

1057 5768e6a6 René Nussbaumer
    """
1058 5768e6a6 René Nussbaumer
    return self._UnlockedGetNodeGroup(uuid)
1059 5768e6a6 René Nussbaumer
1060 5768e6a6 René Nussbaumer
  @locking.ssynchronized(_config_lock, shared=1)
1061 622444e5 Iustin Pop
  def GetAllNodeGroupsInfo(self):
1062 622444e5 Iustin Pop
    """Get the configuration of all node groups.
1063 622444e5 Iustin Pop

1064 622444e5 Iustin Pop
    """
1065 622444e5 Iustin Pop
    return dict(self._config_data.nodegroups)
1066 622444e5 Iustin Pop
1067 1ac6f2ad Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1068 1ac6f2ad Guido Trotter
  def GetNodeGroupList(self):
1069 1ac6f2ad Guido Trotter
    """Get a list of node groups.
1070 1ac6f2ad Guido Trotter

1071 1ac6f2ad Guido Trotter
    """
1072 1ac6f2ad Guido Trotter
    return self._config_data.nodegroups.keys()
1073 1ac6f2ad Guido Trotter
1074 dac81741 Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
1075 dac81741 Michael Hanselmann
  def GetNodeGroupMembersByNodes(self, nodes):
1076 dac81741 Michael Hanselmann
    """Get nodes which are member in the same nodegroups as the given nodes.
1077 dac81741 Michael Hanselmann

1078 dac81741 Michael Hanselmann
    """
1079 dac81741 Michael Hanselmann
    ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group
1080 dac81741 Michael Hanselmann
    return frozenset(member_name
1081 dac81741 Michael Hanselmann
                     for node_name in nodes
1082 dac81741 Michael Hanselmann
                     for member_name in
1083 dac81741 Michael Hanselmann
                       self._UnlockedGetNodeGroup(ngfn(node_name)).members)
1084 dac81741 Michael Hanselmann
1085 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1086 0debfb35 Guido Trotter
  def AddInstance(self, instance, ec_id):
1087 a8083063 Iustin Pop
    """Add an instance to the config.
1088 a8083063 Iustin Pop

1089 a8083063 Iustin Pop
    This should be used after creating a new instance.
1090 a8083063 Iustin Pop

1091 c41eea6e Iustin Pop
    @type instance: L{objects.Instance}
1092 c41eea6e Iustin Pop
    @param instance: the instance object
1093 c41eea6e Iustin Pop

1094 a8083063 Iustin Pop
    """
1095 a8083063 Iustin Pop
    if not isinstance(instance, objects.Instance):
1096 a8083063 Iustin Pop
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
1097 a8083063 Iustin Pop
1098 e00fb268 Iustin Pop
    if instance.disk_template != constants.DT_DISKLESS:
1099 e00fb268 Iustin Pop
      all_lvs = instance.MapLVsByNode()
1100 74a48621 Iustin Pop
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
1101 923b1523 Iustin Pop
1102 e4640214 Guido Trotter
    all_macs = self._AllMACs()
1103 e4640214 Guido Trotter
    for nic in instance.nics:
1104 e4640214 Guido Trotter
      if nic.mac in all_macs:
1105 e4640214 Guido Trotter
        raise errors.ConfigurationError("Cannot add instance %s:"
1106 430b923c Iustin Pop
                                        " MAC address '%s' already in use." %
1107 430b923c Iustin Pop
                                        (instance.name, nic.mac))
1108 430b923c Iustin Pop
1109 0debfb35 Guido Trotter
    self._EnsureUUID(instance, ec_id)
1110 e4640214 Guido Trotter
1111 b989e85d Iustin Pop
    instance.serial_no = 1
1112 d693c864 Iustin Pop
    instance.ctime = instance.mtime = time.time()
1113 a8083063 Iustin Pop
    self._config_data.instances[instance.name] = instance
1114 81a49123 Iustin Pop
    self._config_data.cluster.serial_no += 1
1115 61cf6b5e Iustin Pop
    self._UnlockedReleaseDRBDMinors(instance.name)
1116 a8083063 Iustin Pop
    self._WriteConfig()
1117 a8083063 Iustin Pop
1118 0debfb35 Guido Trotter
  def _EnsureUUID(self, item, ec_id):
1119 430b923c Iustin Pop
    """Ensures a given object has a valid UUID.
1120 430b923c Iustin Pop

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

1124 430b923c Iustin Pop
    """
1125 430b923c Iustin Pop
    if not item.uuid:
1126 4fae38c5 Guido Trotter
      item.uuid = self._GenerateUniqueID(ec_id)
1127 be0fc05d Iustin Pop
    elif item.uuid in self._AllIDs(include_temporary=True):
1128 be0fc05d Iustin Pop
      raise errors.ConfigurationError("Cannot add '%s': UUID %s already"
1129 be0fc05d Iustin Pop
                                      " in use" % (item.name, item.uuid))
1130 430b923c Iustin Pop
1131 6a408fb2 Iustin Pop
  def _SetInstanceStatus(self, instance_name, status):
1132 6a408fb2 Iustin Pop
    """Set the instance's status to a given value.
1133 a8083063 Iustin Pop

1134 a8083063 Iustin Pop
    """
1135 0d68c45d Iustin Pop
    assert isinstance(status, bool), \
1136 0d68c45d Iustin Pop
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
1137 a8083063 Iustin Pop
1138 a8083063 Iustin Pop
    if instance_name not in self._config_data.instances:
1139 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Unknown instance '%s'" %
1140 3ecf6786 Iustin Pop
                                      instance_name)
1141 a8083063 Iustin Pop
    instance = self._config_data.instances[instance_name]
1142 0d68c45d Iustin Pop
    if instance.admin_up != status:
1143 0d68c45d Iustin Pop
      instance.admin_up = status
1144 b989e85d Iustin Pop
      instance.serial_no += 1
1145 d693c864 Iustin Pop
      instance.mtime = time.time()
1146 455a3445 Iustin Pop
      self._WriteConfig()
1147 a8083063 Iustin Pop
1148 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1149 6a408fb2 Iustin Pop
  def MarkInstanceUp(self, instance_name):
1150 6a408fb2 Iustin Pop
    """Mark the instance status to up in the config.
1151 6a408fb2 Iustin Pop

1152 6a408fb2 Iustin Pop
    """
1153 0d68c45d Iustin Pop
    self._SetInstanceStatus(instance_name, True)
1154 6a408fb2 Iustin Pop
1155 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1156 a8083063 Iustin Pop
  def RemoveInstance(self, instance_name):
1157 a8083063 Iustin Pop
    """Remove the instance from the configuration.
1158 a8083063 Iustin Pop

1159 a8083063 Iustin Pop
    """
1160 a8083063 Iustin Pop
    if instance_name not in self._config_data.instances:
1161 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1162 a8083063 Iustin Pop
    del self._config_data.instances[instance_name]
1163 81a49123 Iustin Pop
    self._config_data.cluster.serial_no += 1
1164 a8083063 Iustin Pop
    self._WriteConfig()
1165 a8083063 Iustin Pop
1166 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1167 fc95f88f Iustin Pop
  def RenameInstance(self, old_name, new_name):
1168 fc95f88f Iustin Pop
    """Rename an instance.
1169 fc95f88f Iustin Pop

1170 fc95f88f Iustin Pop
    This needs to be done in ConfigWriter and not by RemoveInstance
1171 fc95f88f Iustin Pop
    combined with AddInstance as only we can guarantee an atomic
1172 fc95f88f Iustin Pop
    rename.
1173 fc95f88f Iustin Pop

1174 fc95f88f Iustin Pop
    """
1175 fc95f88f Iustin Pop
    if old_name not in self._config_data.instances:
1176 fc95f88f Iustin Pop
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
1177 fc95f88f Iustin Pop
    inst = self._config_data.instances[old_name]
1178 fc95f88f Iustin Pop
    del self._config_data.instances[old_name]
1179 fc95f88f Iustin Pop
    inst.name = new_name
1180 b23c4333 Manuel Franceschini
1181 b23c4333 Manuel Franceschini
    for disk in inst.disks:
1182 b23c4333 Manuel Franceschini
      if disk.dev_type == constants.LD_FILE:
1183 b23c4333 Manuel Franceschini
        # rename the file paths in logical and physical id
1184 b23c4333 Manuel Franceschini
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
1185 3721d2fe Guido Trotter
        disk_fname = "disk%s" % disk.iv_name.split("/")[1]
1186 b23c4333 Manuel Franceschini
        disk.physical_id = disk.logical_id = (disk.logical_id[0],
1187 c4feafe8 Iustin Pop
                                              utils.PathJoin(file_storage_dir,
1188 c4feafe8 Iustin Pop
                                                             inst.name,
1189 3721d2fe Guido Trotter
                                                             disk_fname))
1190 b23c4333 Manuel Franceschini
1191 1fc34c48 Michael Hanselmann
    # Force update of ssconf files
1192 1fc34c48 Michael Hanselmann
    self._config_data.cluster.serial_no += 1
1193 1fc34c48 Michael Hanselmann
1194 fc95f88f Iustin Pop
    self._config_data.instances[inst.name] = inst
1195 fc95f88f Iustin Pop
    self._WriteConfig()
1196 fc95f88f Iustin Pop
1197 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1198 a8083063 Iustin Pop
  def MarkInstanceDown(self, instance_name):
1199 a8083063 Iustin Pop
    """Mark the status of an instance to down in the configuration.
1200 a8083063 Iustin Pop

1201 a8083063 Iustin Pop
    """
1202 0d68c45d Iustin Pop
    self._SetInstanceStatus(instance_name, False)
1203 a8083063 Iustin Pop
1204 94bbfece Iustin Pop
  def _UnlockedGetInstanceList(self):
1205 94bbfece Iustin Pop
    """Get the list of instances.
1206 94bbfece Iustin Pop

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

1209 94bbfece Iustin Pop
    """
1210 94bbfece Iustin Pop
    return self._config_data.instances.keys()
1211 94bbfece Iustin Pop
1212 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1213 a8083063 Iustin Pop
  def GetInstanceList(self):
1214 a8083063 Iustin Pop
    """Get the list of instances.
1215 a8083063 Iustin Pop

1216 c41eea6e Iustin Pop
    @return: array of instances, ex. ['instance2.example.com',
1217 c41eea6e Iustin Pop
        'instance1.example.com']
1218 a8083063 Iustin Pop

1219 a8083063 Iustin Pop
    """
1220 94bbfece Iustin Pop
    return self._UnlockedGetInstanceList()
1221 a8083063 Iustin Pop
1222 a8083063 Iustin Pop
  def ExpandInstanceName(self, short_name):
1223 a8083063 Iustin Pop
    """Attempt to expand an incomplete instance name.
1224 a8083063 Iustin Pop

1225 a8083063 Iustin Pop
    """
1226 fe698b38 Michael Hanselmann
    # Locking is done in L{ConfigWriter.GetInstanceList}
1227 fe698b38 Michael Hanselmann
    return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList())
1228 a8083063 Iustin Pop
1229 94bbfece Iustin Pop
  def _UnlockedGetInstanceInfo(self, instance_name):
1230 5bbd3f7f Michael Hanselmann
    """Returns information about an instance.
1231 94bbfece Iustin Pop

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

1234 94bbfece Iustin Pop
    """
1235 94bbfece Iustin Pop
    if instance_name not in self._config_data.instances:
1236 94bbfece Iustin Pop
      return None
1237 94bbfece Iustin Pop
1238 94bbfece Iustin Pop
    return self._config_data.instances[instance_name]
1239 94bbfece Iustin Pop
1240 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1241 a8083063 Iustin Pop
  def GetInstanceInfo(self, instance_name):
1242 5bbd3f7f Michael Hanselmann
    """Returns information about an instance.
1243 a8083063 Iustin Pop

1244 5bbd3f7f Michael Hanselmann
    It takes the information from the configuration file. Other information of
1245 a8083063 Iustin Pop
    an instance are taken from the live systems.
1246 a8083063 Iustin Pop

1247 c41eea6e Iustin Pop
    @param instance_name: name of the instance, e.g.
1248 c41eea6e Iustin Pop
        I{instance1.example.com}
1249 a8083063 Iustin Pop

1250 c41eea6e Iustin Pop
    @rtype: L{objects.Instance}
1251 c41eea6e Iustin Pop
    @return: the instance object
1252 a8083063 Iustin Pop

1253 a8083063 Iustin Pop
    """
1254 94bbfece Iustin Pop
    return self._UnlockedGetInstanceInfo(instance_name)
1255 a8083063 Iustin Pop
1256 0b2de758 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1257 2674690b Michael Hanselmann
  def GetInstanceNodeGroups(self, instance_name, primary_only=False):
1258 2674690b Michael Hanselmann
    """Returns set of node group UUIDs for instance's nodes.
1259 2674690b Michael Hanselmann

1260 2674690b Michael Hanselmann
    @rtype: frozenset
1261 2674690b Michael Hanselmann

1262 2674690b Michael Hanselmann
    """
1263 2674690b Michael Hanselmann
    instance = self._UnlockedGetInstanceInfo(instance_name)
1264 2674690b Michael Hanselmann
    if not instance:
1265 2674690b Michael Hanselmann
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
1266 2674690b Michael Hanselmann
1267 2674690b Michael Hanselmann
    if primary_only:
1268 2674690b Michael Hanselmann
      nodes = [instance.primary_node]
1269 2674690b Michael Hanselmann
    else:
1270 2674690b Michael Hanselmann
      nodes = instance.all_nodes
1271 2674690b Michael Hanselmann
1272 2674690b Michael Hanselmann
    return frozenset(self._UnlockedGetNodeInfo(node_name).group
1273 2674690b Michael Hanselmann
                     for node_name in nodes)
1274 2674690b Michael Hanselmann
1275 2674690b Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
1276 0b2de758 Iustin Pop
  def GetAllInstancesInfo(self):
1277 0b2de758 Iustin Pop
    """Get the configuration of all instances.
1278 0b2de758 Iustin Pop

1279 0b2de758 Iustin Pop
    @rtype: dict
1280 5fcc718f Iustin Pop
    @return: dict of (instance, instance_info), where instance_info is what
1281 0b2de758 Iustin Pop
              would GetInstanceInfo return for the node
1282 0b2de758 Iustin Pop

1283 0b2de758 Iustin Pop
    """
1284 64d3bd52 Guido Trotter
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
1285 64d3bd52 Guido Trotter
                    for instance in self._UnlockedGetInstanceList()])
1286 0b2de758 Iustin Pop
    return my_dict
1287 0b2de758 Iustin Pop
1288 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1289 0debfb35 Guido Trotter
  def AddNode(self, node, ec_id):
1290 a8083063 Iustin Pop
    """Add a node to the configuration.
1291 a8083063 Iustin Pop

1292 c41eea6e Iustin Pop
    @type node: L{objects.Node}
1293 c41eea6e Iustin Pop
    @param node: a Node instance
1294 a8083063 Iustin Pop

1295 a8083063 Iustin Pop
    """
1296 099c52ad Iustin Pop
    logging.info("Adding node %s to configuration", node.name)
1297 d8470559 Michael Hanselmann
1298 0debfb35 Guido Trotter
    self._EnsureUUID(node, ec_id)
1299 430b923c Iustin Pop
1300 b989e85d Iustin Pop
    node.serial_no = 1
1301 d693c864 Iustin Pop
    node.ctime = node.mtime = time.time()
1302 f936c153 Iustin Pop
    self._UnlockedAddNodeToGroup(node.name, node.group)
1303 a8083063 Iustin Pop
    self._config_data.nodes[node.name] = node
1304 b9f72b4e Iustin Pop
    self._config_data.cluster.serial_no += 1
1305 a8083063 Iustin Pop
    self._WriteConfig()
1306 a8083063 Iustin Pop
1307 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1308 a8083063 Iustin Pop
  def RemoveNode(self, node_name):
1309 a8083063 Iustin Pop
    """Remove a node from the configuration.
1310 a8083063 Iustin Pop

1311 a8083063 Iustin Pop
    """
1312 099c52ad Iustin Pop
    logging.info("Removing node %s from configuration", node_name)
1313 d8470559 Michael Hanselmann
1314 a8083063 Iustin Pop
    if node_name not in self._config_data.nodes:
1315 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
1316 a8083063 Iustin Pop
1317 190e3cb6 Guido Trotter
    self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name])
1318 a8083063 Iustin Pop
    del self._config_data.nodes[node_name]
1319 b9f72b4e Iustin Pop
    self._config_data.cluster.serial_no += 1
1320 a8083063 Iustin Pop
    self._WriteConfig()
1321 a8083063 Iustin Pop
1322 a8083063 Iustin Pop
  def ExpandNodeName(self, short_name):
1323 fe698b38 Michael Hanselmann
    """Attempt to expand an incomplete node name.
1324 a8083063 Iustin Pop

1325 a8083063 Iustin Pop
    """
1326 fe698b38 Michael Hanselmann
    # Locking is done in L{ConfigWriter.GetNodeList}
1327 fe698b38 Michael Hanselmann
    return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList())
1328 a8083063 Iustin Pop
1329 f78ede4e Guido Trotter
  def _UnlockedGetNodeInfo(self, node_name):
1330 a8083063 Iustin Pop
    """Get the configuration of a node, as stored in the config.
1331 a8083063 Iustin Pop

1332 c41eea6e Iustin Pop
    This function is for internal use, when the config lock is already
1333 c41eea6e Iustin Pop
    held.
1334 f78ede4e Guido Trotter

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

1337 c41eea6e Iustin Pop
    @rtype: L{objects.Node}
1338 c41eea6e Iustin Pop
    @return: the node object
1339 a8083063 Iustin Pop

1340 a8083063 Iustin Pop
    """
1341 a8083063 Iustin Pop
    if node_name not in self._config_data.nodes:
1342 a8083063 Iustin Pop
      return None
1343 a8083063 Iustin Pop
1344 a8083063 Iustin Pop
    return self._config_data.nodes[node_name]
1345 a8083063 Iustin Pop
1346 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1347 f78ede4e Guido Trotter
  def GetNodeInfo(self, node_name):
1348 f78ede4e Guido Trotter
    """Get the configuration of a node, as stored in the config.
1349 f78ede4e Guido Trotter

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

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

1354 c41eea6e Iustin Pop
    @rtype: L{objects.Node}
1355 c41eea6e Iustin Pop
    @return: the node object
1356 f78ede4e Guido Trotter

1357 f78ede4e Guido Trotter
    """
1358 f78ede4e Guido Trotter
    return self._UnlockedGetNodeInfo(node_name)
1359 f78ede4e Guido Trotter
1360 8bf9e9a5 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1361 8bf9e9a5 Iustin Pop
  def GetNodeInstances(self, node_name):
1362 8bf9e9a5 Iustin Pop
    """Get the instances of a node, as stored in the config.
1363 8bf9e9a5 Iustin Pop

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

1366 8bf9e9a5 Iustin Pop
    @rtype: (list, list)
1367 8bf9e9a5 Iustin Pop
    @return: a tuple with two lists: the primary and the secondary instances
1368 8bf9e9a5 Iustin Pop

1369 8bf9e9a5 Iustin Pop
    """
1370 8bf9e9a5 Iustin Pop
    pri = []
1371 8bf9e9a5 Iustin Pop
    sec = []
1372 8bf9e9a5 Iustin Pop
    for inst in self._config_data.instances.values():
1373 8bf9e9a5 Iustin Pop
      if inst.primary_node == node_name:
1374 8bf9e9a5 Iustin Pop
        pri.append(inst.name)
1375 8bf9e9a5 Iustin Pop
      if node_name in inst.secondary_nodes:
1376 8bf9e9a5 Iustin Pop
        sec.append(inst.name)
1377 8bf9e9a5 Iustin Pop
    return (pri, sec)
1378 8bf9e9a5 Iustin Pop
1379 c71b049c Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
1380 c71b049c Michael Hanselmann
  def GetNodeGroupInstances(self, uuid, primary_only=False):
1381 c71b049c Michael Hanselmann
    """Get the instances of a node group.
1382 c71b049c Michael Hanselmann

1383 c71b049c Michael Hanselmann
    @param uuid: Node group UUID
1384 c71b049c Michael Hanselmann
    @param primary_only: Whether to only consider primary nodes
1385 c71b049c Michael Hanselmann
    @rtype: frozenset
1386 c71b049c Michael Hanselmann
    @return: List of instance names in node group
1387 c71b049c Michael Hanselmann

1388 c71b049c Michael Hanselmann
    """
1389 c71b049c Michael Hanselmann
    if primary_only:
1390 c71b049c Michael Hanselmann
      nodes_fn = lambda inst: [inst.primary_node]
1391 c71b049c Michael Hanselmann
    else:
1392 c71b049c Michael Hanselmann
      nodes_fn = lambda inst: inst.all_nodes
1393 c71b049c Michael Hanselmann
1394 c71b049c Michael Hanselmann
    return frozenset(inst.name
1395 c71b049c Michael Hanselmann
                     for inst in self._config_data.instances.values()
1396 c71b049c Michael Hanselmann
                     for node_name in nodes_fn(inst)
1397 c71b049c Michael Hanselmann
                     if self._UnlockedGetNodeInfo(node_name).group == uuid)
1398 c71b049c Michael Hanselmann
1399 f78ede4e Guido Trotter
  def _UnlockedGetNodeList(self):
1400 a8083063 Iustin Pop
    """Return the list of nodes which are in the configuration.
1401 a8083063 Iustin Pop

1402 c41eea6e Iustin Pop
    This function is for internal use, when the config lock is already
1403 c41eea6e Iustin Pop
    held.
1404 c41eea6e Iustin Pop

1405 c41eea6e Iustin Pop
    @rtype: list
1406 f78ede4e Guido Trotter

1407 a8083063 Iustin Pop
    """
1408 a8083063 Iustin Pop
    return self._config_data.nodes.keys()
1409 a8083063 Iustin Pop
1410 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1411 f78ede4e Guido Trotter
  def GetNodeList(self):
1412 f78ede4e Guido Trotter
    """Return the list of nodes which are in the configuration.
1413 f78ede4e Guido Trotter

1414 f78ede4e Guido Trotter
    """
1415 f78ede4e Guido Trotter
    return self._UnlockedGetNodeList()
1416 f78ede4e Guido Trotter
1417 6819dc49 Iustin Pop
  def _UnlockedGetOnlineNodeList(self):
1418 94a02bb5 Iustin Pop
    """Return the list of nodes which are online.
1419 94a02bb5 Iustin Pop

1420 94a02bb5 Iustin Pop
    """
1421 94a02bb5 Iustin Pop
    all_nodes = [self._UnlockedGetNodeInfo(node)
1422 94a02bb5 Iustin Pop
                 for node in self._UnlockedGetNodeList()]
1423 94a02bb5 Iustin Pop
    return [node.name for node in all_nodes if not node.offline]
1424 94a02bb5 Iustin Pop
1425 94a02bb5 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1426 6819dc49 Iustin Pop
  def GetOnlineNodeList(self):
1427 6819dc49 Iustin Pop
    """Return the list of nodes which are online.
1428 6819dc49 Iustin Pop

1429 6819dc49 Iustin Pop
    """
1430 6819dc49 Iustin Pop
    return self._UnlockedGetOnlineNodeList()
1431 6819dc49 Iustin Pop
1432 6819dc49 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1433 075b62ca Iustin Pop
  def GetVmCapableNodeList(self):
1434 075b62ca Iustin Pop
    """Return the list of nodes which are not vm capable.
1435 075b62ca Iustin Pop

1436 075b62ca Iustin Pop
    """
1437 075b62ca Iustin Pop
    all_nodes = [self._UnlockedGetNodeInfo(node)
1438 075b62ca Iustin Pop
                 for node in self._UnlockedGetNodeList()]
1439 075b62ca Iustin Pop
    return [node.name for node in all_nodes if node.vm_capable]
1440 075b62ca Iustin Pop
1441 075b62ca Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1442 8bf9e9a5 Iustin Pop
  def GetNonVmCapableNodeList(self):
1443 8bf9e9a5 Iustin Pop
    """Return the list of nodes which are not vm capable.
1444 8bf9e9a5 Iustin Pop

1445 8bf9e9a5 Iustin Pop
    """
1446 8bf9e9a5 Iustin Pop
    all_nodes = [self._UnlockedGetNodeInfo(node)
1447 8bf9e9a5 Iustin Pop
                 for node in self._UnlockedGetNodeList()]
1448 8bf9e9a5 Iustin Pop
    return [node.name for node in all_nodes if not node.vm_capable]
1449 8bf9e9a5 Iustin Pop
1450 8bf9e9a5 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1451 d65e5776 Iustin Pop
  def GetAllNodesInfo(self):
1452 d65e5776 Iustin Pop
    """Get the configuration of all nodes.
1453 d65e5776 Iustin Pop

1454 d65e5776 Iustin Pop
    @rtype: dict
1455 ec0292f1 Iustin Pop
    @return: dict of (node, node_info), where node_info is what
1456 d65e5776 Iustin Pop
              would GetNodeInfo return for the node
1457 d65e5776 Iustin Pop

1458 d65e5776 Iustin Pop
    """
1459 d65e5776 Iustin Pop
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
1460 d65e5776 Iustin Pop
                    for node in self._UnlockedGetNodeList()])
1461 d65e5776 Iustin Pop
    return my_dict
1462 d65e5776 Iustin Pop
1463 9d5b1371 Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
1464 9d5b1371 Michael Hanselmann
  def GetNodeGroupsFromNodes(self, nodes):
1465 9d5b1371 Michael Hanselmann
    """Returns groups for a list of nodes.
1466 9d5b1371 Michael Hanselmann

1467 9d5b1371 Michael Hanselmann
    @type nodes: list of string
1468 9d5b1371 Michael Hanselmann
    @param nodes: List of node names
1469 9d5b1371 Michael Hanselmann
    @rtype: frozenset
1470 9d5b1371 Michael Hanselmann

1471 9d5b1371 Michael Hanselmann
    """
1472 9d5b1371 Michael Hanselmann
    return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes)
1473 9d5b1371 Michael Hanselmann
1474 23f06b2b Iustin Pop
  def _UnlockedGetMasterCandidateStats(self, exceptions=None):
1475 ec0292f1 Iustin Pop
    """Get the number of current and maximum desired and possible candidates.
1476 ec0292f1 Iustin Pop

1477 23f06b2b Iustin Pop
    @type exceptions: list
1478 23f06b2b Iustin Pop
    @param exceptions: if passed, list of nodes that should be ignored
1479 ec0292f1 Iustin Pop
    @rtype: tuple
1480 e623dbe3 Guido Trotter
    @return: tuple of (current, desired and possible, possible)
1481 ec0292f1 Iustin Pop

1482 ec0292f1 Iustin Pop
    """
1483 e623dbe3 Guido Trotter
    mc_now = mc_should = mc_max = 0
1484 23f06b2b Iustin Pop
    for node in self._config_data.nodes.values():
1485 23f06b2b Iustin Pop
      if exceptions and node.name in exceptions:
1486 23f06b2b Iustin Pop
        continue
1487 490acd18 Iustin Pop
      if not (node.offline or node.drained) and node.master_capable:
1488 ec0292f1 Iustin Pop
        mc_max += 1
1489 ec0292f1 Iustin Pop
      if node.master_candidate:
1490 ec0292f1 Iustin Pop
        mc_now += 1
1491 e623dbe3 Guido Trotter
    mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size)
1492 e623dbe3 Guido Trotter
    return (mc_now, mc_should, mc_max)
1493 ec0292f1 Iustin Pop
1494 ec0292f1 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
1495 23f06b2b Iustin Pop
  def GetMasterCandidateStats(self, exceptions=None):
1496 ec0292f1 Iustin Pop
    """Get the number of current and maximum possible candidates.
1497 ec0292f1 Iustin Pop

1498 ec0292f1 Iustin Pop
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
1499 ec0292f1 Iustin Pop

1500 23f06b2b Iustin Pop
    @type exceptions: list
1501 23f06b2b Iustin Pop
    @param exceptions: if passed, list of nodes that should be ignored
1502 ec0292f1 Iustin Pop
    @rtype: tuple
1503 ec0292f1 Iustin Pop
    @return: tuple of (current, max)
1504 ec0292f1 Iustin Pop

1505 ec0292f1 Iustin Pop
    """
1506 23f06b2b Iustin Pop
    return self._UnlockedGetMasterCandidateStats(exceptions)
1507 ec0292f1 Iustin Pop
1508 ec0292f1 Iustin Pop
  @locking.ssynchronized(_config_lock)
1509 44485f49 Guido Trotter
  def MaintainCandidatePool(self, exceptions):
1510 ec0292f1 Iustin Pop
    """Try to grow the candidate pool to the desired size.
1511 ec0292f1 Iustin Pop

1512 44485f49 Guido Trotter
    @type exceptions: list
1513 44485f49 Guido Trotter
    @param exceptions: if passed, list of nodes that should be ignored
1514 ec0292f1 Iustin Pop
    @rtype: list
1515 ee513a66 Iustin Pop
    @return: list with the adjusted nodes (L{objects.Node} instances)
1516 ec0292f1 Iustin Pop

1517 ec0292f1 Iustin Pop
    """
1518 44485f49 Guido Trotter
    mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
1519 ec0292f1 Iustin Pop
    mod_list = []
1520 ec0292f1 Iustin Pop
    if mc_now < mc_max:
1521 ec0292f1 Iustin Pop
      node_list = self._config_data.nodes.keys()
1522 ec0292f1 Iustin Pop
      random.shuffle(node_list)
1523 ec0292f1 Iustin Pop
      for name in node_list:
1524 ec0292f1 Iustin Pop
        if mc_now >= mc_max:
1525 ec0292f1 Iustin Pop
          break
1526 ec0292f1 Iustin Pop
        node = self._config_data.nodes[name]
1527 44485f49 Guido Trotter
        if (node.master_candidate or node.offline or node.drained or
1528 490acd18 Iustin Pop
            node.name in exceptions or not node.master_capable):
1529 ec0292f1 Iustin Pop
          continue
1530 ee513a66 Iustin Pop
        mod_list.append(node)
1531 ec0292f1 Iustin Pop
        node.master_candidate = True
1532 ec0292f1 Iustin Pop
        node.serial_no += 1
1533 ec0292f1 Iustin Pop
        mc_now += 1
1534 ec0292f1 Iustin Pop
      if mc_now != mc_max:
1535 ec0292f1 Iustin Pop
        # this should not happen
1536 ec0292f1 Iustin Pop
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
1537 ec0292f1 Iustin Pop
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
1538 ec0292f1 Iustin Pop
      if mod_list:
1539 ec0292f1 Iustin Pop
        self._config_data.cluster.serial_no += 1
1540 ec0292f1 Iustin Pop
        self._WriteConfig()
1541 ec0292f1 Iustin Pop
1542 ec0292f1 Iustin Pop
    return mod_list
1543 ec0292f1 Iustin Pop
1544 190e3cb6 Guido Trotter
  def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid):
1545 190e3cb6 Guido Trotter
    """Add a given node to the specified group.
1546 190e3cb6 Guido Trotter

1547 190e3cb6 Guido Trotter
    """
1548 190e3cb6 Guido Trotter
    if nodegroup_uuid not in self._config_data.nodegroups:
1549 190e3cb6 Guido Trotter
      # This can happen if a node group gets deleted between its lookup and
1550 190e3cb6 Guido Trotter
      # when we're adding the first node to it, since we don't keep a lock in
1551 190e3cb6 Guido Trotter
      # the meantime. It's ok though, as we'll fail cleanly if the node group
1552 190e3cb6 Guido Trotter
      # is not found anymore.
1553 f936c153 Iustin Pop
      raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid)
1554 190e3cb6 Guido Trotter
    if node_name not in self._config_data.nodegroups[nodegroup_uuid].members:
1555 190e3cb6 Guido Trotter
      self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
1556 190e3cb6 Guido Trotter
1557 190e3cb6 Guido Trotter
  def _UnlockedRemoveNodeFromGroup(self, node):
1558 190e3cb6 Guido Trotter
    """Remove a given node from its group.
1559 190e3cb6 Guido Trotter

1560 190e3cb6 Guido Trotter
    """
1561 f936c153 Iustin Pop
    nodegroup = node.group
1562 190e3cb6 Guido Trotter
    if nodegroup not in self._config_data.nodegroups:
1563 f936c153 Iustin Pop
      logging.warning("Warning: node '%s' has unknown node group '%s'"
1564 190e3cb6 Guido Trotter
                      " (while being removed from it)", node.name, nodegroup)
1565 190e3cb6 Guido Trotter
    nodegroup_obj = self._config_data.nodegroups[nodegroup]
1566 190e3cb6 Guido Trotter
    if node.name not in nodegroup_obj.members:
1567 f936c153 Iustin Pop
      logging.warning("Warning: node '%s' not a member of its node group '%s'"
1568 190e3cb6 Guido Trotter
                      " (while being removed from it)", node.name, nodegroup)
1569 190e3cb6 Guido Trotter
    else:
1570 190e3cb6 Guido Trotter
      nodegroup_obj.members.remove(node.name)
1571 190e3cb6 Guido Trotter
1572 a8083063 Iustin Pop
  def _BumpSerialNo(self):
1573 a8083063 Iustin Pop
    """Bump up the serial number of the config.
1574 a8083063 Iustin Pop

1575 a8083063 Iustin Pop
    """
1576 9d38c6e1 Iustin Pop
    self._config_data.serial_no += 1
1577 d693c864 Iustin Pop
    self._config_data.mtime = time.time()
1578 a8083063 Iustin Pop
1579 76d5d3a3 Iustin Pop
  def _AllUUIDObjects(self):
1580 76d5d3a3 Iustin Pop
    """Returns all objects with uuid attributes.
1581 76d5d3a3 Iustin Pop

1582 76d5d3a3 Iustin Pop
    """
1583 76d5d3a3 Iustin Pop
    return (self._config_data.instances.values() +
1584 76d5d3a3 Iustin Pop
            self._config_data.nodes.values() +
1585 3df43542 Guido Trotter
            self._config_data.nodegroups.values() +
1586 76d5d3a3 Iustin Pop
            [self._config_data.cluster])
1587 76d5d3a3 Iustin Pop
1588 eb180fe2 Iustin Pop
  def _OpenConfig(self, accept_foreign):
1589 a8083063 Iustin Pop
    """Read the config data from disk.
1590 a8083063 Iustin Pop

1591 a8083063 Iustin Pop
    """
1592 13998ef2 Michael Hanselmann
    raw_data = utils.ReadFile(self._cfg_file)
1593 13998ef2 Michael Hanselmann
1594 a8083063 Iustin Pop
    try:
1595 13998ef2 Michael Hanselmann
      data = objects.ConfigData.FromDict(serializer.Load(raw_data))
1596 13998ef2 Michael Hanselmann
    except Exception, err:
1597 13998ef2 Michael Hanselmann
      raise errors.ConfigurationError(err)
1598 5b263ed7 Michael Hanselmann
1599 5b263ed7 Michael Hanselmann
    # Make sure the configuration has the right version
1600 5b263ed7 Michael Hanselmann
    _ValidateConfig(data)
1601 5b263ed7 Michael Hanselmann
1602 a8083063 Iustin Pop
    if (not hasattr(data, 'cluster') or
1603 243cdbcc Michael Hanselmann
        not hasattr(data.cluster, 'rsahostkeypub')):
1604 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Incomplete configuration"
1605 243cdbcc Michael Hanselmann
                                      " (missing cluster.rsahostkeypub)")
1606 90d726a8 Iustin Pop
1607 eb180fe2 Iustin Pop
    if data.cluster.master_node != self._my_hostname and not accept_foreign:
1608 eb180fe2 Iustin Pop
      msg = ("The configuration denotes node %s as master, while my"
1609 eb180fe2 Iustin Pop
             " hostname is %s; opening a foreign configuration is only"
1610 eb180fe2 Iustin Pop
             " possible in accept_foreign mode" %
1611 eb180fe2 Iustin Pop
             (data.cluster.master_node, self._my_hostname))
1612 eb180fe2 Iustin Pop
      raise errors.ConfigurationError(msg)
1613 eb180fe2 Iustin Pop
1614 90d726a8 Iustin Pop
    # Upgrade configuration if needed
1615 90d726a8 Iustin Pop
    data.UpgradeConfig()
1616 90d726a8 Iustin Pop
1617 a8083063 Iustin Pop
    self._config_data = data
1618 3c7f6c44 Iustin Pop
    # reset the last serial as -1 so that the next write will cause
1619 0779e3aa Iustin Pop
    # ssconf update
1620 0779e3aa Iustin Pop
    self._last_cluster_serial = -1
1621 a8083063 Iustin Pop
1622 76d5d3a3 Iustin Pop
    # And finally run our (custom) config upgrade sequence
1623 76d5d3a3 Iustin Pop
    self._UpgradeConfig()
1624 76d5d3a3 Iustin Pop
1625 bd407597 Iustin Pop
    self._cfg_id = utils.GetFileID(path=self._cfg_file)
1626 bd407597 Iustin Pop
1627 76d5d3a3 Iustin Pop
  def _UpgradeConfig(self):
1628 76d5d3a3 Iustin Pop
    """Run upgrade steps that cannot be done purely in the objects.
1629 76d5d3a3 Iustin Pop

1630 76d5d3a3 Iustin Pop
    This is because some data elements need uniqueness across the
1631 76d5d3a3 Iustin Pop
    whole configuration, etc.
1632 76d5d3a3 Iustin Pop

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

1639 76d5d3a3 Iustin Pop
    """
1640 76d5d3a3 Iustin Pop
    modified = False
1641 76d5d3a3 Iustin Pop
    for item in self._AllUUIDObjects():
1642 76d5d3a3 Iustin Pop
      if item.uuid is None:
1643 4fae38c5 Guido Trotter
        item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
1644 76d5d3a3 Iustin Pop
        modified = True
1645 f9e81396 Guido Trotter
    if not self._config_data.nodegroups:
1646 75cf411a Adeodato Simo
      default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME
1647 75cf411a Adeodato Simo
      default_nodegroup = objects.NodeGroup(name=default_nodegroup_name,
1648 75cf411a Adeodato Simo
                                            members=[])
1649 e11a1b77 Adeodato Simo
      self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True)
1650 f9e81396 Guido Trotter
      modified = True
1651 190e3cb6 Guido Trotter
    for node in self._config_data.nodes.values():
1652 f936c153 Iustin Pop
      if not node.group:
1653 f936c153 Iustin Pop
        node.group = self.LookupNodeGroup(None)
1654 190e3cb6 Guido Trotter
        modified = True
1655 190e3cb6 Guido Trotter
      # This is technically *not* an upgrade, but needs to be done both when
1656 190e3cb6 Guido Trotter
      # nodegroups are being added, and upon normally loading the config,
1657 190e3cb6 Guido Trotter
      # because the members list of a node group is discarded upon
1658 190e3cb6 Guido Trotter
      # serializing/deserializing the object.
1659 f936c153 Iustin Pop
      self._UnlockedAddNodeToGroup(node.name, node.group)
1660 76d5d3a3 Iustin Pop
    if modified:
1661 76d5d3a3 Iustin Pop
      self._WriteConfig()
1662 4fae38c5 Guido Trotter
      # This is ok even if it acquires the internal lock, as _UpgradeConfig is
1663 4fae38c5 Guido Trotter
      # only called at config init time, without the lock held
1664 4fae38c5 Guido Trotter
      self.DropECReservations(_UPGRADE_CONFIG_JID)
1665 4fae38c5 Guido Trotter
1666 a4eae71f Michael Hanselmann
  def _DistributeConfig(self, feedback_fn):
1667 a8083063 Iustin Pop
    """Distribute the configuration to the other nodes.
1668 a8083063 Iustin Pop

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

1672 a8083063 Iustin Pop
    """
1673 a8083063 Iustin Pop
    if self._offline:
1674 a8083063 Iustin Pop
      return True
1675 a4eae71f Michael Hanselmann
1676 a8083063 Iustin Pop
    bad = False
1677 a8083063 Iustin Pop
1678 6a5b8b4b Iustin Pop
    node_list = []
1679 6a5b8b4b Iustin Pop
    addr_list = []
1680 6a5b8b4b Iustin Pop
    myhostname = self._my_hostname
1681 6b294c53 Iustin Pop
    # we can skip checking whether _UnlockedGetNodeInfo returns None
1682 6b294c53 Iustin Pop
    # since the node list comes from _UnlocketGetNodeList, and we are
1683 6b294c53 Iustin Pop
    # called with the lock held, so no modifications should take place
1684 6b294c53 Iustin Pop
    # in between
1685 6a5b8b4b Iustin Pop
    for node_name in self._UnlockedGetNodeList():
1686 6a5b8b4b Iustin Pop
      if node_name == myhostname:
1687 6a5b8b4b Iustin Pop
        continue
1688 6a5b8b4b Iustin Pop
      node_info = self._UnlockedGetNodeInfo(node_name)
1689 6a5b8b4b Iustin Pop
      if not node_info.master_candidate:
1690 6a5b8b4b Iustin Pop
        continue
1691 6a5b8b4b Iustin Pop
      node_list.append(node_info.name)
1692 6a5b8b4b Iustin Pop
      addr_list.append(node_info.primary_ip)
1693 6b294c53 Iustin Pop
1694 6a5b8b4b Iustin Pop
    result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
1695 6a5b8b4b Iustin Pop
                                            address_list=addr_list)
1696 1b54fc6c Guido Trotter
    for to_node, to_result in result.items():
1697 3cebe102 Michael Hanselmann
      msg = to_result.fail_msg
1698 1b54fc6c Guido Trotter
      if msg:
1699 1b54fc6c Guido Trotter
        msg = ("Copy of file %s to node %s failed: %s" %
1700 dd7db360 Iustin Pop
               (self._cfg_file, to_node, msg))
1701 1b54fc6c Guido Trotter
        logging.error(msg)
1702 a4eae71f Michael Hanselmann
1703 a4eae71f Michael Hanselmann
        if feedback_fn:
1704 a4eae71f Michael Hanselmann
          feedback_fn(msg)
1705 a4eae71f Michael Hanselmann
1706 a8083063 Iustin Pop
        bad = True
1707 a4eae71f Michael Hanselmann
1708 a8083063 Iustin Pop
    return not bad
1709 a8083063 Iustin Pop
1710 a4eae71f Michael Hanselmann
  def _WriteConfig(self, destination=None, feedback_fn=None):
1711 a8083063 Iustin Pop
    """Write the configuration data to persistent storage.
1712 a8083063 Iustin Pop

1713 a8083063 Iustin Pop
    """
1714 a4eae71f Michael Hanselmann
    assert feedback_fn is None or callable(feedback_fn)
1715 a4eae71f Michael Hanselmann
1716 d2231b8c Iustin Pop
    # Warn on config errors, but don't abort the save - the
1717 d2231b8c Iustin Pop
    # configuration has already been modified, and we can't revert;
1718 d2231b8c Iustin Pop
    # the best we can do is to warn the user and save as is, leaving
1719 d2231b8c Iustin Pop
    # recovery to the user
1720 4a89c54a Iustin Pop
    config_errors = self._UnlockedVerifyConfig()
1721 4a89c54a Iustin Pop
    if config_errors:
1722 d2231b8c Iustin Pop
      errmsg = ("Configuration data is not consistent: %s" %
1723 1f864b60 Iustin Pop
                (utils.CommaJoin(config_errors)))
1724 d2231b8c Iustin Pop
      logging.critical(errmsg)
1725 d2231b8c Iustin Pop
      if feedback_fn:
1726 d2231b8c Iustin Pop
        feedback_fn(errmsg)
1727 d2231b8c Iustin Pop
1728 a8083063 Iustin Pop
    if destination is None:
1729 a8083063 Iustin Pop
      destination = self._cfg_file
1730 a8083063 Iustin Pop
    self._BumpSerialNo()
1731 8d14b30d Iustin Pop
    txt = serializer.Dump(self._config_data.ToDict())
1732 13998ef2 Michael Hanselmann
1733 e60c73a1 René Nussbaumer
    getents = self._getents()
1734 bd407597 Iustin Pop
    try:
1735 bd407597 Iustin Pop
      fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
1736 bd407597 Iustin Pop
                               close=False, gid=getents.confd_gid, mode=0640)
1737 bd407597 Iustin Pop
    except errors.LockError:
1738 bd407597 Iustin Pop
      raise errors.ConfigurationError("The configuration file has been"
1739 bd407597 Iustin Pop
                                      " modified since the last write, cannot"
1740 bd407597 Iustin Pop
                                      " update")
1741 bd407597 Iustin Pop
    try:
1742 bd407597 Iustin Pop
      self._cfg_id = utils.GetFileID(fd=fd)
1743 bd407597 Iustin Pop
    finally:
1744 bd407597 Iustin Pop
      os.close(fd)
1745 13998ef2 Michael Hanselmann
1746 14e15659 Iustin Pop
    self.write_count += 1
1747 3d3a04bc Iustin Pop
1748 f56618e0 Iustin Pop
    # and redistribute the config file to master candidates
1749 a4eae71f Michael Hanselmann
    self._DistributeConfig(feedback_fn)
1750 a8083063 Iustin Pop
1751 54d1a06e Michael Hanselmann
    # Write ssconf files on all nodes (including locally)
1752 0779e3aa Iustin Pop
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
1753 d9a855f1 Michael Hanselmann
      if not self._offline:
1754 cd34faf2 Michael Hanselmann
        result = rpc.RpcRunner.call_write_ssconf_files(
1755 6819dc49 Iustin Pop
          self._UnlockedGetOnlineNodeList(),
1756 e1e75d00 Iustin Pop
          self._UnlockedGetSsconfValues())
1757 a4eae71f Michael Hanselmann
1758 e1e75d00 Iustin Pop
        for nname, nresu in result.items():
1759 3cebe102 Michael Hanselmann
          msg = nresu.fail_msg
1760 e1e75d00 Iustin Pop
          if msg:
1761 a4eae71f Michael Hanselmann
            errmsg = ("Error while uploading ssconf files to"
1762 a4eae71f Michael Hanselmann
                      " node %s: %s" % (nname, msg))
1763 a4eae71f Michael Hanselmann
            logging.warning(errmsg)
1764 a4eae71f Michael Hanselmann
1765 a4eae71f Michael Hanselmann
            if feedback_fn:
1766 a4eae71f Michael Hanselmann
              feedback_fn(errmsg)
1767 a4eae71f Michael Hanselmann
1768 0779e3aa Iustin Pop
      self._last_cluster_serial = self._config_data.cluster.serial_no
1769 54d1a06e Michael Hanselmann
1770 03d1dba2 Michael Hanselmann
  def _UnlockedGetSsconfValues(self):
1771 054596f0 Iustin Pop
    """Return the values needed by ssconf.
1772 054596f0 Iustin Pop

1773 054596f0 Iustin Pop
    @rtype: dict
1774 054596f0 Iustin Pop
    @return: a dictionary with keys the ssconf names and values their
1775 054596f0 Iustin Pop
        associated value
1776 054596f0 Iustin Pop

1777 054596f0 Iustin Pop
    """
1778 a3316e4a Iustin Pop
    fn = "\n".join
1779 81a49123 Iustin Pop
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1780 a3316e4a Iustin Pop
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
1781 a3316e4a Iustin Pop
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1782 c3029d0a Luca Bigliardi
    node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
1783 5909fb97 Luca Bigliardi
                    for ninfo in node_info]
1784 c3029d0a Luca Bigliardi
    node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
1785 5909fb97 Luca Bigliardi
                    for ninfo in node_info]
1786 a3316e4a Iustin Pop
1787 81a49123 Iustin Pop
    instance_data = fn(instance_names)
1788 a3316e4a Iustin Pop
    off_data = fn(node.name for node in node_info if node.offline)
1789 81a49123 Iustin Pop
    on_data = fn(node.name for node in node_info if not node.offline)
1790 a3316e4a Iustin Pop
    mc_data = fn(node.name for node in node_info if node.master_candidate)
1791 8113a52e Luca Bigliardi
    mc_ips_data = fn(node.primary_ip for node in node_info
1792 8113a52e Luca Bigliardi
                     if node.master_candidate)
1793 a3316e4a Iustin Pop
    node_data = fn(node_names)
1794 f9780ccd Luca Bigliardi
    node_pri_ips_data = fn(node_pri_ips)
1795 f9780ccd Luca Bigliardi
    node_snd_ips_data = fn(node_snd_ips)
1796 f56618e0 Iustin Pop
1797 054596f0 Iustin Pop
    cluster = self._config_data.cluster
1798 5d60b3bd Iustin Pop
    cluster_tags = fn(cluster.GetTags())
1799 4f7a6a10 Iustin Pop
1800 4f7a6a10 Iustin Pop
    hypervisor_list = fn(cluster.enabled_hypervisors)
1801 4f7a6a10 Iustin Pop
1802 0fbae49a Balazs Lecz
    uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
1803 0fbae49a Balazs Lecz
1804 6f076453 Guido Trotter
    nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in
1805 6f076453 Guido Trotter
                  self._config_data.nodegroups.values()]
1806 6f076453 Guido Trotter
    nodegroups_data = fn(utils.NiceSort(nodegroups))
1807 6f076453 Guido Trotter
1808 2afc9238 Iustin Pop
    ssconf_values = {
1809 054596f0 Iustin Pop
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
1810 5d60b3bd Iustin Pop
      constants.SS_CLUSTER_TAGS: cluster_tags,
1811 054596f0 Iustin Pop
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1812 4b97f902 Apollon Oikonomopoulos
      constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir,
1813 a3316e4a Iustin Pop
      constants.SS_MASTER_CANDIDATES: mc_data,
1814 8113a52e Luca Bigliardi
      constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data,
1815 054596f0 Iustin Pop
      constants.SS_MASTER_IP: cluster.master_ip,
1816 054596f0 Iustin Pop
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
1817 054596f0 Iustin Pop
      constants.SS_MASTER_NODE: cluster.master_node,
1818 a3316e4a Iustin Pop
      constants.SS_NODE_LIST: node_data,
1819 f9780ccd Luca Bigliardi
      constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data,
1820 f9780ccd Luca Bigliardi
      constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data,
1821 a3316e4a Iustin Pop
      constants.SS_OFFLINE_NODES: off_data,
1822 81a49123 Iustin Pop
      constants.SS_ONLINE_NODES: on_data,
1823 868a98ca Manuel Franceschini
      constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
1824 81a49123 Iustin Pop
      constants.SS_INSTANCE_LIST: instance_data,
1825 8a113c7a Iustin Pop
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1826 4f7a6a10 Iustin Pop
      constants.SS_HYPERVISOR_LIST: hypervisor_list,
1827 5c465a95 Iustin Pop
      constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
1828 0fbae49a Balazs Lecz
      constants.SS_UID_POOL: uid_pool,
1829 6f076453 Guido Trotter
      constants.SS_NODEGROUPS: nodegroups_data,
1830 03d1dba2 Michael Hanselmann
      }
1831 2afc9238 Iustin Pop
    bad_values = [(k, v) for k, v in ssconf_values.items()
1832 2afc9238 Iustin Pop
                  if not isinstance(v, (str, basestring))]
1833 2afc9238 Iustin Pop
    if bad_values:
1834 2afc9238 Iustin Pop
      err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values)
1835 2afc9238 Iustin Pop
      raise errors.ConfigurationError("Some ssconf key(s) have non-string"
1836 2afc9238 Iustin Pop
                                      " values: %s" % err)
1837 2afc9238 Iustin Pop
    return ssconf_values
1838 03d1dba2 Michael Hanselmann
1839 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1840 d367b66c Manuel Franceschini
  def GetSsconfValues(self):
1841 d367b66c Manuel Franceschini
    """Wrapper using lock around _UnlockedGetSsconf().
1842 d367b66c Manuel Franceschini

1843 d367b66c Manuel Franceschini
    """
1844 d367b66c Manuel Franceschini
    return self._UnlockedGetSsconfValues()
1845 d367b66c Manuel Franceschini
1846 d367b66c Manuel Franceschini
  @locking.ssynchronized(_config_lock, shared=1)
1847 a8083063 Iustin Pop
  def GetVGName(self):
1848 a8083063 Iustin Pop
    """Return the volume group name.
1849 a8083063 Iustin Pop

1850 a8083063 Iustin Pop
    """
1851 a8083063 Iustin Pop
    return self._config_data.cluster.volume_group_name
1852 a8083063 Iustin Pop
1853 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1854 89ff8e15 Manuel Franceschini
  def SetVGName(self, vg_name):
1855 89ff8e15 Manuel Franceschini
    """Set the volume group name.
1856 89ff8e15 Manuel Franceschini

1857 89ff8e15 Manuel Franceschini
    """
1858 2d4011cd Manuel Franceschini
    self._config_data.cluster.volume_group_name = vg_name
1859 b9f72b4e Iustin Pop
    self._config_data.cluster.serial_no += 1
1860 89ff8e15 Manuel Franceschini
    self._WriteConfig()
1861 89ff8e15 Manuel Franceschini
1862 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1863 9e33896b Luca Bigliardi
  def GetDRBDHelper(self):
1864 9e33896b Luca Bigliardi
    """Return DRBD usermode helper.
1865 9e33896b Luca Bigliardi

1866 9e33896b Luca Bigliardi
    """
1867 9e33896b Luca Bigliardi
    return self._config_data.cluster.drbd_usermode_helper
1868 9e33896b Luca Bigliardi
1869 9e33896b Luca Bigliardi
  @locking.ssynchronized(_config_lock)
1870 9e33896b Luca Bigliardi
  def SetDRBDHelper(self, drbd_helper):
1871 9e33896b Luca Bigliardi
    """Set DRBD usermode helper.
1872 9e33896b Luca Bigliardi

1873 9e33896b Luca Bigliardi
    """
1874 9e33896b Luca Bigliardi
    self._config_data.cluster.drbd_usermode_helper = drbd_helper
1875 9e33896b Luca Bigliardi
    self._config_data.cluster.serial_no += 1
1876 9e33896b Luca Bigliardi
    self._WriteConfig()
1877 9e33896b Luca Bigliardi
1878 9e33896b Luca Bigliardi
  @locking.ssynchronized(_config_lock, shared=1)
1879 a8083063 Iustin Pop
  def GetMACPrefix(self):
1880 a8083063 Iustin Pop
    """Return the mac prefix.
1881 a8083063 Iustin Pop

1882 a8083063 Iustin Pop
    """
1883 a8083063 Iustin Pop
    return self._config_data.cluster.mac_prefix
1884 62779dd0 Iustin Pop
1885 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1886 62779dd0 Iustin Pop
  def GetClusterInfo(self):
1887 5bbd3f7f Michael Hanselmann
    """Returns information about the cluster
1888 62779dd0 Iustin Pop

1889 c41eea6e Iustin Pop
    @rtype: L{objects.Cluster}
1890 c41eea6e Iustin Pop
    @return: the cluster object
1891 62779dd0 Iustin Pop

1892 62779dd0 Iustin Pop
    """
1893 62779dd0 Iustin Pop
    return self._config_data.cluster
1894 e00fb268 Iustin Pop
1895 51cb1581 Luca Bigliardi
  @locking.ssynchronized(_config_lock, shared=1)
1896 51cb1581 Luca Bigliardi
  def HasAnyDiskOfType(self, dev_type):
1897 51cb1581 Luca Bigliardi
    """Check if in there is at disk of the given type in the configuration.
1898 51cb1581 Luca Bigliardi

1899 51cb1581 Luca Bigliardi
    """
1900 51cb1581 Luca Bigliardi
    return self._config_data.HasAnyDiskOfType(dev_type)
1901 51cb1581 Luca Bigliardi
1902 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1903 a4eae71f Michael Hanselmann
  def Update(self, target, feedback_fn):
1904 e00fb268 Iustin Pop
    """Notify function to be called after updates.
1905 e00fb268 Iustin Pop

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

1912 c41eea6e Iustin Pop
    @param target: an instance of either L{objects.Cluster},
1913 c41eea6e Iustin Pop
        L{objects.Node} or L{objects.Instance} which is existing in
1914 c41eea6e Iustin Pop
        the cluster
1915 a4eae71f Michael Hanselmann
    @param feedback_fn: Callable feedback function
1916 c41eea6e Iustin Pop

1917 e00fb268 Iustin Pop
    """
1918 e00fb268 Iustin Pop
    if self._config_data is None:
1919 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Configuration file not read,"
1920 3ecf6786 Iustin Pop
                                   " cannot save.")
1921 f34901f8 Iustin Pop
    update_serial = False
1922 e00fb268 Iustin Pop
    if isinstance(target, objects.Cluster):
1923 e00fb268 Iustin Pop
      test = target == self._config_data.cluster
1924 e00fb268 Iustin Pop
    elif isinstance(target, objects.Node):
1925 e00fb268 Iustin Pop
      test = target in self._config_data.nodes.values()
1926 f34901f8 Iustin Pop
      update_serial = True
1927 e00fb268 Iustin Pop
    elif isinstance(target, objects.Instance):
1928 e00fb268 Iustin Pop
      test = target in self._config_data.instances.values()
1929 e11a1b77 Adeodato Simo
    elif isinstance(target, objects.NodeGroup):
1930 e11a1b77 Adeodato Simo
      test = target in self._config_data.nodegroups.values()
1931 e00fb268 Iustin Pop
    else:
1932 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
1933 3ecf6786 Iustin Pop
                                   " ConfigWriter.Update" % type(target))
1934 e00fb268 Iustin Pop
    if not test:
1935 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Configuration updated since object"
1936 3ecf6786 Iustin Pop
                                      " has been read or unknown object")
1937 f34901f8 Iustin Pop
    target.serial_no += 1
1938 d693c864 Iustin Pop
    target.mtime = now = time.time()
1939 f34901f8 Iustin Pop
1940 cff4c037 Iustin Pop
    if update_serial:
1941 f34901f8 Iustin Pop
      # for node updates, we need to increase the cluster serial too
1942 f34901f8 Iustin Pop
      self._config_data.cluster.serial_no += 1
1943 d693c864 Iustin Pop
      self._config_data.cluster.mtime = now
1944 b989e85d Iustin Pop
1945 61cf6b5e Iustin Pop
    if isinstance(target, objects.Instance):
1946 61cf6b5e Iustin Pop
      self._UnlockedReleaseDRBDMinors(target.name)
1947 61cf6b5e Iustin Pop
1948 a4eae71f Michael Hanselmann
    self._WriteConfig(feedback_fn=feedback_fn)
1949 73064714 Guido Trotter
1950 73064714 Guido Trotter
  @locking.ssynchronized(_config_lock)
1951 73064714 Guido Trotter
  def DropECReservations(self, ec_id):
1952 73064714 Guido Trotter
    """Drop per-execution-context reservations
1953 73064714 Guido Trotter

1954 73064714 Guido Trotter
    """
1955 d8aee57e Iustin Pop
    for rm in self._all_rms:
1956 d8aee57e Iustin Pop
      rm.DropECReservations(ec_id)