Statistics
| Branch: | Tag: | Revision:

root / lib / config.py @ 821d1bd1

History | View | Annotate | Download (38.2 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 a8083063 Iustin Pop
# Copyright (C) 2006, 2007 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 a8083063 Iustin Pop
import os
35 a8083063 Iustin Pop
import tempfile
36 a8083063 Iustin Pop
import random
37 d8470559 Michael Hanselmann
import logging
38 a8083063 Iustin Pop
39 a8083063 Iustin Pop
from ganeti import errors
40 f78ede4e Guido Trotter
from ganeti import locking
41 a8083063 Iustin Pop
from ganeti import utils
42 a8083063 Iustin Pop
from ganeti import constants
43 a8083063 Iustin Pop
from ganeti import rpc
44 a8083063 Iustin Pop
from ganeti import objects
45 8d14b30d Iustin Pop
from ganeti import serializer
46 243cdbcc Michael Hanselmann
47 243cdbcc Michael Hanselmann
48 f78ede4e Guido Trotter
_config_lock = locking.SharedLock()
49 f78ede4e Guido Trotter
50 f78ede4e Guido Trotter
51 5b263ed7 Michael Hanselmann
def _ValidateConfig(data):
52 c41eea6e Iustin Pop
  """Verifies that a configuration objects looks valid.
53 c41eea6e Iustin Pop

54 c41eea6e Iustin Pop
  This only verifies the version of the configuration.
55 c41eea6e Iustin Pop

56 c41eea6e Iustin Pop
  @raise errors.ConfigurationError: if the version differs from what
57 c41eea6e Iustin Pop
      we expect
58 c41eea6e Iustin Pop

59 c41eea6e Iustin Pop
  """
60 5b263ed7 Michael Hanselmann
  if data.version != constants.CONFIG_VERSION:
61 243cdbcc Michael Hanselmann
    raise errors.ConfigurationError("Cluster configuration version"
62 243cdbcc Michael Hanselmann
                                    " mismatch, got %s instead of %s" %
63 5b263ed7 Michael Hanselmann
                                    (data.version,
64 243cdbcc Michael Hanselmann
                                     constants.CONFIG_VERSION))
65 a8083063 Iustin Pop
66 319856a9 Michael Hanselmann
67 a8083063 Iustin Pop
class ConfigWriter:
68 098c0958 Michael Hanselmann
  """The interface to the cluster configuration.
69 a8083063 Iustin Pop

70 098c0958 Michael Hanselmann
  """
71 a8083063 Iustin Pop
  def __init__(self, cfg_file=None, offline=False):
72 14e15659 Iustin Pop
    self.write_count = 0
73 f78ede4e Guido Trotter
    self._lock = _config_lock
74 a8083063 Iustin Pop
    self._config_data = None
75 a8083063 Iustin Pop
    self._offline = offline
76 a8083063 Iustin Pop
    if cfg_file is None:
77 a8083063 Iustin Pop
      self._cfg_file = constants.CLUSTER_CONF_FILE
78 a8083063 Iustin Pop
    else:
79 a8083063 Iustin Pop
      self._cfg_file = cfg_file
80 923b1523 Iustin Pop
    self._temporary_ids = set()
81 a81c53c9 Iustin Pop
    self._temporary_drbds = {}
82 89e1fc26 Iustin Pop
    # Note: in order to prevent errors when resolving our name in
83 89e1fc26 Iustin Pop
    # _DistributeConfig, we compute it here once and reuse it; it's
84 89e1fc26 Iustin Pop
    # better to raise an error before starting to modify the config
85 89e1fc26 Iustin Pop
    # file than after it was modified
86 89e1fc26 Iustin Pop
    self._my_hostname = utils.HostInfo().name
87 3c7f6c44 Iustin Pop
    self._last_cluster_serial = -1
88 3d3a04bc Iustin Pop
    self._OpenConfig()
89 a8083063 Iustin Pop
90 a8083063 Iustin Pop
  # this method needs to be static, so that we can call it on the class
91 a8083063 Iustin Pop
  @staticmethod
92 a8083063 Iustin Pop
  def IsCluster():
93 a8083063 Iustin Pop
    """Check if the cluster is configured.
94 a8083063 Iustin Pop

95 a8083063 Iustin Pop
    """
96 a8083063 Iustin Pop
    return os.path.exists(constants.CLUSTER_CONF_FILE)
97 a8083063 Iustin Pop
98 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
99 a8083063 Iustin Pop
  def GenerateMAC(self):
100 a8083063 Iustin Pop
    """Generate a MAC for an instance.
101 a8083063 Iustin Pop

102 a8083063 Iustin Pop
    This should check the current instances for duplicates.
103 a8083063 Iustin Pop

104 a8083063 Iustin Pop
    """
105 a8083063 Iustin Pop
    prefix = self._config_data.cluster.mac_prefix
106 a8083063 Iustin Pop
    all_macs = self._AllMACs()
107 a8083063 Iustin Pop
    retries = 64
108 a8083063 Iustin Pop
    while retries > 0:
109 a8083063 Iustin Pop
      byte1 = random.randrange(0, 256)
110 a8083063 Iustin Pop
      byte2 = random.randrange(0, 256)
111 a8083063 Iustin Pop
      byte3 = random.randrange(0, 256)
112 a8083063 Iustin Pop
      mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
113 a8083063 Iustin Pop
      if mac not in all_macs:
114 a8083063 Iustin Pop
        break
115 a8083063 Iustin Pop
      retries -= 1
116 a8083063 Iustin Pop
    else:
117 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Can't generate unique MAC")
118 a8083063 Iustin Pop
    return mac
119 a8083063 Iustin Pop
120 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
121 1862d460 Alexander Schreiber
  def IsMacInUse(self, mac):
122 1862d460 Alexander Schreiber
    """Predicate: check if the specified MAC is in use in the Ganeti cluster.
123 1862d460 Alexander Schreiber

124 1862d460 Alexander Schreiber
    This only checks instances managed by this cluster, it does not
125 1862d460 Alexander Schreiber
    check for potential collisions elsewhere.
126 1862d460 Alexander Schreiber

127 1862d460 Alexander Schreiber
    """
128 1862d460 Alexander Schreiber
    all_macs = self._AllMACs()
129 1862d460 Alexander Schreiber
    return mac in all_macs
130 1862d460 Alexander Schreiber
131 f9518d38 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
132 f9518d38 Iustin Pop
  def GenerateDRBDSecret(self):
133 f9518d38 Iustin Pop
    """Generate a DRBD secret.
134 f9518d38 Iustin Pop

135 f9518d38 Iustin Pop
    This checks the current disks for duplicates.
136 f9518d38 Iustin Pop

137 f9518d38 Iustin Pop
    """
138 f9518d38 Iustin Pop
    all_secrets = self._AllDRBDSecrets()
139 f9518d38 Iustin Pop
    retries = 64
140 f9518d38 Iustin Pop
    while retries > 0:
141 f9518d38 Iustin Pop
      secret = utils.GenerateSecret()
142 f9518d38 Iustin Pop
      if secret not in all_secrets:
143 f9518d38 Iustin Pop
        break
144 f9518d38 Iustin Pop
      retries -= 1
145 f9518d38 Iustin Pop
    else:
146 f9518d38 Iustin Pop
      raise errors.ConfigurationError("Can't generate unique DRBD secret")
147 f9518d38 Iustin Pop
    return secret
148 f9518d38 Iustin Pop
149 923b1523 Iustin Pop
  def _ComputeAllLVs(self):
150 923b1523 Iustin Pop
    """Compute the list of all LVs.
151 923b1523 Iustin Pop

152 923b1523 Iustin Pop
    """
153 923b1523 Iustin Pop
    lvnames = set()
154 923b1523 Iustin Pop
    for instance in self._config_data.instances.values():
155 923b1523 Iustin Pop
      node_data = instance.MapLVsByNode()
156 923b1523 Iustin Pop
      for lv_list in node_data.values():
157 923b1523 Iustin Pop
        lvnames.update(lv_list)
158 923b1523 Iustin Pop
    return lvnames
159 923b1523 Iustin Pop
160 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
161 923b1523 Iustin Pop
  def GenerateUniqueID(self, exceptions=None):
162 923b1523 Iustin Pop
    """Generate an unique disk name.
163 923b1523 Iustin Pop

164 923b1523 Iustin Pop
    This checks the current node, instances and disk names for
165 923b1523 Iustin Pop
    duplicates.
166 923b1523 Iustin Pop

167 c41eea6e Iustin Pop
    @param exceptions: a list with some other names which should be checked
168 c41eea6e Iustin Pop
        for uniqueness (used for example when you want to get
169 c41eea6e Iustin Pop
        more than one id at one time without adding each one in
170 c41eea6e Iustin Pop
        turn to the config file)
171 923b1523 Iustin Pop

172 c41eea6e Iustin Pop
    @rtype: string
173 c41eea6e Iustin Pop
    @return: the unique id
174 923b1523 Iustin Pop

175 923b1523 Iustin Pop
    """
176 923b1523 Iustin Pop
    existing = set()
177 923b1523 Iustin Pop
    existing.update(self._temporary_ids)
178 923b1523 Iustin Pop
    existing.update(self._ComputeAllLVs())
179 923b1523 Iustin Pop
    existing.update(self._config_data.instances.keys())
180 923b1523 Iustin Pop
    existing.update(self._config_data.nodes.keys())
181 923b1523 Iustin Pop
    if exceptions is not None:
182 923b1523 Iustin Pop
      existing.update(exceptions)
183 923b1523 Iustin Pop
    retries = 64
184 923b1523 Iustin Pop
    while retries > 0:
185 24818e8f Michael Hanselmann
      unique_id = utils.NewUUID()
186 923b1523 Iustin Pop
      if unique_id not in existing and unique_id is not None:
187 923b1523 Iustin Pop
        break
188 923b1523 Iustin Pop
    else:
189 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Not able generate an unique ID"
190 3ecf6786 Iustin Pop
                                      " (last tried ID: %s" % unique_id)
191 923b1523 Iustin Pop
    self._temporary_ids.add(unique_id)
192 923b1523 Iustin Pop
    return unique_id
193 923b1523 Iustin Pop
194 a8083063 Iustin Pop
  def _AllMACs(self):
195 a8083063 Iustin Pop
    """Return all MACs present in the config.
196 a8083063 Iustin Pop

197 c41eea6e Iustin Pop
    @rtype: list
198 c41eea6e Iustin Pop
    @return: the list of all MACs
199 c41eea6e Iustin Pop

200 a8083063 Iustin Pop
    """
201 a8083063 Iustin Pop
    result = []
202 a8083063 Iustin Pop
    for instance in self._config_data.instances.values():
203 a8083063 Iustin Pop
      for nic in instance.nics:
204 a8083063 Iustin Pop
        result.append(nic.mac)
205 a8083063 Iustin Pop
206 a8083063 Iustin Pop
    return result
207 a8083063 Iustin Pop
208 f9518d38 Iustin Pop
  def _AllDRBDSecrets(self):
209 f9518d38 Iustin Pop
    """Return all DRBD secrets present in the config.
210 f9518d38 Iustin Pop

211 c41eea6e Iustin Pop
    @rtype: list
212 c41eea6e Iustin Pop
    @return: the list of all DRBD secrets
213 c41eea6e Iustin Pop

214 f9518d38 Iustin Pop
    """
215 f9518d38 Iustin Pop
    def helper(disk, result):
216 f9518d38 Iustin Pop
      """Recursively gather secrets from this disk."""
217 f9518d38 Iustin Pop
      if disk.dev_type == constants.DT_DRBD8:
218 f9518d38 Iustin Pop
        result.append(disk.logical_id[5])
219 f9518d38 Iustin Pop
      if disk.children:
220 f9518d38 Iustin Pop
        for child in disk.children:
221 f9518d38 Iustin Pop
          helper(child, result)
222 f9518d38 Iustin Pop
223 f9518d38 Iustin Pop
    result = []
224 f9518d38 Iustin Pop
    for instance in self._config_data.instances.values():
225 f9518d38 Iustin Pop
      for disk in instance.disks:
226 f9518d38 Iustin Pop
        helper(disk, result)
227 f9518d38 Iustin Pop
228 f9518d38 Iustin Pop
    return result
229 f9518d38 Iustin Pop
230 4a89c54a Iustin Pop
  def _UnlockedVerifyConfig(self):
231 a8efbb40 Iustin Pop
    """Verify function.
232 a8efbb40 Iustin Pop

233 4a89c54a Iustin Pop
    @rtype: list
234 4a89c54a Iustin Pop
    @return: a list of error messages; a non-empty list signifies
235 4a89c54a Iustin Pop
        configuration errors
236 4a89c54a Iustin Pop

237 a8083063 Iustin Pop
    """
238 a8083063 Iustin Pop
    result = []
239 a8083063 Iustin Pop
    seen_macs = []
240 48ce9fd9 Iustin Pop
    ports = {}
241 a8083063 Iustin Pop
    data = self._config_data
242 a8083063 Iustin Pop
    for instance_name in data.instances:
243 a8083063 Iustin Pop
      instance = data.instances[instance_name]
244 a8083063 Iustin Pop
      if instance.primary_node not in data.nodes:
245 8522ceeb Iustin Pop
        result.append("instance '%s' has invalid primary node '%s'" %
246 a8083063 Iustin Pop
                      (instance_name, instance.primary_node))
247 a8083063 Iustin Pop
      for snode in instance.secondary_nodes:
248 a8083063 Iustin Pop
        if snode not in data.nodes:
249 8522ceeb Iustin Pop
          result.append("instance '%s' has invalid secondary node '%s'" %
250 a8083063 Iustin Pop
                        (instance_name, snode))
251 a8083063 Iustin Pop
      for idx, nic in enumerate(instance.nics):
252 a8083063 Iustin Pop
        if nic.mac in seen_macs:
253 8522ceeb Iustin Pop
          result.append("instance '%s' has NIC %d mac %s duplicate" %
254 a8083063 Iustin Pop
                        (instance_name, idx, nic.mac))
255 a8083063 Iustin Pop
        else:
256 a8083063 Iustin Pop
          seen_macs.append(nic.mac)
257 48ce9fd9 Iustin Pop
258 48ce9fd9 Iustin Pop
      # gather the drbd ports for duplicate checks
259 48ce9fd9 Iustin Pop
      for dsk in instance.disks:
260 48ce9fd9 Iustin Pop
        if dsk.dev_type in constants.LDS_DRBD:
261 48ce9fd9 Iustin Pop
          tcp_port = dsk.logical_id[2]
262 48ce9fd9 Iustin Pop
          if tcp_port not in ports:
263 48ce9fd9 Iustin Pop
            ports[tcp_port] = []
264 48ce9fd9 Iustin Pop
          ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
265 48ce9fd9 Iustin Pop
      # gather network port reservation
266 48ce9fd9 Iustin Pop
      net_port = getattr(instance, "network_port", None)
267 48ce9fd9 Iustin Pop
      if net_port is not None:
268 48ce9fd9 Iustin Pop
        if net_port not in ports:
269 48ce9fd9 Iustin Pop
          ports[net_port] = []
270 48ce9fd9 Iustin Pop
        ports[net_port].append((instance.name, "network port"))
271 48ce9fd9 Iustin Pop
272 332d0e37 Iustin Pop
      # instance disk verify
273 332d0e37 Iustin Pop
      for idx, disk in enumerate(instance.disks):
274 332d0e37 Iustin Pop
        result.extend(["instance '%s' disk %d error: %s" %
275 332d0e37 Iustin Pop
                       (instance.name, idx, msg) for msg in disk.Verify()])
276 332d0e37 Iustin Pop
277 48ce9fd9 Iustin Pop
    # cluster-wide pool of free ports
278 a8efbb40 Iustin Pop
    for free_port in data.cluster.tcpudp_port_pool:
279 48ce9fd9 Iustin Pop
      if free_port not in ports:
280 48ce9fd9 Iustin Pop
        ports[free_port] = []
281 48ce9fd9 Iustin Pop
      ports[free_port].append(("cluster", "port marked as free"))
282 48ce9fd9 Iustin Pop
283 48ce9fd9 Iustin Pop
    # compute tcp/udp duplicate ports
284 48ce9fd9 Iustin Pop
    keys = ports.keys()
285 48ce9fd9 Iustin Pop
    keys.sort()
286 48ce9fd9 Iustin Pop
    for pnum in keys:
287 48ce9fd9 Iustin Pop
      pdata = ports[pnum]
288 48ce9fd9 Iustin Pop
      if len(pdata) > 1:
289 48ce9fd9 Iustin Pop
        txt = ", ".join(["%s/%s" % val for val in pdata])
290 48ce9fd9 Iustin Pop
        result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
291 48ce9fd9 Iustin Pop
292 48ce9fd9 Iustin Pop
    # highest used tcp port check
293 48ce9fd9 Iustin Pop
    if keys:
294 a8efbb40 Iustin Pop
      if keys[-1] > data.cluster.highest_used_port:
295 48ce9fd9 Iustin Pop
        result.append("Highest used port mismatch, saved %s, computed %s" %
296 a8efbb40 Iustin Pop
                      (data.cluster.highest_used_port, keys[-1]))
297 a8efbb40 Iustin Pop
298 3a26773f Iustin Pop
    if not data.nodes[data.cluster.master_node].master_candidate:
299 3a26773f Iustin Pop
      result.append("Master node is not a master candidate")
300 3a26773f Iustin Pop
301 4a89c54a Iustin Pop
    # master candidate checks
302 ec0292f1 Iustin Pop
    mc_now, mc_max = self._UnlockedGetMasterCandidateStats()
303 ec0292f1 Iustin Pop
    if mc_now < mc_max:
304 ec0292f1 Iustin Pop
      result.append("Not enough master candidates: actual %d, target %d" %
305 ec0292f1 Iustin Pop
                    (mc_now, mc_max))
306 48ce9fd9 Iustin Pop
307 4a89c54a Iustin Pop
    # drbd minors check
308 4a89c54a Iustin Pop
    d_map, duplicates = self._UnlockedComputeDRBDMap()
309 4a89c54a Iustin Pop
    for node, minor, instance_a, instance_b in duplicates:
310 4a89c54a Iustin Pop
      result.append("DRBD minor %d on node %s is assigned twice to instances"
311 4a89c54a Iustin Pop
                    " %s and %s" % (minor, node, instance_a, instance_b))
312 4a89c54a Iustin Pop
313 a8083063 Iustin Pop
    return result
314 a8083063 Iustin Pop
315 4a89c54a Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
316 4a89c54a Iustin Pop
  def VerifyConfig(self):
317 4a89c54a Iustin Pop
    """Verify function.
318 4a89c54a Iustin Pop

319 4a89c54a Iustin Pop
    This is just a wrapper over L{_UnlockedVerifyConfig}.
320 4a89c54a Iustin Pop

321 4a89c54a Iustin Pop
    @rtype: list
322 4a89c54a Iustin Pop
    @return: a list of error messages; a non-empty list signifies
323 4a89c54a Iustin Pop
        configuration errors
324 4a89c54a Iustin Pop

325 4a89c54a Iustin Pop
    """
326 4a89c54a Iustin Pop
    return self._UnlockedVerifyConfig()
327 4a89c54a Iustin Pop
328 f78ede4e Guido Trotter
  def _UnlockedSetDiskID(self, disk, node_name):
329 a8083063 Iustin Pop
    """Convert the unique ID to the ID needed on the target nodes.
330 a8083063 Iustin Pop

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

333 a8083063 Iustin Pop
    The routine descends down and updates its children also, because
334 a8083063 Iustin Pop
    this helps when the only the top device is passed to the remote
335 a8083063 Iustin Pop
    node.
336 a8083063 Iustin Pop

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

339 a8083063 Iustin Pop
    """
340 a8083063 Iustin Pop
    if disk.children:
341 a8083063 Iustin Pop
      for child in disk.children:
342 f78ede4e Guido Trotter
        self._UnlockedSetDiskID(child, node_name)
343 a8083063 Iustin Pop
344 a8083063 Iustin Pop
    if disk.logical_id is None and disk.physical_id is not None:
345 a8083063 Iustin Pop
      return
346 ffa1c0dc Iustin Pop
    if disk.dev_type == constants.LD_DRBD8:
347 f9518d38 Iustin Pop
      pnode, snode, port, pminor, sminor, secret = disk.logical_id
348 a8083063 Iustin Pop
      if node_name not in (pnode, snode):
349 3ecf6786 Iustin Pop
        raise errors.ConfigurationError("DRBD device not knowing node %s" %
350 3ecf6786 Iustin Pop
                                        node_name)
351 f78ede4e Guido Trotter
      pnode_info = self._UnlockedGetNodeInfo(pnode)
352 f78ede4e Guido Trotter
      snode_info = self._UnlockedGetNodeInfo(snode)
353 a8083063 Iustin Pop
      if pnode_info is None or snode_info is None:
354 a8083063 Iustin Pop
        raise errors.ConfigurationError("Can't find primary or secondary node"
355 a8083063 Iustin Pop
                                        " for %s" % str(disk))
356 ffa1c0dc Iustin Pop
      p_data = (pnode_info.secondary_ip, port)
357 ffa1c0dc Iustin Pop
      s_data = (snode_info.secondary_ip, port)
358 a8083063 Iustin Pop
      if pnode == node_name:
359 f9518d38 Iustin Pop
        disk.physical_id = p_data + s_data + (pminor, secret)
360 a8083063 Iustin Pop
      else: # it must be secondary, we tested above
361 f9518d38 Iustin Pop
        disk.physical_id = s_data + p_data + (sminor, secret)
362 a8083063 Iustin Pop
    else:
363 a8083063 Iustin Pop
      disk.physical_id = disk.logical_id
364 a8083063 Iustin Pop
    return
365 a8083063 Iustin Pop
366 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
367 f78ede4e Guido Trotter
  def SetDiskID(self, disk, node_name):
368 f78ede4e Guido Trotter
    """Convert the unique ID to the ID needed on the target nodes.
369 f78ede4e Guido Trotter

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

372 f78ede4e Guido Trotter
    The routine descends down and updates its children also, because
373 f78ede4e Guido Trotter
    this helps when the only the top device is passed to the remote
374 f78ede4e Guido Trotter
    node.
375 f78ede4e Guido Trotter

376 f78ede4e Guido Trotter
    """
377 f78ede4e Guido Trotter
    return self._UnlockedSetDiskID(disk, node_name)
378 f78ede4e Guido Trotter
379 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
380 b2fddf63 Iustin Pop
  def AddTcpUdpPort(self, port):
381 b2fddf63 Iustin Pop
    """Adds a new port to the available port pool.
382 b2fddf63 Iustin Pop

383 b2fddf63 Iustin Pop
    """
384 264bb3c5 Michael Hanselmann
    if not isinstance(port, int):
385 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Invalid type passed for port")
386 264bb3c5 Michael Hanselmann
387 b2fddf63 Iustin Pop
    self._config_data.cluster.tcpudp_port_pool.add(port)
388 264bb3c5 Michael Hanselmann
    self._WriteConfig()
389 264bb3c5 Michael Hanselmann
390 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
391 b2fddf63 Iustin Pop
  def GetPortList(self):
392 264bb3c5 Michael Hanselmann
    """Returns a copy of the current port list.
393 264bb3c5 Michael Hanselmann

394 264bb3c5 Michael Hanselmann
    """
395 b2fddf63 Iustin Pop
    return self._config_data.cluster.tcpudp_port_pool.copy()
396 264bb3c5 Michael Hanselmann
397 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
398 a8083063 Iustin Pop
  def AllocatePort(self):
399 a8083063 Iustin Pop
    """Allocate a port.
400 a8083063 Iustin Pop

401 b2fddf63 Iustin Pop
    The port will be taken from the available port pool or from the
402 b2fddf63 Iustin Pop
    default port range (and in this case we increase
403 b2fddf63 Iustin Pop
    highest_used_port).
404 a8083063 Iustin Pop

405 a8083063 Iustin Pop
    """
406 264bb3c5 Michael Hanselmann
    # If there are TCP/IP ports configured, we use them first.
407 b2fddf63 Iustin Pop
    if self._config_data.cluster.tcpudp_port_pool:
408 b2fddf63 Iustin Pop
      port = self._config_data.cluster.tcpudp_port_pool.pop()
409 264bb3c5 Michael Hanselmann
    else:
410 264bb3c5 Michael Hanselmann
      port = self._config_data.cluster.highest_used_port + 1
411 264bb3c5 Michael Hanselmann
      if port >= constants.LAST_DRBD_PORT:
412 3ecf6786 Iustin Pop
        raise errors.ConfigurationError("The highest used port is greater"
413 3ecf6786 Iustin Pop
                                        " than %s. Aborting." %
414 3ecf6786 Iustin Pop
                                        constants.LAST_DRBD_PORT)
415 264bb3c5 Michael Hanselmann
      self._config_data.cluster.highest_used_port = port
416 a8083063 Iustin Pop
417 a8083063 Iustin Pop
    self._WriteConfig()
418 a8083063 Iustin Pop
    return port
419 a8083063 Iustin Pop
420 6d2e83d5 Iustin Pop
  def _UnlockedComputeDRBDMap(self):
421 a81c53c9 Iustin Pop
    """Compute the used DRBD minor/nodes.
422 a81c53c9 Iustin Pop

423 4a89c54a Iustin Pop
    @rtype: (dict, list)
424 c41eea6e Iustin Pop
    @return: dictionary of node_name: dict of minor: instance_name;
425 c41eea6e Iustin Pop
        the returned dict will have all the nodes in it (even if with
426 4a89c54a Iustin Pop
        an empty list), and a list of duplicates; if the duplicates
427 4a89c54a Iustin Pop
        list is not empty, the configuration is corrupted and its caller
428 4a89c54a Iustin Pop
        should raise an exception
429 a81c53c9 Iustin Pop

430 a81c53c9 Iustin Pop
    """
431 a81c53c9 Iustin Pop
    def _AppendUsedPorts(instance_name, disk, used):
432 4a89c54a Iustin Pop
      duplicates = []
433 f9518d38 Iustin Pop
      if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5:
434 f9518d38 Iustin Pop
        nodeA, nodeB, dummy, minorA, minorB = disk.logical_id[:5]
435 a81c53c9 Iustin Pop
        for node, port in ((nodeA, minorA), (nodeB, minorB)):
436 4a89c54a Iustin Pop
          assert node in used, ("Node '%s' of instance '%s' not found"
437 4a89c54a Iustin Pop
                                " in node list" % (node, instance_name))
438 a81c53c9 Iustin Pop
          if port in used[node]:
439 4a89c54a Iustin Pop
            duplicates.append((node, port, instance_name, used[node][port]))
440 4a89c54a Iustin Pop
          else:
441 4a89c54a Iustin Pop
            used[node][port] = instance_name
442 a81c53c9 Iustin Pop
      if disk.children:
443 a81c53c9 Iustin Pop
        for child in disk.children:
444 4a89c54a Iustin Pop
          duplicates.extend(_AppendUsedPorts(instance_name, child, used))
445 4a89c54a Iustin Pop
      return duplicates
446 a81c53c9 Iustin Pop
447 4a89c54a Iustin Pop
    duplicates = []
448 a81c53c9 Iustin Pop
    my_dict = dict((node, {}) for node in self._config_data.nodes)
449 79b26a7a Iustin Pop
    for instance in self._config_data.instances.itervalues():
450 79b26a7a Iustin Pop
      for disk in instance.disks:
451 79b26a7a Iustin Pop
        duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict))
452 a81c53c9 Iustin Pop
    for (node, minor), instance in self._temporary_drbds.iteritems():
453 79b26a7a Iustin Pop
      if minor in my_dict[node] and my_dict[node][minor] != instance:
454 4a89c54a Iustin Pop
        duplicates.append((node, minor, instance, my_dict[node][minor]))
455 4a89c54a Iustin Pop
      else:
456 4a89c54a Iustin Pop
        my_dict[node][minor] = instance
457 4a89c54a Iustin Pop
    return my_dict, duplicates
458 a81c53c9 Iustin Pop
459 a81c53c9 Iustin Pop
  @locking.ssynchronized(_config_lock)
460 6d2e83d5 Iustin Pop
  def ComputeDRBDMap(self):
461 6d2e83d5 Iustin Pop
    """Compute the used DRBD minor/nodes.
462 6d2e83d5 Iustin Pop

463 6d2e83d5 Iustin Pop
    This is just a wrapper over L{_UnlockedComputeDRBDMap}.
464 6d2e83d5 Iustin Pop

465 6d2e83d5 Iustin Pop
    @return: dictionary of node_name: dict of minor: instance_name;
466 6d2e83d5 Iustin Pop
        the returned dict will have all the nodes in it (even if with
467 6d2e83d5 Iustin Pop
        an empty list).
468 6d2e83d5 Iustin Pop

469 6d2e83d5 Iustin Pop
    """
470 4a89c54a Iustin Pop
    d_map, duplicates = self._UnlockedComputeDRBDMap()
471 4a89c54a Iustin Pop
    if duplicates:
472 4a89c54a Iustin Pop
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
473 4a89c54a Iustin Pop
                                      str(duplicates))
474 4a89c54a Iustin Pop
    return d_map
475 6d2e83d5 Iustin Pop
476 6d2e83d5 Iustin Pop
  @locking.ssynchronized(_config_lock)
477 a81c53c9 Iustin Pop
  def AllocateDRBDMinor(self, nodes, instance):
478 a81c53c9 Iustin Pop
    """Allocate a drbd minor.
479 a81c53c9 Iustin Pop

480 a81c53c9 Iustin Pop
    The free minor will be automatically computed from the existing
481 a81c53c9 Iustin Pop
    devices. A node can be given multiple times in order to allocate
482 a81c53c9 Iustin Pop
    multiple minors. The result is the list of minors, in the same
483 a81c53c9 Iustin Pop
    order as the passed nodes.
484 a81c53c9 Iustin Pop

485 32388e6d Iustin Pop
    @type instance: string
486 32388e6d Iustin Pop
    @param instance: the instance for which we allocate minors
487 32388e6d Iustin Pop

488 a81c53c9 Iustin Pop
    """
489 32388e6d Iustin Pop
    assert isinstance(instance, basestring), \
490 4a89c54a Iustin Pop
           "Invalid argument '%s' passed to AllocateDRBDMinor" % instance
491 32388e6d Iustin Pop
492 4a89c54a Iustin Pop
    d_map, duplicates = self._UnlockedComputeDRBDMap()
493 4a89c54a Iustin Pop
    if duplicates:
494 4a89c54a Iustin Pop
      raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" %
495 4a89c54a Iustin Pop
                                      str(duplicates))
496 a81c53c9 Iustin Pop
    result = []
497 a81c53c9 Iustin Pop
    for nname in nodes:
498 a81c53c9 Iustin Pop
      ndata = d_map[nname]
499 a81c53c9 Iustin Pop
      if not ndata:
500 a81c53c9 Iustin Pop
        # no minors used, we can start at 0
501 a81c53c9 Iustin Pop
        result.append(0)
502 a81c53c9 Iustin Pop
        ndata[0] = instance
503 d48663e4 Iustin Pop
        self._temporary_drbds[(nname, 0)] = instance
504 a81c53c9 Iustin Pop
        continue
505 a81c53c9 Iustin Pop
      keys = ndata.keys()
506 a81c53c9 Iustin Pop
      keys.sort()
507 a81c53c9 Iustin Pop
      ffree = utils.FirstFree(keys)
508 a81c53c9 Iustin Pop
      if ffree is None:
509 a81c53c9 Iustin Pop
        # return the next minor
510 a81c53c9 Iustin Pop
        # TODO: implement high-limit check
511 a81c53c9 Iustin Pop
        minor = keys[-1] + 1
512 a81c53c9 Iustin Pop
      else:
513 a81c53c9 Iustin Pop
        minor = ffree
514 4a89c54a Iustin Pop
      # double-check minor against current instances
515 4a89c54a Iustin Pop
      assert minor not in d_map[nname], \
516 4a89c54a Iustin Pop
             ("Attempt to reuse allocated DRBD minor %d on node %s,"
517 4a89c54a Iustin Pop
              " already allocated to instance %s" %
518 4a89c54a Iustin Pop
              (minor, nname, d_map[nname][minor]))
519 a81c53c9 Iustin Pop
      ndata[minor] = instance
520 4a89c54a Iustin Pop
      # double-check minor against reservation
521 4a89c54a Iustin Pop
      r_key = (nname, minor)
522 4a89c54a Iustin Pop
      assert r_key not in self._temporary_drbds, \
523 4a89c54a Iustin Pop
             ("Attempt to reuse reserved DRBD minor %d on node %s,"
524 4a89c54a Iustin Pop
              " reserved for instance %s" %
525 4a89c54a Iustin Pop
              (minor, nname, self._temporary_drbds[r_key]))
526 4a89c54a Iustin Pop
      self._temporary_drbds[r_key] = instance
527 4a89c54a Iustin Pop
      result.append(minor)
528 a81c53c9 Iustin Pop
    logging.debug("Request to allocate drbd minors, input: %s, returning %s",
529 a81c53c9 Iustin Pop
                  nodes, result)
530 a81c53c9 Iustin Pop
    return result
531 a81c53c9 Iustin Pop
532 61cf6b5e Iustin Pop
  def _UnlockedReleaseDRBDMinors(self, instance):
533 a81c53c9 Iustin Pop
    """Release temporary drbd minors allocated for a given instance.
534 a81c53c9 Iustin Pop

535 a81c53c9 Iustin Pop
    @type instance: string
536 a81c53c9 Iustin Pop
    @param instance: the instance for which temporary minors should be
537 a81c53c9 Iustin Pop
                     released
538 a81c53c9 Iustin Pop

539 a81c53c9 Iustin Pop
    """
540 32388e6d Iustin Pop
    assert isinstance(instance, basestring), \
541 32388e6d Iustin Pop
           "Invalid argument passed to ReleaseDRBDMinors"
542 a81c53c9 Iustin Pop
    for key, name in self._temporary_drbds.items():
543 a81c53c9 Iustin Pop
      if name == instance:
544 a81c53c9 Iustin Pop
        del self._temporary_drbds[key]
545 a81c53c9 Iustin Pop
546 61cf6b5e Iustin Pop
  @locking.ssynchronized(_config_lock)
547 61cf6b5e Iustin Pop
  def ReleaseDRBDMinors(self, instance):
548 61cf6b5e Iustin Pop
    """Release temporary drbd minors allocated for a given instance.
549 61cf6b5e Iustin Pop

550 61cf6b5e Iustin Pop
    This should be called on the error paths, on the success paths
551 61cf6b5e Iustin Pop
    it's automatically called by the ConfigWriter add and update
552 61cf6b5e Iustin Pop
    functions.
553 61cf6b5e Iustin Pop

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

556 61cf6b5e Iustin Pop
    @type instance: string
557 61cf6b5e Iustin Pop
    @param instance: the instance for which temporary minors should be
558 61cf6b5e Iustin Pop
                     released
559 61cf6b5e Iustin Pop

560 61cf6b5e Iustin Pop
    """
561 61cf6b5e Iustin Pop
    self._UnlockedReleaseDRBDMinors(instance)
562 61cf6b5e Iustin Pop
563 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
564 4a8b186a Michael Hanselmann
  def GetConfigVersion(self):
565 4a8b186a Michael Hanselmann
    """Get the configuration version.
566 4a8b186a Michael Hanselmann

567 4a8b186a Michael Hanselmann
    @return: Config version
568 4a8b186a Michael Hanselmann

569 4a8b186a Michael Hanselmann
    """
570 4a8b186a Michael Hanselmann
    return self._config_data.version
571 4a8b186a Michael Hanselmann
572 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
573 4a8b186a Michael Hanselmann
  def GetClusterName(self):
574 4a8b186a Michael Hanselmann
    """Get cluster name.
575 4a8b186a Michael Hanselmann

576 4a8b186a Michael Hanselmann
    @return: Cluster name
577 4a8b186a Michael Hanselmann

578 4a8b186a Michael Hanselmann
    """
579 4a8b186a Michael Hanselmann
    return self._config_data.cluster.cluster_name
580 4a8b186a Michael Hanselmann
581 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
582 4a8b186a Michael Hanselmann
  def GetMasterNode(self):
583 4a8b186a Michael Hanselmann
    """Get the hostname of the master node for this cluster.
584 4a8b186a Michael Hanselmann

585 4a8b186a Michael Hanselmann
    @return: Master hostname
586 4a8b186a Michael Hanselmann

587 4a8b186a Michael Hanselmann
    """
588 4a8b186a Michael Hanselmann
    return self._config_data.cluster.master_node
589 4a8b186a Michael Hanselmann
590 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
591 4a8b186a Michael Hanselmann
  def GetMasterIP(self):
592 4a8b186a Michael Hanselmann
    """Get the IP of the master node for this cluster.
593 4a8b186a Michael Hanselmann

594 4a8b186a Michael Hanselmann
    @return: Master IP
595 4a8b186a Michael Hanselmann

596 4a8b186a Michael Hanselmann
    """
597 4a8b186a Michael Hanselmann
    return self._config_data.cluster.master_ip
598 4a8b186a Michael Hanselmann
599 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
600 4a8b186a Michael Hanselmann
  def GetMasterNetdev(self):
601 4a8b186a Michael Hanselmann
    """Get the master network device for this cluster.
602 4a8b186a Michael Hanselmann

603 4a8b186a Michael Hanselmann
    """
604 4a8b186a Michael Hanselmann
    return self._config_data.cluster.master_netdev
605 4a8b186a Michael Hanselmann
606 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
607 4a8b186a Michael Hanselmann
  def GetFileStorageDir(self):
608 4a8b186a Michael Hanselmann
    """Get the file storage dir for this cluster.
609 4a8b186a Michael Hanselmann

610 4a8b186a Michael Hanselmann
    """
611 4a8b186a Michael Hanselmann
    return self._config_data.cluster.file_storage_dir
612 4a8b186a Michael Hanselmann
613 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
614 4a8b186a Michael Hanselmann
  def GetHypervisorType(self):
615 4a8b186a Michael Hanselmann
    """Get the hypervisor type for this cluster.
616 4a8b186a Michael Hanselmann

617 4a8b186a Michael Hanselmann
    """
618 64272529 Iustin Pop
    return self._config_data.cluster.default_hypervisor
619 4a8b186a Michael Hanselmann
620 4a8b186a Michael Hanselmann
  @locking.ssynchronized(_config_lock, shared=1)
621 a8083063 Iustin Pop
  def GetHostKey(self):
622 a8083063 Iustin Pop
    """Return the rsa hostkey from the config.
623 a8083063 Iustin Pop

624 c41eea6e Iustin Pop
    @rtype: string
625 c41eea6e Iustin Pop
    @return: the rsa hostkey
626 a8083063 Iustin Pop

627 a8083063 Iustin Pop
    """
628 a8083063 Iustin Pop
    return self._config_data.cluster.rsahostkeypub
629 a8083063 Iustin Pop
630 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
631 a8083063 Iustin Pop
  def AddInstance(self, instance):
632 a8083063 Iustin Pop
    """Add an instance to the config.
633 a8083063 Iustin Pop

634 a8083063 Iustin Pop
    This should be used after creating a new instance.
635 a8083063 Iustin Pop

636 c41eea6e Iustin Pop
    @type instance: L{objects.Instance}
637 c41eea6e Iustin Pop
    @param instance: the instance object
638 c41eea6e Iustin Pop

639 a8083063 Iustin Pop
    """
640 a8083063 Iustin Pop
    if not isinstance(instance, objects.Instance):
641 a8083063 Iustin Pop
      raise errors.ProgrammerError("Invalid type passed to AddInstance")
642 a8083063 Iustin Pop
643 e00fb268 Iustin Pop
    if instance.disk_template != constants.DT_DISKLESS:
644 e00fb268 Iustin Pop
      all_lvs = instance.MapLVsByNode()
645 74a48621 Iustin Pop
      logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
646 923b1523 Iustin Pop
647 b989e85d Iustin Pop
    instance.serial_no = 1
648 a8083063 Iustin Pop
    self._config_data.instances[instance.name] = instance
649 81a49123 Iustin Pop
    self._config_data.cluster.serial_no += 1
650 61cf6b5e Iustin Pop
    self._UnlockedReleaseDRBDMinors(instance.name)
651 a8083063 Iustin Pop
    self._WriteConfig()
652 a8083063 Iustin Pop
653 6a408fb2 Iustin Pop
  def _SetInstanceStatus(self, instance_name, status):
654 6a408fb2 Iustin Pop
    """Set the instance's status to a given value.
655 a8083063 Iustin Pop

656 a8083063 Iustin Pop
    """
657 0d68c45d Iustin Pop
    assert isinstance(status, bool), \
658 0d68c45d Iustin Pop
           "Invalid status '%s' passed to SetInstanceStatus" % (status,)
659 a8083063 Iustin Pop
660 a8083063 Iustin Pop
    if instance_name not in self._config_data.instances:
661 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Unknown instance '%s'" %
662 3ecf6786 Iustin Pop
                                      instance_name)
663 a8083063 Iustin Pop
    instance = self._config_data.instances[instance_name]
664 0d68c45d Iustin Pop
    if instance.admin_up != status:
665 0d68c45d Iustin Pop
      instance.admin_up = status
666 b989e85d Iustin Pop
      instance.serial_no += 1
667 455a3445 Iustin Pop
      self._WriteConfig()
668 a8083063 Iustin Pop
669 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
670 6a408fb2 Iustin Pop
  def MarkInstanceUp(self, instance_name):
671 6a408fb2 Iustin Pop
    """Mark the instance status to up in the config.
672 6a408fb2 Iustin Pop

673 6a408fb2 Iustin Pop
    """
674 0d68c45d Iustin Pop
    self._SetInstanceStatus(instance_name, True)
675 6a408fb2 Iustin Pop
676 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
677 a8083063 Iustin Pop
  def RemoveInstance(self, instance_name):
678 a8083063 Iustin Pop
    """Remove the instance from the configuration.
679 a8083063 Iustin Pop

680 a8083063 Iustin Pop
    """
681 a8083063 Iustin Pop
    if instance_name not in self._config_data.instances:
682 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Unknown instance '%s'" % instance_name)
683 a8083063 Iustin Pop
    del self._config_data.instances[instance_name]
684 81a49123 Iustin Pop
    self._config_data.cluster.serial_no += 1
685 a8083063 Iustin Pop
    self._WriteConfig()
686 a8083063 Iustin Pop
687 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
688 fc95f88f Iustin Pop
  def RenameInstance(self, old_name, new_name):
689 fc95f88f Iustin Pop
    """Rename an instance.
690 fc95f88f Iustin Pop

691 fc95f88f Iustin Pop
    This needs to be done in ConfigWriter and not by RemoveInstance
692 fc95f88f Iustin Pop
    combined with AddInstance as only we can guarantee an atomic
693 fc95f88f Iustin Pop
    rename.
694 fc95f88f Iustin Pop

695 fc95f88f Iustin Pop
    """
696 fc95f88f Iustin Pop
    if old_name not in self._config_data.instances:
697 fc95f88f Iustin Pop
      raise errors.ConfigurationError("Unknown instance '%s'" % old_name)
698 fc95f88f Iustin Pop
    inst = self._config_data.instances[old_name]
699 fc95f88f Iustin Pop
    del self._config_data.instances[old_name]
700 fc95f88f Iustin Pop
    inst.name = new_name
701 b23c4333 Manuel Franceschini
702 b23c4333 Manuel Franceschini
    for disk in inst.disks:
703 b23c4333 Manuel Franceschini
      if disk.dev_type == constants.LD_FILE:
704 b23c4333 Manuel Franceschini
        # rename the file paths in logical and physical id
705 b23c4333 Manuel Franceschini
        file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
706 b23c4333 Manuel Franceschini
        disk.physical_id = disk.logical_id = (disk.logical_id[0],
707 b23c4333 Manuel Franceschini
                                              os.path.join(file_storage_dir,
708 b23c4333 Manuel Franceschini
                                                           inst.name,
709 b23c4333 Manuel Franceschini
                                                           disk.iv_name))
710 b23c4333 Manuel Franceschini
711 fc95f88f Iustin Pop
    self._config_data.instances[inst.name] = inst
712 fc95f88f Iustin Pop
    self._WriteConfig()
713 fc95f88f Iustin Pop
714 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
715 a8083063 Iustin Pop
  def MarkInstanceDown(self, instance_name):
716 a8083063 Iustin Pop
    """Mark the status of an instance to down in the configuration.
717 a8083063 Iustin Pop

718 a8083063 Iustin Pop
    """
719 0d68c45d Iustin Pop
    self._SetInstanceStatus(instance_name, False)
720 a8083063 Iustin Pop
721 94bbfece Iustin Pop
  def _UnlockedGetInstanceList(self):
722 94bbfece Iustin Pop
    """Get the list of instances.
723 94bbfece Iustin Pop

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

726 94bbfece Iustin Pop
    """
727 94bbfece Iustin Pop
    return self._config_data.instances.keys()
728 94bbfece Iustin Pop
729 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
730 a8083063 Iustin Pop
  def GetInstanceList(self):
731 a8083063 Iustin Pop
    """Get the list of instances.
732 a8083063 Iustin Pop

733 c41eea6e Iustin Pop
    @return: array of instances, ex. ['instance2.example.com',
734 c41eea6e Iustin Pop
        'instance1.example.com']
735 a8083063 Iustin Pop

736 a8083063 Iustin Pop
    """
737 94bbfece Iustin Pop
    return self._UnlockedGetInstanceList()
738 a8083063 Iustin Pop
739 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
740 a8083063 Iustin Pop
  def ExpandInstanceName(self, short_name):
741 a8083063 Iustin Pop
    """Attempt to expand an incomplete instance name.
742 a8083063 Iustin Pop

743 a8083063 Iustin Pop
    """
744 a8083063 Iustin Pop
    return utils.MatchNameComponent(short_name,
745 a8083063 Iustin Pop
                                    self._config_data.instances.keys())
746 a8083063 Iustin Pop
747 94bbfece Iustin Pop
  def _UnlockedGetInstanceInfo(self, instance_name):
748 94bbfece Iustin Pop
    """Returns informations about an instance.
749 94bbfece Iustin Pop

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

752 94bbfece Iustin Pop
    """
753 94bbfece Iustin Pop
    if instance_name not in self._config_data.instances:
754 94bbfece Iustin Pop
      return None
755 94bbfece Iustin Pop
756 94bbfece Iustin Pop
    return self._config_data.instances[instance_name]
757 94bbfece Iustin Pop
758 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
759 a8083063 Iustin Pop
  def GetInstanceInfo(self, instance_name):
760 a8083063 Iustin Pop
    """Returns informations about an instance.
761 a8083063 Iustin Pop

762 a8083063 Iustin Pop
    It takes the information from the configuration file. Other informations of
763 a8083063 Iustin Pop
    an instance are taken from the live systems.
764 a8083063 Iustin Pop

765 c41eea6e Iustin Pop
    @param instance_name: name of the instance, e.g.
766 c41eea6e Iustin Pop
        I{instance1.example.com}
767 a8083063 Iustin Pop

768 c41eea6e Iustin Pop
    @rtype: L{objects.Instance}
769 c41eea6e Iustin Pop
    @return: the instance object
770 a8083063 Iustin Pop

771 a8083063 Iustin Pop
    """
772 94bbfece Iustin Pop
    return self._UnlockedGetInstanceInfo(instance_name)
773 a8083063 Iustin Pop
774 0b2de758 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
775 0b2de758 Iustin Pop
  def GetAllInstancesInfo(self):
776 0b2de758 Iustin Pop
    """Get the configuration of all instances.
777 0b2de758 Iustin Pop

778 0b2de758 Iustin Pop
    @rtype: dict
779 0b2de758 Iustin Pop
    @returns: dict of (instance, instance_info), where instance_info is what
780 0b2de758 Iustin Pop
              would GetInstanceInfo return for the node
781 0b2de758 Iustin Pop

782 0b2de758 Iustin Pop
    """
783 64d3bd52 Guido Trotter
    my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance))
784 64d3bd52 Guido Trotter
                    for instance in self._UnlockedGetInstanceList()])
785 0b2de758 Iustin Pop
    return my_dict
786 0b2de758 Iustin Pop
787 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
788 a8083063 Iustin Pop
  def AddNode(self, node):
789 a8083063 Iustin Pop
    """Add a node to the configuration.
790 a8083063 Iustin Pop

791 c41eea6e Iustin Pop
    @type node: L{objects.Node}
792 c41eea6e Iustin Pop
    @param node: a Node instance
793 a8083063 Iustin Pop

794 a8083063 Iustin Pop
    """
795 d8470559 Michael Hanselmann
    logging.info("Adding node %s to configuration" % node.name)
796 d8470559 Michael Hanselmann
797 b989e85d Iustin Pop
    node.serial_no = 1
798 a8083063 Iustin Pop
    self._config_data.nodes[node.name] = node
799 b9f72b4e Iustin Pop
    self._config_data.cluster.serial_no += 1
800 a8083063 Iustin Pop
    self._WriteConfig()
801 a8083063 Iustin Pop
802 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
803 a8083063 Iustin Pop
  def RemoveNode(self, node_name):
804 a8083063 Iustin Pop
    """Remove a node from the configuration.
805 a8083063 Iustin Pop

806 a8083063 Iustin Pop
    """
807 d8470559 Michael Hanselmann
    logging.info("Removing node %s from configuration" % node_name)
808 d8470559 Michael Hanselmann
809 a8083063 Iustin Pop
    if node_name not in self._config_data.nodes:
810 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Unknown node '%s'" % node_name)
811 a8083063 Iustin Pop
812 a8083063 Iustin Pop
    del self._config_data.nodes[node_name]
813 b9f72b4e Iustin Pop
    self._config_data.cluster.serial_no += 1
814 a8083063 Iustin Pop
    self._WriteConfig()
815 a8083063 Iustin Pop
816 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
817 a8083063 Iustin Pop
  def ExpandNodeName(self, short_name):
818 a8083063 Iustin Pop
    """Attempt to expand an incomplete instance name.
819 a8083063 Iustin Pop

820 a8083063 Iustin Pop
    """
821 a8083063 Iustin Pop
    return utils.MatchNameComponent(short_name,
822 a8083063 Iustin Pop
                                    self._config_data.nodes.keys())
823 a8083063 Iustin Pop
824 f78ede4e Guido Trotter
  def _UnlockedGetNodeInfo(self, node_name):
825 a8083063 Iustin Pop
    """Get the configuration of a node, as stored in the config.
826 a8083063 Iustin Pop

827 c41eea6e Iustin Pop
    This function is for internal use, when the config lock is already
828 c41eea6e Iustin Pop
    held.
829 f78ede4e Guido Trotter

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

832 c41eea6e Iustin Pop
    @rtype: L{objects.Node}
833 c41eea6e Iustin Pop
    @return: the node object
834 a8083063 Iustin Pop

835 a8083063 Iustin Pop
    """
836 a8083063 Iustin Pop
    if node_name not in self._config_data.nodes:
837 a8083063 Iustin Pop
      return None
838 a8083063 Iustin Pop
839 a8083063 Iustin Pop
    return self._config_data.nodes[node_name]
840 a8083063 Iustin Pop
841 f78ede4e Guido Trotter
842 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
843 f78ede4e Guido Trotter
  def GetNodeInfo(self, node_name):
844 f78ede4e Guido Trotter
    """Get the configuration of a node, as stored in the config.
845 f78ede4e Guido Trotter

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

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

850 c41eea6e Iustin Pop
    @rtype: L{objects.Node}
851 c41eea6e Iustin Pop
    @return: the node object
852 f78ede4e Guido Trotter

853 f78ede4e Guido Trotter
    """
854 f78ede4e Guido Trotter
    return self._UnlockedGetNodeInfo(node_name)
855 f78ede4e Guido Trotter
856 f78ede4e Guido Trotter
  def _UnlockedGetNodeList(self):
857 a8083063 Iustin Pop
    """Return the list of nodes which are in the configuration.
858 a8083063 Iustin Pop

859 c41eea6e Iustin Pop
    This function is for internal use, when the config lock is already
860 c41eea6e Iustin Pop
    held.
861 c41eea6e Iustin Pop

862 c41eea6e Iustin Pop
    @rtype: list
863 f78ede4e Guido Trotter

864 a8083063 Iustin Pop
    """
865 a8083063 Iustin Pop
    return self._config_data.nodes.keys()
866 a8083063 Iustin Pop
867 f78ede4e Guido Trotter
868 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
869 f78ede4e Guido Trotter
  def GetNodeList(self):
870 f78ede4e Guido Trotter
    """Return the list of nodes which are in the configuration.
871 f78ede4e Guido Trotter

872 f78ede4e Guido Trotter
    """
873 f78ede4e Guido Trotter
    return self._UnlockedGetNodeList()
874 f78ede4e Guido Trotter
875 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
876 94a02bb5 Iustin Pop
  def GetOnlineNodeList(self):
877 94a02bb5 Iustin Pop
    """Return the list of nodes which are online.
878 94a02bb5 Iustin Pop

879 94a02bb5 Iustin Pop
    """
880 94a02bb5 Iustin Pop
    all_nodes = [self._UnlockedGetNodeInfo(node)
881 94a02bb5 Iustin Pop
                 for node in self._UnlockedGetNodeList()]
882 94a02bb5 Iustin Pop
    return [node.name for node in all_nodes if not node.offline]
883 94a02bb5 Iustin Pop
884 94a02bb5 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
885 d65e5776 Iustin Pop
  def GetAllNodesInfo(self):
886 d65e5776 Iustin Pop
    """Get the configuration of all nodes.
887 d65e5776 Iustin Pop

888 d65e5776 Iustin Pop
    @rtype: dict
889 ec0292f1 Iustin Pop
    @return: dict of (node, node_info), where node_info is what
890 d65e5776 Iustin Pop
              would GetNodeInfo return for the node
891 d65e5776 Iustin Pop

892 d65e5776 Iustin Pop
    """
893 d65e5776 Iustin Pop
    my_dict = dict([(node, self._UnlockedGetNodeInfo(node))
894 d65e5776 Iustin Pop
                    for node in self._UnlockedGetNodeList()])
895 d65e5776 Iustin Pop
    return my_dict
896 d65e5776 Iustin Pop
897 ec0292f1 Iustin Pop
  def _UnlockedGetMasterCandidateStats(self):
898 ec0292f1 Iustin Pop
    """Get the number of current and maximum desired and possible candidates.
899 ec0292f1 Iustin Pop

900 ec0292f1 Iustin Pop
    @rtype: tuple
901 ec0292f1 Iustin Pop
    @return: tuple of (current, desired and possible)
902 ec0292f1 Iustin Pop

903 ec0292f1 Iustin Pop
    """
904 ec0292f1 Iustin Pop
    mc_now = mc_max = 0
905 ec0292f1 Iustin Pop
    for node in self._config_data.nodes.itervalues():
906 ec0292f1 Iustin Pop
      if not node.offline:
907 ec0292f1 Iustin Pop
        mc_max += 1
908 ec0292f1 Iustin Pop
      if node.master_candidate:
909 ec0292f1 Iustin Pop
        mc_now += 1
910 ec0292f1 Iustin Pop
    mc_max = min(mc_max, self._config_data.cluster.candidate_pool_size)
911 ec0292f1 Iustin Pop
    return (mc_now, mc_max)
912 ec0292f1 Iustin Pop
913 ec0292f1 Iustin Pop
  @locking.ssynchronized(_config_lock, shared=1)
914 ec0292f1 Iustin Pop
  def GetMasterCandidateStats(self):
915 ec0292f1 Iustin Pop
    """Get the number of current and maximum possible candidates.
916 ec0292f1 Iustin Pop

917 ec0292f1 Iustin Pop
    This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
918 ec0292f1 Iustin Pop

919 ec0292f1 Iustin Pop
    @rtype: tuple
920 ec0292f1 Iustin Pop
    @return: tuple of (current, max)
921 ec0292f1 Iustin Pop

922 ec0292f1 Iustin Pop
    """
923 ec0292f1 Iustin Pop
    return self._UnlockedGetMasterCandidateStats()
924 ec0292f1 Iustin Pop
925 ec0292f1 Iustin Pop
  @locking.ssynchronized(_config_lock)
926 ec0292f1 Iustin Pop
  def MaintainCandidatePool(self):
927 ec0292f1 Iustin Pop
    """Try to grow the candidate pool to the desired size.
928 ec0292f1 Iustin Pop

929 ec0292f1 Iustin Pop
    @rtype: list
930 ee513a66 Iustin Pop
    @return: list with the adjusted nodes (L{objects.Node} instances)
931 ec0292f1 Iustin Pop

932 ec0292f1 Iustin Pop
    """
933 ec0292f1 Iustin Pop
    mc_now, mc_max = self._UnlockedGetMasterCandidateStats()
934 ec0292f1 Iustin Pop
    mod_list = []
935 ec0292f1 Iustin Pop
    if mc_now < mc_max:
936 ec0292f1 Iustin Pop
      node_list = self._config_data.nodes.keys()
937 ec0292f1 Iustin Pop
      random.shuffle(node_list)
938 ec0292f1 Iustin Pop
      for name in node_list:
939 ec0292f1 Iustin Pop
        if mc_now >= mc_max:
940 ec0292f1 Iustin Pop
          break
941 ec0292f1 Iustin Pop
        node = self._config_data.nodes[name]
942 ec0292f1 Iustin Pop
        if node.master_candidate or node.offline:
943 ec0292f1 Iustin Pop
          continue
944 ee513a66 Iustin Pop
        mod_list.append(node)
945 ec0292f1 Iustin Pop
        node.master_candidate = True
946 ec0292f1 Iustin Pop
        node.serial_no += 1
947 ec0292f1 Iustin Pop
        mc_now += 1
948 ec0292f1 Iustin Pop
      if mc_now != mc_max:
949 ec0292f1 Iustin Pop
        # this should not happen
950 ec0292f1 Iustin Pop
        logging.warning("Warning: MaintainCandidatePool didn't manage to"
951 ec0292f1 Iustin Pop
                        " fill the candidate pool (%d/%d)", mc_now, mc_max)
952 ec0292f1 Iustin Pop
      if mod_list:
953 ec0292f1 Iustin Pop
        self._config_data.cluster.serial_no += 1
954 ec0292f1 Iustin Pop
        self._WriteConfig()
955 ec0292f1 Iustin Pop
956 ec0292f1 Iustin Pop
    return mod_list
957 ec0292f1 Iustin Pop
958 a8083063 Iustin Pop
  def _BumpSerialNo(self):
959 a8083063 Iustin Pop
    """Bump up the serial number of the config.
960 a8083063 Iustin Pop

961 a8083063 Iustin Pop
    """
962 9d38c6e1 Iustin Pop
    self._config_data.serial_no += 1
963 a8083063 Iustin Pop
964 a8083063 Iustin Pop
  def _OpenConfig(self):
965 a8083063 Iustin Pop
    """Read the config data from disk.
966 a8083063 Iustin Pop

967 a8083063 Iustin Pop
    """
968 a8083063 Iustin Pop
    f = open(self._cfg_file, 'r')
969 a8083063 Iustin Pop
    try:
970 a8083063 Iustin Pop
      try:
971 8d14b30d Iustin Pop
        data = objects.ConfigData.FromDict(serializer.Load(f.read()))
972 a8083063 Iustin Pop
      except Exception, err:
973 3ecf6786 Iustin Pop
        raise errors.ConfigurationError(err)
974 a8083063 Iustin Pop
    finally:
975 a8083063 Iustin Pop
      f.close()
976 5b263ed7 Michael Hanselmann
977 5b263ed7 Michael Hanselmann
    # Make sure the configuration has the right version
978 5b263ed7 Michael Hanselmann
    _ValidateConfig(data)
979 5b263ed7 Michael Hanselmann
980 a8083063 Iustin Pop
    if (not hasattr(data, 'cluster') or
981 243cdbcc Michael Hanselmann
        not hasattr(data.cluster, 'rsahostkeypub')):
982 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Incomplete configuration"
983 243cdbcc Michael Hanselmann
                                      " (missing cluster.rsahostkeypub)")
984 a8083063 Iustin Pop
    self._config_data = data
985 3c7f6c44 Iustin Pop
    # reset the last serial as -1 so that the next write will cause
986 0779e3aa Iustin Pop
    # ssconf update
987 0779e3aa Iustin Pop
    self._last_cluster_serial = -1
988 a8083063 Iustin Pop
989 a8083063 Iustin Pop
  def _DistributeConfig(self):
990 a8083063 Iustin Pop
    """Distribute the configuration to the other nodes.
991 a8083063 Iustin Pop

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

995 a8083063 Iustin Pop
    """
996 a8083063 Iustin Pop
    if self._offline:
997 a8083063 Iustin Pop
      return True
998 a8083063 Iustin Pop
    bad = False
999 a8083063 Iustin Pop
1000 6a5b8b4b Iustin Pop
    node_list = []
1001 6a5b8b4b Iustin Pop
    addr_list = []
1002 6a5b8b4b Iustin Pop
    myhostname = self._my_hostname
1003 6b294c53 Iustin Pop
    # we can skip checking whether _UnlockedGetNodeInfo returns None
1004 6b294c53 Iustin Pop
    # since the node list comes from _UnlocketGetNodeList, and we are
1005 6b294c53 Iustin Pop
    # called with the lock held, so no modifications should take place
1006 6b294c53 Iustin Pop
    # in between
1007 6a5b8b4b Iustin Pop
    for node_name in self._UnlockedGetNodeList():
1008 6a5b8b4b Iustin Pop
      if node_name == myhostname:
1009 6a5b8b4b Iustin Pop
        continue
1010 6a5b8b4b Iustin Pop
      node_info = self._UnlockedGetNodeInfo(node_name)
1011 6a5b8b4b Iustin Pop
      if not node_info.master_candidate:
1012 6a5b8b4b Iustin Pop
        continue
1013 6a5b8b4b Iustin Pop
      node_list.append(node_info.name)
1014 6a5b8b4b Iustin Pop
      addr_list.append(node_info.primary_ip)
1015 6b294c53 Iustin Pop
1016 6a5b8b4b Iustin Pop
    result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
1017 6a5b8b4b Iustin Pop
                                            address_list=addr_list)
1018 6a5b8b4b Iustin Pop
    for node in node_list:
1019 a8083063 Iustin Pop
      if not result[node]:
1020 74a48621 Iustin Pop
        logging.error("copy of file %s to node %s failed",
1021 74a48621 Iustin Pop
                      self._cfg_file, node)
1022 a8083063 Iustin Pop
        bad = True
1023 a8083063 Iustin Pop
    return not bad
1024 a8083063 Iustin Pop
1025 a8083063 Iustin Pop
  def _WriteConfig(self, destination=None):
1026 a8083063 Iustin Pop
    """Write the configuration data to persistent storage.
1027 a8083063 Iustin Pop

1028 a8083063 Iustin Pop
    """
1029 4a89c54a Iustin Pop
    config_errors = self._UnlockedVerifyConfig()
1030 4a89c54a Iustin Pop
    if config_errors:
1031 4a89c54a Iustin Pop
      raise errors.ConfigurationError("Configuration data is not"
1032 4a89c54a Iustin Pop
                                      " consistent: %s" %
1033 4a89c54a Iustin Pop
                                      (", ".join(config_errors)))
1034 a8083063 Iustin Pop
    if destination is None:
1035 a8083063 Iustin Pop
      destination = self._cfg_file
1036 a8083063 Iustin Pop
    self._BumpSerialNo()
1037 8d14b30d Iustin Pop
    txt = serializer.Dump(self._config_data.ToDict())
1038 a8083063 Iustin Pop
    dir_name, file_name = os.path.split(destination)
1039 a8083063 Iustin Pop
    fd, name = tempfile.mkstemp('.newconfig', file_name, dir_name)
1040 a8083063 Iustin Pop
    f = os.fdopen(fd, 'w')
1041 a8083063 Iustin Pop
    try:
1042 8d14b30d Iustin Pop
      f.write(txt)
1043 a8083063 Iustin Pop
      os.fsync(f.fileno())
1044 a8083063 Iustin Pop
    finally:
1045 a8083063 Iustin Pop
      f.close()
1046 a8083063 Iustin Pop
    # we don't need to do os.close(fd) as f.close() did it
1047 a8083063 Iustin Pop
    os.rename(name, destination)
1048 14e15659 Iustin Pop
    self.write_count += 1
1049 3d3a04bc Iustin Pop
1050 f56618e0 Iustin Pop
    # and redistribute the config file to master candidates
1051 a8083063 Iustin Pop
    self._DistributeConfig()
1052 a8083063 Iustin Pop
1053 54d1a06e Michael Hanselmann
    # Write ssconf files on all nodes (including locally)
1054 0779e3aa Iustin Pop
    if self._last_cluster_serial < self._config_data.cluster.serial_no:
1055 d9a855f1 Michael Hanselmann
      if not self._offline:
1056 03d1dba2 Michael Hanselmann
        rpc.RpcRunner.call_write_ssconf_files(self._UnlockedGetNodeList(),
1057 03d1dba2 Michael Hanselmann
                                              self._UnlockedGetSsconfValues())
1058 0779e3aa Iustin Pop
      self._last_cluster_serial = self._config_data.cluster.serial_no
1059 54d1a06e Michael Hanselmann
1060 03d1dba2 Michael Hanselmann
  def _UnlockedGetSsconfValues(self):
1061 054596f0 Iustin Pop
    """Return the values needed by ssconf.
1062 054596f0 Iustin Pop

1063 054596f0 Iustin Pop
    @rtype: dict
1064 054596f0 Iustin Pop
    @return: a dictionary with keys the ssconf names and values their
1065 054596f0 Iustin Pop
        associated value
1066 054596f0 Iustin Pop

1067 054596f0 Iustin Pop
    """
1068 a3316e4a Iustin Pop
    fn = "\n".join
1069 81a49123 Iustin Pop
    instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
1070 a3316e4a Iustin Pop
    node_names = utils.NiceSort(self._UnlockedGetNodeList())
1071 a3316e4a Iustin Pop
    node_info = [self._UnlockedGetNodeInfo(name) for name in node_names]
1072 a3316e4a Iustin Pop
1073 81a49123 Iustin Pop
    instance_data = fn(instance_names)
1074 a3316e4a Iustin Pop
    off_data = fn(node.name for node in node_info if node.offline)
1075 81a49123 Iustin Pop
    on_data = fn(node.name for node in node_info if not node.offline)
1076 a3316e4a Iustin Pop
    mc_data = fn(node.name for node in node_info if node.master_candidate)
1077 a3316e4a Iustin Pop
    node_data = fn(node_names)
1078 f56618e0 Iustin Pop
1079 054596f0 Iustin Pop
    cluster = self._config_data.cluster
1080 03d1dba2 Michael Hanselmann
    return {
1081 054596f0 Iustin Pop
      constants.SS_CLUSTER_NAME: cluster.cluster_name,
1082 054596f0 Iustin Pop
      constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir,
1083 a3316e4a Iustin Pop
      constants.SS_MASTER_CANDIDATES: mc_data,
1084 054596f0 Iustin Pop
      constants.SS_MASTER_IP: cluster.master_ip,
1085 054596f0 Iustin Pop
      constants.SS_MASTER_NETDEV: cluster.master_netdev,
1086 054596f0 Iustin Pop
      constants.SS_MASTER_NODE: cluster.master_node,
1087 a3316e4a Iustin Pop
      constants.SS_NODE_LIST: node_data,
1088 a3316e4a Iustin Pop
      constants.SS_OFFLINE_NODES: off_data,
1089 81a49123 Iustin Pop
      constants.SS_ONLINE_NODES: on_data,
1090 81a49123 Iustin Pop
      constants.SS_INSTANCE_LIST: instance_data,
1091 8a113c7a Iustin Pop
      constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION,
1092 03d1dba2 Michael Hanselmann
      }
1093 03d1dba2 Michael Hanselmann
1094 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1095 f6bd6e98 Michael Hanselmann
  def InitConfig(self, version, cluster_config, master_node_config):
1096 a8083063 Iustin Pop
    """Create the initial cluster configuration.
1097 a8083063 Iustin Pop

1098 a8083063 Iustin Pop
    It will contain the current node, which will also be the master
1099 b9eeeb02 Michael Hanselmann
    node, and no instances.
1100 a8083063 Iustin Pop

1101 f6bd6e98 Michael Hanselmann
    @type version: int
1102 f6bd6e98 Michael Hanselmann
    @param version: Configuration version
1103 b9eeeb02 Michael Hanselmann
    @type cluster_config: objects.Cluster
1104 b9eeeb02 Michael Hanselmann
    @param cluster_config: Cluster configuration
1105 b9eeeb02 Michael Hanselmann
    @type master_node_config: objects.Node
1106 b9eeeb02 Michael Hanselmann
    @param master_node_config: Master node configuration
1107 b9eeeb02 Michael Hanselmann

1108 b9eeeb02 Michael Hanselmann
    """
1109 b9eeeb02 Michael Hanselmann
    nodes = {
1110 b9eeeb02 Michael Hanselmann
      master_node_config.name: master_node_config,
1111 b9eeeb02 Michael Hanselmann
      }
1112 b9eeeb02 Michael Hanselmann
1113 f6bd6e98 Michael Hanselmann
    self._config_data = objects.ConfigData(version=version,
1114 f6bd6e98 Michael Hanselmann
                                           cluster=cluster_config,
1115 b9eeeb02 Michael Hanselmann
                                           nodes=nodes,
1116 a8083063 Iustin Pop
                                           instances={},
1117 9d38c6e1 Iustin Pop
                                           serial_no=1)
1118 a8083063 Iustin Pop
    self._WriteConfig()
1119 a8083063 Iustin Pop
1120 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1121 a8083063 Iustin Pop
  def GetVGName(self):
1122 a8083063 Iustin Pop
    """Return the volume group name.
1123 a8083063 Iustin Pop

1124 a8083063 Iustin Pop
    """
1125 a8083063 Iustin Pop
    return self._config_data.cluster.volume_group_name
1126 a8083063 Iustin Pop
1127 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1128 89ff8e15 Manuel Franceschini
  def SetVGName(self, vg_name):
1129 89ff8e15 Manuel Franceschini
    """Set the volume group name.
1130 89ff8e15 Manuel Franceschini

1131 89ff8e15 Manuel Franceschini
    """
1132 2d4011cd Manuel Franceschini
    self._config_data.cluster.volume_group_name = vg_name
1133 b9f72b4e Iustin Pop
    self._config_data.cluster.serial_no += 1
1134 89ff8e15 Manuel Franceschini
    self._WriteConfig()
1135 89ff8e15 Manuel Franceschini
1136 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1137 a8083063 Iustin Pop
  def GetDefBridge(self):
1138 a8083063 Iustin Pop
    """Return the default bridge.
1139 a8083063 Iustin Pop

1140 a8083063 Iustin Pop
    """
1141 a8083063 Iustin Pop
    return self._config_data.cluster.default_bridge
1142 a8083063 Iustin Pop
1143 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1144 a8083063 Iustin Pop
  def GetMACPrefix(self):
1145 a8083063 Iustin Pop
    """Return the mac prefix.
1146 a8083063 Iustin Pop

1147 a8083063 Iustin Pop
    """
1148 a8083063 Iustin Pop
    return self._config_data.cluster.mac_prefix
1149 62779dd0 Iustin Pop
1150 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock, shared=1)
1151 62779dd0 Iustin Pop
  def GetClusterInfo(self):
1152 62779dd0 Iustin Pop
    """Returns informations about the cluster
1153 62779dd0 Iustin Pop

1154 c41eea6e Iustin Pop
    @rtype: L{objects.Cluster}
1155 c41eea6e Iustin Pop
    @return: the cluster object
1156 62779dd0 Iustin Pop

1157 62779dd0 Iustin Pop
    """
1158 62779dd0 Iustin Pop
    return self._config_data.cluster
1159 e00fb268 Iustin Pop
1160 f78ede4e Guido Trotter
  @locking.ssynchronized(_config_lock)
1161 e00fb268 Iustin Pop
  def Update(self, target):
1162 e00fb268 Iustin Pop
    """Notify function to be called after updates.
1163 e00fb268 Iustin Pop

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

1170 c41eea6e Iustin Pop
    @param target: an instance of either L{objects.Cluster},
1171 c41eea6e Iustin Pop
        L{objects.Node} or L{objects.Instance} which is existing in
1172 c41eea6e Iustin Pop
        the cluster
1173 c41eea6e Iustin Pop

1174 e00fb268 Iustin Pop
    """
1175 e00fb268 Iustin Pop
    if self._config_data is None:
1176 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Configuration file not read,"
1177 3ecf6786 Iustin Pop
                                   " cannot save.")
1178 f34901f8 Iustin Pop
    update_serial = False
1179 e00fb268 Iustin Pop
    if isinstance(target, objects.Cluster):
1180 e00fb268 Iustin Pop
      test = target == self._config_data.cluster
1181 e00fb268 Iustin Pop
    elif isinstance(target, objects.Node):
1182 e00fb268 Iustin Pop
      test = target in self._config_data.nodes.values()
1183 f34901f8 Iustin Pop
      update_serial = True
1184 e00fb268 Iustin Pop
    elif isinstance(target, objects.Instance):
1185 e00fb268 Iustin Pop
      test = target in self._config_data.instances.values()
1186 e00fb268 Iustin Pop
    else:
1187 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Invalid object type (%s) passed to"
1188 3ecf6786 Iustin Pop
                                   " ConfigWriter.Update" % type(target))
1189 e00fb268 Iustin Pop
    if not test:
1190 3ecf6786 Iustin Pop
      raise errors.ConfigurationError("Configuration updated since object"
1191 3ecf6786 Iustin Pop
                                      " has been read or unknown object")
1192 f34901f8 Iustin Pop
    target.serial_no += 1
1193 f34901f8 Iustin Pop
1194 cff4c037 Iustin Pop
    if update_serial:
1195 f34901f8 Iustin Pop
      # for node updates, we need to increase the cluster serial too
1196 f34901f8 Iustin Pop
      self._config_data.cluster.serial_no += 1
1197 b989e85d Iustin Pop
1198 61cf6b5e Iustin Pop
    if isinstance(target, objects.Instance):
1199 61cf6b5e Iustin Pop
      self._UnlockedReleaseDRBDMinors(target.name)
1200 61cf6b5e Iustin Pop
1201 e00fb268 Iustin Pop
    self._WriteConfig()