root / lib / config.py @ 3a93eebb
History | View | Annotate | Download (62.4 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
|
5 |
#
|
6 |
# This program is free software; you can redistribute it and/or modify
|
7 |
# it under the terms of the GNU General Public License as published by
|
8 |
# the Free Software Foundation; either version 2 of the License, or
|
9 |
# (at your option) any later version.
|
10 |
#
|
11 |
# This program is distributed in the hope that it will be useful, but
|
12 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 |
# General Public License for more details.
|
15 |
#
|
16 |
# You should have received a copy of the GNU General Public License
|
17 |
# along with this program; if not, write to the Free Software
|
18 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
|
22 |
"""Configuration management for Ganeti
|
23 |
|
24 |
This module provides the interface to the Ganeti cluster configuration.
|
25 |
|
26 |
The configuration data is stored on every node but is updated on the master
|
27 |
only. After each update, the master distributes the data to the other nodes.
|
28 |
|
29 |
Currently, the data storage format is JSON. YAML was slow and consuming too
|
30 |
much memory.
|
31 |
|
32 |
"""
|
33 |
|
34 |
# pylint: disable-msg=R0904
|
35 |
# R0904: Too many public methods
|
36 |
|
37 |
import os |
38 |
import random |
39 |
import logging |
40 |
import time |
41 |
|
42 |
from ganeti import errors |
43 |
from ganeti import locking |
44 |
from ganeti import utils |
45 |
from ganeti import constants |
46 |
from ganeti import rpc |
47 |
from ganeti import objects |
48 |
from ganeti import serializer |
49 |
from ganeti import uidpool |
50 |
from ganeti import netutils |
51 |
from ganeti import runtime |
52 |
|
53 |
|
54 |
_config_lock = locking.SharedLock("ConfigWriter")
|
55 |
|
56 |
# job id used for resource management at config upgrade time
|
57 |
_UPGRADE_CONFIG_JID = "jid-cfg-upgrade"
|
58 |
|
59 |
|
60 |
def _ValidateConfig(data): |
61 |
"""Verifies that a configuration objects looks valid.
|
62 |
|
63 |
This only verifies the version of the configuration.
|
64 |
|
65 |
@raise errors.ConfigurationError: if the version differs from what
|
66 |
we expect
|
67 |
|
68 |
"""
|
69 |
if data.version != constants.CONFIG_VERSION:
|
70 |
raise errors.ConfigVersionMismatch(constants.CONFIG_VERSION, data.version)
|
71 |
|
72 |
|
73 |
class TemporaryReservationManager: |
74 |
"""A temporary resource reservation manager.
|
75 |
|
76 |
This is used to reserve resources in a job, before using them, making sure
|
77 |
other jobs cannot get them in the meantime.
|
78 |
|
79 |
"""
|
80 |
def __init__(self): |
81 |
self._ec_reserved = {}
|
82 |
|
83 |
def Reserved(self, resource): |
84 |
for holder_reserved in self._ec_reserved.values(): |
85 |
if resource in holder_reserved: |
86 |
return True |
87 |
return False |
88 |
|
89 |
def Reserve(self, ec_id, resource): |
90 |
if self.Reserved(resource): |
91 |
raise errors.ReservationError("Duplicate reservation for resource '%s'" |
92 |
% str(resource))
|
93 |
if ec_id not in self._ec_reserved: |
94 |
self._ec_reserved[ec_id] = set([resource]) |
95 |
else:
|
96 |
self._ec_reserved[ec_id].add(resource)
|
97 |
|
98 |
def DropECReservations(self, ec_id): |
99 |
if ec_id in self._ec_reserved: |
100 |
del self._ec_reserved[ec_id] |
101 |
|
102 |
def GetReserved(self): |
103 |
all_reserved = set()
|
104 |
for holder_reserved in self._ec_reserved.values(): |
105 |
all_reserved.update(holder_reserved) |
106 |
return all_reserved
|
107 |
|
108 |
def Generate(self, existing, generate_one_fn, ec_id): |
109 |
"""Generate a new resource of this type
|
110 |
|
111 |
"""
|
112 |
assert callable(generate_one_fn) |
113 |
|
114 |
all_elems = self.GetReserved()
|
115 |
all_elems.update(existing) |
116 |
retries = 64
|
117 |
while retries > 0: |
118 |
new_resource = generate_one_fn() |
119 |
if new_resource is not None and new_resource not in all_elems: |
120 |
break
|
121 |
else:
|
122 |
raise errors.ConfigurationError("Not able generate new resource" |
123 |
" (last tried: %s)" % new_resource)
|
124 |
self.Reserve(ec_id, new_resource)
|
125 |
return new_resource
|
126 |
|
127 |
|
128 |
def _MatchNameComponentIgnoreCase(short_name, names): |
129 |
"""Wrapper around L{utils.text.MatchNameComponent}.
|
130 |
|
131 |
"""
|
132 |
return utils.MatchNameComponent(short_name, names, case_sensitive=False) |
133 |
|
134 |
|
135 |
class ConfigWriter: |
136 |
"""The interface to the cluster configuration.
|
137 |
|
138 |
@ivar _temporary_lvs: reservation manager for temporary LVs
|
139 |
@ivar _all_rms: a list of all temporary reservation managers
|
140 |
|
141 |
"""
|
142 |
def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts, |
143 |
accept_foreign=False):
|
144 |
self.write_count = 0 |
145 |
self._lock = _config_lock
|
146 |
self._config_data = None |
147 |
self._offline = offline
|
148 |
if cfg_file is None: |
149 |
self._cfg_file = constants.CLUSTER_CONF_FILE
|
150 |
else:
|
151 |
self._cfg_file = cfg_file
|
152 |
self._getents = _getents
|
153 |
self._temporary_ids = TemporaryReservationManager()
|
154 |
self._temporary_drbds = {}
|
155 |
self._temporary_macs = TemporaryReservationManager()
|
156 |
self._temporary_secrets = TemporaryReservationManager()
|
157 |
self._temporary_lvs = TemporaryReservationManager()
|
158 |
self._all_rms = [self._temporary_ids, self._temporary_macs, |
159 |
self._temporary_secrets, self._temporary_lvs] |
160 |
# Note: in order to prevent errors when resolving our name in
|
161 |
# _DistributeConfig, we compute it here once and reuse it; it's
|
162 |
# better to raise an error before starting to modify the config
|
163 |
# file than after it was modified
|
164 |
self._my_hostname = netutils.Hostname.GetSysName()
|
165 |
self._last_cluster_serial = -1 |
166 |
self._cfg_id = None |
167 |
self._OpenConfig(accept_foreign)
|
168 |
|
169 |
# this method needs to be static, so that we can call it on the class
|
170 |
@staticmethod
|
171 |
def IsCluster(): |
172 |
"""Check if the cluster is configured.
|
173 |
|
174 |
"""
|
175 |
return os.path.exists(constants.CLUSTER_CONF_FILE)
|
176 |
|
177 |
def _GenerateOneMAC(self): |
178 |
"""Generate one mac address
|
179 |
|
180 |
"""
|
181 |
prefix = self._config_data.cluster.mac_prefix
|
182 |
byte1 = random.randrange(0, 256) |
183 |
byte2 = random.randrange(0, 256) |
184 |
byte3 = random.randrange(0, 256) |
185 |
mac = "%s:%02x:%02x:%02x" % (prefix, byte1, byte2, byte3)
|
186 |
return mac
|
187 |
|
188 |
@locking.ssynchronized(_config_lock, shared=1) |
189 |
def GetNdParams(self, node): |
190 |
"""Get the node params populated with cluster defaults.
|
191 |
|
192 |
@type node: L{object.Node}
|
193 |
@param node: The node we want to know the params for
|
194 |
@return: A dict with the filled in node params
|
195 |
|
196 |
"""
|
197 |
nodegroup = self._UnlockedGetNodeGroup(node.group)
|
198 |
return self._config_data.cluster.FillND(node, nodegroup) |
199 |
|
200 |
@locking.ssynchronized(_config_lock, shared=1) |
201 |
def GenerateMAC(self, ec_id): |
202 |
"""Generate a MAC for an instance.
|
203 |
|
204 |
This should check the current instances for duplicates.
|
205 |
|
206 |
"""
|
207 |
existing = self._AllMACs()
|
208 |
return self._temporary_ids.Generate(existing, self._GenerateOneMAC, ec_id) |
209 |
|
210 |
@locking.ssynchronized(_config_lock, shared=1) |
211 |
def ReserveMAC(self, mac, ec_id): |
212 |
"""Reserve a MAC for an instance.
|
213 |
|
214 |
This only checks instances managed by this cluster, it does not
|
215 |
check for potential collisions elsewhere.
|
216 |
|
217 |
"""
|
218 |
all_macs = self._AllMACs()
|
219 |
if mac in all_macs: |
220 |
raise errors.ReservationError("mac already in use") |
221 |
else:
|
222 |
self._temporary_macs.Reserve(mac, ec_id)
|
223 |
|
224 |
@locking.ssynchronized(_config_lock, shared=1) |
225 |
def ReserveLV(self, lv_name, ec_id): |
226 |
"""Reserve an VG/LV pair for an instance.
|
227 |
|
228 |
@type lv_name: string
|
229 |
@param lv_name: the logical volume name to reserve
|
230 |
|
231 |
"""
|
232 |
all_lvs = self._AllLVs()
|
233 |
if lv_name in all_lvs: |
234 |
raise errors.ReservationError("LV already in use") |
235 |
else:
|
236 |
self._temporary_lvs.Reserve(lv_name, ec_id)
|
237 |
|
238 |
@locking.ssynchronized(_config_lock, shared=1) |
239 |
def GenerateDRBDSecret(self, ec_id): |
240 |
"""Generate a DRBD secret.
|
241 |
|
242 |
This checks the current disks for duplicates.
|
243 |
|
244 |
"""
|
245 |
return self._temporary_secrets.Generate(self._AllDRBDSecrets(), |
246 |
utils.GenerateSecret, |
247 |
ec_id) |
248 |
|
249 |
def _AllLVs(self): |
250 |
"""Compute the list of all LVs.
|
251 |
|
252 |
"""
|
253 |
lvnames = set()
|
254 |
for instance in self._config_data.instances.values(): |
255 |
node_data = instance.MapLVsByNode() |
256 |
for lv_list in node_data.values(): |
257 |
lvnames.update(lv_list) |
258 |
return lvnames
|
259 |
|
260 |
def _AllIDs(self, include_temporary): |
261 |
"""Compute the list of all UUIDs and names we have.
|
262 |
|
263 |
@type include_temporary: boolean
|
264 |
@param include_temporary: whether to include the _temporary_ids set
|
265 |
@rtype: set
|
266 |
@return: a set of IDs
|
267 |
|
268 |
"""
|
269 |
existing = set()
|
270 |
if include_temporary:
|
271 |
existing.update(self._temporary_ids.GetReserved())
|
272 |
existing.update(self._AllLVs())
|
273 |
existing.update(self._config_data.instances.keys())
|
274 |
existing.update(self._config_data.nodes.keys())
|
275 |
existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid]) |
276 |
return existing
|
277 |
|
278 |
def _GenerateUniqueID(self, ec_id): |
279 |
"""Generate an unique UUID.
|
280 |
|
281 |
This checks the current node, instances and disk names for
|
282 |
duplicates.
|
283 |
|
284 |
@rtype: string
|
285 |
@return: the unique id
|
286 |
|
287 |
"""
|
288 |
existing = self._AllIDs(include_temporary=False) |
289 |
return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id) |
290 |
|
291 |
@locking.ssynchronized(_config_lock, shared=1) |
292 |
def GenerateUniqueID(self, ec_id): |
293 |
"""Generate an unique ID.
|
294 |
|
295 |
This is just a wrapper over the unlocked version.
|
296 |
|
297 |
@type ec_id: string
|
298 |
@param ec_id: unique id for the job to reserve the id to
|
299 |
|
300 |
"""
|
301 |
return self._GenerateUniqueID(ec_id) |
302 |
|
303 |
def _AllMACs(self): |
304 |
"""Return all MACs present in the config.
|
305 |
|
306 |
@rtype: list
|
307 |
@return: the list of all MACs
|
308 |
|
309 |
"""
|
310 |
result = [] |
311 |
for instance in self._config_data.instances.values(): |
312 |
for nic in instance.nics: |
313 |
result.append(nic.mac) |
314 |
|
315 |
return result
|
316 |
|
317 |
def _AllDRBDSecrets(self): |
318 |
"""Return all DRBD secrets present in the config.
|
319 |
|
320 |
@rtype: list
|
321 |
@return: the list of all DRBD secrets
|
322 |
|
323 |
"""
|
324 |
def helper(disk, result): |
325 |
"""Recursively gather secrets from this disk."""
|
326 |
if disk.dev_type == constants.DT_DRBD8:
|
327 |
result.append(disk.logical_id[5])
|
328 |
if disk.children:
|
329 |
for child in disk.children: |
330 |
helper(child, result) |
331 |
|
332 |
result = [] |
333 |
for instance in self._config_data.instances.values(): |
334 |
for disk in instance.disks: |
335 |
helper(disk, result) |
336 |
|
337 |
return result
|
338 |
|
339 |
def _CheckDiskIDs(self, disk, l_ids, p_ids): |
340 |
"""Compute duplicate disk IDs
|
341 |
|
342 |
@type disk: L{objects.Disk}
|
343 |
@param disk: the disk at which to start searching
|
344 |
@type l_ids: list
|
345 |
@param l_ids: list of current logical ids
|
346 |
@type p_ids: list
|
347 |
@param p_ids: list of current physical ids
|
348 |
@rtype: list
|
349 |
@return: a list of error messages
|
350 |
|
351 |
"""
|
352 |
result = [] |
353 |
if disk.logical_id is not None: |
354 |
if disk.logical_id in l_ids: |
355 |
result.append("duplicate logical id %s" % str(disk.logical_id)) |
356 |
else:
|
357 |
l_ids.append(disk.logical_id) |
358 |
if disk.physical_id is not None: |
359 |
if disk.physical_id in p_ids: |
360 |
result.append("duplicate physical id %s" % str(disk.physical_id)) |
361 |
else:
|
362 |
p_ids.append(disk.physical_id) |
363 |
|
364 |
if disk.children:
|
365 |
for child in disk.children: |
366 |
result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
|
367 |
return result
|
368 |
|
369 |
def _UnlockedVerifyConfig(self): |
370 |
"""Verify function.
|
371 |
|
372 |
@rtype: list
|
373 |
@return: a list of error messages; a non-empty list signifies
|
374 |
configuration errors
|
375 |
|
376 |
"""
|
377 |
# pylint: disable-msg=R0914
|
378 |
result = [] |
379 |
seen_macs = [] |
380 |
ports = {} |
381 |
data = self._config_data
|
382 |
cluster = data.cluster |
383 |
seen_lids = [] |
384 |
seen_pids = [] |
385 |
|
386 |
# global cluster checks
|
387 |
if not cluster.enabled_hypervisors: |
388 |
result.append("enabled hypervisors list doesn't have any entries")
|
389 |
invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
|
390 |
if invalid_hvs:
|
391 |
result.append("enabled hypervisors contains invalid entries: %s" %
|
392 |
invalid_hvs) |
393 |
missing_hvp = (set(cluster.enabled_hypervisors) -
|
394 |
set(cluster.hvparams.keys()))
|
395 |
if missing_hvp:
|
396 |
result.append("hypervisor parameters missing for the enabled"
|
397 |
" hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
|
398 |
|
399 |
if cluster.master_node not in data.nodes: |
400 |
result.append("cluster has invalid primary node '%s'" %
|
401 |
cluster.master_node) |
402 |
|
403 |
def _helper(owner, attr, value, template): |
404 |
try:
|
405 |
utils.ForceDictType(value, template) |
406 |
except errors.GenericError, err:
|
407 |
result.append("%s has invalid %s: %s" % (owner, attr, err))
|
408 |
|
409 |
def _helper_nic(owner, params): |
410 |
try:
|
411 |
objects.NIC.CheckParameterSyntax(params) |
412 |
except errors.ConfigurationError, err:
|
413 |
result.append("%s has invalid nicparams: %s" % (owner, err))
|
414 |
|
415 |
# check cluster parameters
|
416 |
_helper("cluster", "beparams", cluster.SimpleFillBE({}), |
417 |
constants.BES_PARAMETER_TYPES) |
418 |
_helper("cluster", "nicparams", cluster.SimpleFillNIC({}), |
419 |
constants.NICS_PARAMETER_TYPES) |
420 |
_helper_nic("cluster", cluster.SimpleFillNIC({}))
|
421 |
_helper("cluster", "ndparams", cluster.SimpleFillND({}), |
422 |
constants.NDS_PARAMETER_TYPES) |
423 |
|
424 |
# per-instance checks
|
425 |
for instance_name in data.instances: |
426 |
instance = data.instances[instance_name] |
427 |
if instance.name != instance_name:
|
428 |
result.append("instance '%s' is indexed by wrong name '%s'" %
|
429 |
(instance.name, instance_name)) |
430 |
if instance.primary_node not in data.nodes: |
431 |
result.append("instance '%s' has invalid primary node '%s'" %
|
432 |
(instance_name, instance.primary_node)) |
433 |
for snode in instance.secondary_nodes: |
434 |
if snode not in data.nodes: |
435 |
result.append("instance '%s' has invalid secondary node '%s'" %
|
436 |
(instance_name, snode)) |
437 |
for idx, nic in enumerate(instance.nics): |
438 |
if nic.mac in seen_macs: |
439 |
result.append("instance '%s' has NIC %d mac %s duplicate" %
|
440 |
(instance_name, idx, nic.mac)) |
441 |
else:
|
442 |
seen_macs.append(nic.mac) |
443 |
if nic.nicparams:
|
444 |
filled = cluster.SimpleFillNIC(nic.nicparams) |
445 |
owner = "instance %s nic %d" % (instance.name, idx)
|
446 |
_helper(owner, "nicparams",
|
447 |
filled, constants.NICS_PARAMETER_TYPES) |
448 |
_helper_nic(owner, filled) |
449 |
|
450 |
# parameter checks
|
451 |
if instance.beparams:
|
452 |
_helper("instance %s" % instance.name, "beparams", |
453 |
cluster.FillBE(instance), constants.BES_PARAMETER_TYPES) |
454 |
|
455 |
# gather the drbd ports for duplicate checks
|
456 |
for dsk in instance.disks: |
457 |
if dsk.dev_type in constants.LDS_DRBD: |
458 |
tcp_port = dsk.logical_id[2]
|
459 |
if tcp_port not in ports: |
460 |
ports[tcp_port] = [] |
461 |
ports[tcp_port].append((instance.name, "drbd disk %s" % dsk.iv_name))
|
462 |
# gather network port reservation
|
463 |
net_port = getattr(instance, "network_port", None) |
464 |
if net_port is not None: |
465 |
if net_port not in ports: |
466 |
ports[net_port] = [] |
467 |
ports[net_port].append((instance.name, "network port"))
|
468 |
|
469 |
# instance disk verify
|
470 |
for idx, disk in enumerate(instance.disks): |
471 |
result.extend(["instance '%s' disk %d error: %s" %
|
472 |
(instance.name, idx, msg) for msg in disk.Verify()]) |
473 |
result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
|
474 |
|
475 |
# cluster-wide pool of free ports
|
476 |
for free_port in cluster.tcpudp_port_pool: |
477 |
if free_port not in ports: |
478 |
ports[free_port] = [] |
479 |
ports[free_port].append(("cluster", "port marked as free")) |
480 |
|
481 |
# compute tcp/udp duplicate ports
|
482 |
keys = ports.keys() |
483 |
keys.sort() |
484 |
for pnum in keys: |
485 |
pdata = ports[pnum] |
486 |
if len(pdata) > 1: |
487 |
txt = utils.CommaJoin(["%s/%s" % val for val in pdata]) |
488 |
result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
|
489 |
|
490 |
# highest used tcp port check
|
491 |
if keys:
|
492 |
if keys[-1] > cluster.highest_used_port: |
493 |
result.append("Highest used port mismatch, saved %s, computed %s" %
|
494 |
(cluster.highest_used_port, keys[-1]))
|
495 |
|
496 |
if not data.nodes[cluster.master_node].master_candidate: |
497 |
result.append("Master node is not a master candidate")
|
498 |
|
499 |
# master candidate checks
|
500 |
mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
|
501 |
if mc_now < mc_max:
|
502 |
result.append("Not enough master candidates: actual %d, target %d" %
|
503 |
(mc_now, mc_max)) |
504 |
|
505 |
# node checks
|
506 |
for node_name, node in data.nodes.items(): |
507 |
if node.name != node_name:
|
508 |
result.append("Node '%s' is indexed by wrong name '%s'" %
|
509 |
(node.name, node_name)) |
510 |
if [node.master_candidate, node.drained, node.offline].count(True) > 1: |
511 |
result.append("Node %s state is invalid: master_candidate=%s,"
|
512 |
" drain=%s, offline=%s" %
|
513 |
(node.name, node.master_candidate, node.drained, |
514 |
node.offline)) |
515 |
if node.group not in data.nodegroups: |
516 |
result.append("Node '%s' has invalid group '%s'" %
|
517 |
(node.name, node.group)) |
518 |
else:
|
519 |
_helper("node %s" % node.name, "ndparams", |
520 |
cluster.FillND(node, data.nodegroups[node.group]), |
521 |
constants.NDS_PARAMETER_TYPES) |
522 |
|
523 |
# nodegroups checks
|
524 |
nodegroups_names = set()
|
525 |
for nodegroup_uuid in data.nodegroups: |
526 |
nodegroup = data.nodegroups[nodegroup_uuid] |
527 |
if nodegroup.uuid != nodegroup_uuid:
|
528 |
result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
|
529 |
% (nodegroup.name, nodegroup.uuid, nodegroup_uuid)) |
530 |
if utils.UUID_RE.match(nodegroup.name.lower()):
|
531 |
result.append("node group '%s' (uuid: '%s') has uuid-like name" %
|
532 |
(nodegroup.name, nodegroup.uuid)) |
533 |
if nodegroup.name in nodegroups_names: |
534 |
result.append("duplicate node group name '%s'" % nodegroup.name)
|
535 |
else:
|
536 |
nodegroups_names.add(nodegroup.name) |
537 |
if nodegroup.ndparams:
|
538 |
_helper("group %s" % nodegroup.name, "ndparams", |
539 |
cluster.SimpleFillND(nodegroup.ndparams), |
540 |
constants.NDS_PARAMETER_TYPES) |
541 |
|
542 |
|
543 |
# drbd minors check
|
544 |
_, duplicates = self._UnlockedComputeDRBDMap()
|
545 |
for node, minor, instance_a, instance_b in duplicates: |
546 |
result.append("DRBD minor %d on node %s is assigned twice to instances"
|
547 |
" %s and %s" % (minor, node, instance_a, instance_b))
|
548 |
|
549 |
# IP checks
|
550 |
default_nicparams = cluster.nicparams[constants.PP_DEFAULT] |
551 |
ips = {} |
552 |
|
553 |
def _AddIpAddress(ip, name): |
554 |
ips.setdefault(ip, []).append(name) |
555 |
|
556 |
_AddIpAddress(cluster.master_ip, "cluster_ip")
|
557 |
|
558 |
for node in data.nodes.values(): |
559 |
_AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
|
560 |
if node.secondary_ip != node.primary_ip:
|
561 |
_AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
|
562 |
|
563 |
for instance in data.instances.values(): |
564 |
for idx, nic in enumerate(instance.nics): |
565 |
if nic.ip is None: |
566 |
continue
|
567 |
|
568 |
nicparams = objects.FillDict(default_nicparams, nic.nicparams) |
569 |
nic_mode = nicparams[constants.NIC_MODE] |
570 |
nic_link = nicparams[constants.NIC_LINK] |
571 |
|
572 |
if nic_mode == constants.NIC_MODE_BRIDGED:
|
573 |
link = "bridge:%s" % nic_link
|
574 |
elif nic_mode == constants.NIC_MODE_ROUTED:
|
575 |
link = "route:%s" % nic_link
|
576 |
else:
|
577 |
raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode) |
578 |
|
579 |
_AddIpAddress("%s/%s" % (link, nic.ip),
|
580 |
"instance:%s/nic:%d" % (instance.name, idx))
|
581 |
|
582 |
for ip, owners in ips.items(): |
583 |
if len(owners) > 1: |
584 |
result.append("IP address %s is used by multiple owners: %s" %
|
585 |
(ip, utils.CommaJoin(owners))) |
586 |
|
587 |
return result
|
588 |
|
589 |
@locking.ssynchronized(_config_lock, shared=1) |
590 |
def VerifyConfig(self): |
591 |
"""Verify function.
|
592 |
|
593 |
This is just a wrapper over L{_UnlockedVerifyConfig}.
|
594 |
|
595 |
@rtype: list
|
596 |
@return: a list of error messages; a non-empty list signifies
|
597 |
configuration errors
|
598 |
|
599 |
"""
|
600 |
return self._UnlockedVerifyConfig() |
601 |
|
602 |
def _UnlockedSetDiskID(self, disk, node_name): |
603 |
"""Convert the unique ID to the ID needed on the target nodes.
|
604 |
|
605 |
This is used only for drbd, which needs ip/port configuration.
|
606 |
|
607 |
The routine descends down and updates its children also, because
|
608 |
this helps when the only the top device is passed to the remote
|
609 |
node.
|
610 |
|
611 |
This function is for internal use, when the config lock is already held.
|
612 |
|
613 |
"""
|
614 |
if disk.children:
|
615 |
for child in disk.children: |
616 |
self._UnlockedSetDiskID(child, node_name)
|
617 |
|
618 |
if disk.logical_id is None and disk.physical_id is not None: |
619 |
return
|
620 |
if disk.dev_type == constants.LD_DRBD8:
|
621 |
pnode, snode, port, pminor, sminor, secret = disk.logical_id |
622 |
if node_name not in (pnode, snode): |
623 |
raise errors.ConfigurationError("DRBD device not knowing node %s" % |
624 |
node_name) |
625 |
pnode_info = self._UnlockedGetNodeInfo(pnode)
|
626 |
snode_info = self._UnlockedGetNodeInfo(snode)
|
627 |
if pnode_info is None or snode_info is None: |
628 |
raise errors.ConfigurationError("Can't find primary or secondary node" |
629 |
" for %s" % str(disk)) |
630 |
p_data = (pnode_info.secondary_ip, port) |
631 |
s_data = (snode_info.secondary_ip, port) |
632 |
if pnode == node_name:
|
633 |
disk.physical_id = p_data + s_data + (pminor, secret) |
634 |
else: # it must be secondary, we tested above |
635 |
disk.physical_id = s_data + p_data + (sminor, secret) |
636 |
else:
|
637 |
disk.physical_id = disk.logical_id |
638 |
return
|
639 |
|
640 |
@locking.ssynchronized(_config_lock)
|
641 |
def SetDiskID(self, disk, node_name): |
642 |
"""Convert the unique ID to the ID needed on the target nodes.
|
643 |
|
644 |
This is used only for drbd, which needs ip/port configuration.
|
645 |
|
646 |
The routine descends down and updates its children also, because
|
647 |
this helps when the only the top device is passed to the remote
|
648 |
node.
|
649 |
|
650 |
"""
|
651 |
return self._UnlockedSetDiskID(disk, node_name) |
652 |
|
653 |
@locking.ssynchronized(_config_lock)
|
654 |
def AddTcpUdpPort(self, port): |
655 |
"""Adds a new port to the available port pool.
|
656 |
|
657 |
"""
|
658 |
if not isinstance(port, int): |
659 |
raise errors.ProgrammerError("Invalid type passed for port") |
660 |
|
661 |
self._config_data.cluster.tcpudp_port_pool.add(port)
|
662 |
self._WriteConfig()
|
663 |
|
664 |
@locking.ssynchronized(_config_lock, shared=1) |
665 |
def GetPortList(self): |
666 |
"""Returns a copy of the current port list.
|
667 |
|
668 |
"""
|
669 |
return self._config_data.cluster.tcpudp_port_pool.copy() |
670 |
|
671 |
@locking.ssynchronized(_config_lock)
|
672 |
def AllocatePort(self): |
673 |
"""Allocate a port.
|
674 |
|
675 |
The port will be taken from the available port pool or from the
|
676 |
default port range (and in this case we increase
|
677 |
highest_used_port).
|
678 |
|
679 |
"""
|
680 |
# If there are TCP/IP ports configured, we use them first.
|
681 |
if self._config_data.cluster.tcpudp_port_pool: |
682 |
port = self._config_data.cluster.tcpudp_port_pool.pop()
|
683 |
else:
|
684 |
port = self._config_data.cluster.highest_used_port + 1 |
685 |
if port >= constants.LAST_DRBD_PORT:
|
686 |
raise errors.ConfigurationError("The highest used port is greater" |
687 |
" than %s. Aborting." %
|
688 |
constants.LAST_DRBD_PORT) |
689 |
self._config_data.cluster.highest_used_port = port
|
690 |
|
691 |
self._WriteConfig()
|
692 |
return port
|
693 |
|
694 |
def _UnlockedComputeDRBDMap(self): |
695 |
"""Compute the used DRBD minor/nodes.
|
696 |
|
697 |
@rtype: (dict, list)
|
698 |
@return: dictionary of node_name: dict of minor: instance_name;
|
699 |
the returned dict will have all the nodes in it (even if with
|
700 |
an empty list), and a list of duplicates; if the duplicates
|
701 |
list is not empty, the configuration is corrupted and its caller
|
702 |
should raise an exception
|
703 |
|
704 |
"""
|
705 |
def _AppendUsedPorts(instance_name, disk, used): |
706 |
duplicates = [] |
707 |
if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5: |
708 |
node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
|
709 |
for node, port in ((node_a, minor_a), (node_b, minor_b)): |
710 |
assert node in used, ("Node '%s' of instance '%s' not found" |
711 |
" in node list" % (node, instance_name))
|
712 |
if port in used[node]: |
713 |
duplicates.append((node, port, instance_name, used[node][port])) |
714 |
else:
|
715 |
used[node][port] = instance_name |
716 |
if disk.children:
|
717 |
for child in disk.children: |
718 |
duplicates.extend(_AppendUsedPorts(instance_name, child, used)) |
719 |
return duplicates
|
720 |
|
721 |
duplicates = [] |
722 |
my_dict = dict((node, {}) for node in self._config_data.nodes) |
723 |
for instance in self._config_data.instances.itervalues(): |
724 |
for disk in instance.disks: |
725 |
duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict)) |
726 |
for (node, minor), instance in self._temporary_drbds.iteritems(): |
727 |
if minor in my_dict[node] and my_dict[node][minor] != instance: |
728 |
duplicates.append((node, minor, instance, my_dict[node][minor])) |
729 |
else:
|
730 |
my_dict[node][minor] = instance |
731 |
return my_dict, duplicates
|
732 |
|
733 |
@locking.ssynchronized(_config_lock)
|
734 |
def ComputeDRBDMap(self): |
735 |
"""Compute the used DRBD minor/nodes.
|
736 |
|
737 |
This is just a wrapper over L{_UnlockedComputeDRBDMap}.
|
738 |
|
739 |
@return: dictionary of node_name: dict of minor: instance_name;
|
740 |
the returned dict will have all the nodes in it (even if with
|
741 |
an empty list).
|
742 |
|
743 |
"""
|
744 |
d_map, duplicates = self._UnlockedComputeDRBDMap()
|
745 |
if duplicates:
|
746 |
raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" % |
747 |
str(duplicates))
|
748 |
return d_map
|
749 |
|
750 |
@locking.ssynchronized(_config_lock)
|
751 |
def AllocateDRBDMinor(self, nodes, instance): |
752 |
"""Allocate a drbd minor.
|
753 |
|
754 |
The free minor will be automatically computed from the existing
|
755 |
devices. A node can be given multiple times in order to allocate
|
756 |
multiple minors. The result is the list of minors, in the same
|
757 |
order as the passed nodes.
|
758 |
|
759 |
@type instance: string
|
760 |
@param instance: the instance for which we allocate minors
|
761 |
|
762 |
"""
|
763 |
assert isinstance(instance, basestring), \ |
764 |
"Invalid argument '%s' passed to AllocateDRBDMinor" % instance
|
765 |
|
766 |
d_map, duplicates = self._UnlockedComputeDRBDMap()
|
767 |
if duplicates:
|
768 |
raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" % |
769 |
str(duplicates))
|
770 |
result = [] |
771 |
for nname in nodes: |
772 |
ndata = d_map[nname] |
773 |
if not ndata: |
774 |
# no minors used, we can start at 0
|
775 |
result.append(0)
|
776 |
ndata[0] = instance
|
777 |
self._temporary_drbds[(nname, 0)] = instance |
778 |
continue
|
779 |
keys = ndata.keys() |
780 |
keys.sort() |
781 |
ffree = utils.FirstFree(keys) |
782 |
if ffree is None: |
783 |
# return the next minor
|
784 |
# TODO: implement high-limit check
|
785 |
minor = keys[-1] + 1 |
786 |
else:
|
787 |
minor = ffree |
788 |
# double-check minor against current instances
|
789 |
assert minor not in d_map[nname], \ |
790 |
("Attempt to reuse allocated DRBD minor %d on node %s,"
|
791 |
" already allocated to instance %s" %
|
792 |
(minor, nname, d_map[nname][minor])) |
793 |
ndata[minor] = instance |
794 |
# double-check minor against reservation
|
795 |
r_key = (nname, minor) |
796 |
assert r_key not in self._temporary_drbds, \ |
797 |
("Attempt to reuse reserved DRBD minor %d on node %s,"
|
798 |
" reserved for instance %s" %
|
799 |
(minor, nname, self._temporary_drbds[r_key]))
|
800 |
self._temporary_drbds[r_key] = instance
|
801 |
result.append(minor) |
802 |
logging.debug("Request to allocate drbd minors, input: %s, returning %s",
|
803 |
nodes, result) |
804 |
return result
|
805 |
|
806 |
def _UnlockedReleaseDRBDMinors(self, instance): |
807 |
"""Release temporary drbd minors allocated for a given instance.
|
808 |
|
809 |
@type instance: string
|
810 |
@param instance: the instance for which temporary minors should be
|
811 |
released
|
812 |
|
813 |
"""
|
814 |
assert isinstance(instance, basestring), \ |
815 |
"Invalid argument passed to ReleaseDRBDMinors"
|
816 |
for key, name in self._temporary_drbds.items(): |
817 |
if name == instance:
|
818 |
del self._temporary_drbds[key] |
819 |
|
820 |
@locking.ssynchronized(_config_lock)
|
821 |
def ReleaseDRBDMinors(self, instance): |
822 |
"""Release temporary drbd minors allocated for a given instance.
|
823 |
|
824 |
This should be called on the error paths, on the success paths
|
825 |
it's automatically called by the ConfigWriter add and update
|
826 |
functions.
|
827 |
|
828 |
This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
|
829 |
|
830 |
@type instance: string
|
831 |
@param instance: the instance for which temporary minors should be
|
832 |
released
|
833 |
|
834 |
"""
|
835 |
self._UnlockedReleaseDRBDMinors(instance)
|
836 |
|
837 |
@locking.ssynchronized(_config_lock, shared=1) |
838 |
def GetConfigVersion(self): |
839 |
"""Get the configuration version.
|
840 |
|
841 |
@return: Config version
|
842 |
|
843 |
"""
|
844 |
return self._config_data.version |
845 |
|
846 |
@locking.ssynchronized(_config_lock, shared=1) |
847 |
def GetClusterName(self): |
848 |
"""Get cluster name.
|
849 |
|
850 |
@return: Cluster name
|
851 |
|
852 |
"""
|
853 |
return self._config_data.cluster.cluster_name |
854 |
|
855 |
@locking.ssynchronized(_config_lock, shared=1) |
856 |
def GetMasterNode(self): |
857 |
"""Get the hostname of the master node for this cluster.
|
858 |
|
859 |
@return: Master hostname
|
860 |
|
861 |
"""
|
862 |
return self._config_data.cluster.master_node |
863 |
|
864 |
@locking.ssynchronized(_config_lock, shared=1) |
865 |
def GetMasterIP(self): |
866 |
"""Get the IP of the master node for this cluster.
|
867 |
|
868 |
@return: Master IP
|
869 |
|
870 |
"""
|
871 |
return self._config_data.cluster.master_ip |
872 |
|
873 |
@locking.ssynchronized(_config_lock, shared=1) |
874 |
def GetMasterNetdev(self): |
875 |
"""Get the master network device for this cluster.
|
876 |
|
877 |
"""
|
878 |
return self._config_data.cluster.master_netdev |
879 |
|
880 |
@locking.ssynchronized(_config_lock, shared=1) |
881 |
def GetFileStorageDir(self): |
882 |
"""Get the file storage dir for this cluster.
|
883 |
|
884 |
"""
|
885 |
return self._config_data.cluster.file_storage_dir |
886 |
|
887 |
@locking.ssynchronized(_config_lock, shared=1) |
888 |
def GetSharedFileStorageDir(self): |
889 |
"""Get the shared file storage dir for this cluster.
|
890 |
|
891 |
"""
|
892 |
return self._config_data.cluster.shared_file_storage_dir |
893 |
|
894 |
@locking.ssynchronized(_config_lock, shared=1) |
895 |
def GetHypervisorType(self): |
896 |
"""Get the hypervisor type for this cluster.
|
897 |
|
898 |
"""
|
899 |
return self._config_data.cluster.enabled_hypervisors[0] |
900 |
|
901 |
@locking.ssynchronized(_config_lock, shared=1) |
902 |
def GetHostKey(self): |
903 |
"""Return the rsa hostkey from the config.
|
904 |
|
905 |
@rtype: string
|
906 |
@return: the rsa hostkey
|
907 |
|
908 |
"""
|
909 |
return self._config_data.cluster.rsahostkeypub |
910 |
|
911 |
@locking.ssynchronized(_config_lock, shared=1) |
912 |
def GetDefaultIAllocator(self): |
913 |
"""Get the default instance allocator for this cluster.
|
914 |
|
915 |
"""
|
916 |
return self._config_data.cluster.default_iallocator |
917 |
|
918 |
@locking.ssynchronized(_config_lock, shared=1) |
919 |
def GetPrimaryIPFamily(self): |
920 |
"""Get cluster primary ip family.
|
921 |
|
922 |
@return: primary ip family
|
923 |
|
924 |
"""
|
925 |
return self._config_data.cluster.primary_ip_family |
926 |
|
927 |
@locking.ssynchronized(_config_lock)
|
928 |
def AddNodeGroup(self, group, ec_id, check_uuid=True): |
929 |
"""Add a node group to the configuration.
|
930 |
|
931 |
This method calls group.UpgradeConfig() to fill any missing attributes
|
932 |
according to their default values.
|
933 |
|
934 |
@type group: L{objects.NodeGroup}
|
935 |
@param group: the NodeGroup object to add
|
936 |
@type ec_id: string
|
937 |
@param ec_id: unique id for the job to use when creating a missing UUID
|
938 |
@type check_uuid: bool
|
939 |
@param check_uuid: add an UUID to the group if it doesn't have one or, if
|
940 |
it does, ensure that it does not exist in the
|
941 |
configuration already
|
942 |
|
943 |
"""
|
944 |
self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
|
945 |
self._WriteConfig()
|
946 |
|
947 |
def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid): |
948 |
"""Add a node group to the configuration.
|
949 |
|
950 |
"""
|
951 |
logging.info("Adding node group %s to configuration", group.name)
|
952 |
|
953 |
# Some code might need to add a node group with a pre-populated UUID
|
954 |
# generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
|
955 |
# the "does this UUID" exist already check.
|
956 |
if check_uuid:
|
957 |
self._EnsureUUID(group, ec_id)
|
958 |
|
959 |
try:
|
960 |
existing_uuid = self._UnlockedLookupNodeGroup(group.name)
|
961 |
except errors.OpPrereqError:
|
962 |
pass
|
963 |
else:
|
964 |
raise errors.OpPrereqError("Desired group name '%s' already exists as a" |
965 |
" node group (UUID: %s)" %
|
966 |
(group.name, existing_uuid), |
967 |
errors.ECODE_EXISTS) |
968 |
|
969 |
group.serial_no = 1
|
970 |
group.ctime = group.mtime = time.time() |
971 |
group.UpgradeConfig() |
972 |
|
973 |
self._config_data.nodegroups[group.uuid] = group
|
974 |
self._config_data.cluster.serial_no += 1 |
975 |
|
976 |
@locking.ssynchronized(_config_lock)
|
977 |
def RemoveNodeGroup(self, group_uuid): |
978 |
"""Remove a node group from the configuration.
|
979 |
|
980 |
@type group_uuid: string
|
981 |
@param group_uuid: the UUID of the node group to remove
|
982 |
|
983 |
"""
|
984 |
logging.info("Removing node group %s from configuration", group_uuid)
|
985 |
|
986 |
if group_uuid not in self._config_data.nodegroups: |
987 |
raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid) |
988 |
|
989 |
assert len(self._config_data.nodegroups) != 1, \ |
990 |
"Group '%s' is the only group, cannot be removed" % group_uuid
|
991 |
|
992 |
del self._config_data.nodegroups[group_uuid] |
993 |
self._config_data.cluster.serial_no += 1 |
994 |
self._WriteConfig()
|
995 |
|
996 |
def _UnlockedLookupNodeGroup(self, target): |
997 |
"""Lookup a node group's UUID.
|
998 |
|
999 |
@type target: string or None
|
1000 |
@param target: group name or UUID or None to look for the default
|
1001 |
@rtype: string
|
1002 |
@return: nodegroup UUID
|
1003 |
@raises errors.OpPrereqError: when the target group cannot be found
|
1004 |
|
1005 |
"""
|
1006 |
if target is None: |
1007 |
if len(self._config_data.nodegroups) != 1: |
1008 |
raise errors.OpPrereqError("More than one node group exists. Target" |
1009 |
" group must be specified explicitely.")
|
1010 |
else:
|
1011 |
return self._config_data.nodegroups.keys()[0] |
1012 |
if target in self._config_data.nodegroups: |
1013 |
return target
|
1014 |
for nodegroup in self._config_data.nodegroups.values(): |
1015 |
if nodegroup.name == target:
|
1016 |
return nodegroup.uuid
|
1017 |
raise errors.OpPrereqError("Node group '%s' not found" % target, |
1018 |
errors.ECODE_NOENT) |
1019 |
|
1020 |
@locking.ssynchronized(_config_lock, shared=1) |
1021 |
def LookupNodeGroup(self, target): |
1022 |
"""Lookup a node group's UUID.
|
1023 |
|
1024 |
This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
|
1025 |
|
1026 |
@type target: string or None
|
1027 |
@param target: group name or UUID or None to look for the default
|
1028 |
@rtype: string
|
1029 |
@return: nodegroup UUID
|
1030 |
|
1031 |
"""
|
1032 |
return self._UnlockedLookupNodeGroup(target) |
1033 |
|
1034 |
def _UnlockedGetNodeGroup(self, uuid): |
1035 |
"""Lookup a node group.
|
1036 |
|
1037 |
@type uuid: string
|
1038 |
@param uuid: group UUID
|
1039 |
@rtype: L{objects.NodeGroup} or None
|
1040 |
@return: nodegroup object, or None if not found
|
1041 |
|
1042 |
"""
|
1043 |
if uuid not in self._config_data.nodegroups: |
1044 |
return None |
1045 |
|
1046 |
return self._config_data.nodegroups[uuid] |
1047 |
|
1048 |
@locking.ssynchronized(_config_lock, shared=1) |
1049 |
def GetNodeGroup(self, uuid): |
1050 |
"""Lookup a node group.
|
1051 |
|
1052 |
@type uuid: string
|
1053 |
@param uuid: group UUID
|
1054 |
@rtype: L{objects.NodeGroup} or None
|
1055 |
@return: nodegroup object, or None if not found
|
1056 |
|
1057 |
"""
|
1058 |
return self._UnlockedGetNodeGroup(uuid) |
1059 |
|
1060 |
@locking.ssynchronized(_config_lock, shared=1) |
1061 |
def GetAllNodeGroupsInfo(self): |
1062 |
"""Get the configuration of all node groups.
|
1063 |
|
1064 |
"""
|
1065 |
return dict(self._config_data.nodegroups) |
1066 |
|
1067 |
@locking.ssynchronized(_config_lock, shared=1) |
1068 |
def GetNodeGroupList(self): |
1069 |
"""Get a list of node groups.
|
1070 |
|
1071 |
"""
|
1072 |
return self._config_data.nodegroups.keys() |
1073 |
|
1074 |
@locking.ssynchronized(_config_lock)
|
1075 |
def AddInstance(self, instance, ec_id): |
1076 |
"""Add an instance to the config.
|
1077 |
|
1078 |
This should be used after creating a new instance.
|
1079 |
|
1080 |
@type instance: L{objects.Instance}
|
1081 |
@param instance: the instance object
|
1082 |
|
1083 |
"""
|
1084 |
if not isinstance(instance, objects.Instance): |
1085 |
raise errors.ProgrammerError("Invalid type passed to AddInstance") |
1086 |
|
1087 |
if instance.disk_template != constants.DT_DISKLESS:
|
1088 |
all_lvs = instance.MapLVsByNode() |
1089 |
logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
|
1090 |
|
1091 |
all_macs = self._AllMACs()
|
1092 |
for nic in instance.nics: |
1093 |
if nic.mac in all_macs: |
1094 |
raise errors.ConfigurationError("Cannot add instance %s:" |
1095 |
" MAC address '%s' already in use." %
|
1096 |
(instance.name, nic.mac)) |
1097 |
|
1098 |
self._EnsureUUID(instance, ec_id)
|
1099 |
|
1100 |
instance.serial_no = 1
|
1101 |
instance.ctime = instance.mtime = time.time() |
1102 |
self._config_data.instances[instance.name] = instance
|
1103 |
self._config_data.cluster.serial_no += 1 |
1104 |
self._UnlockedReleaseDRBDMinors(instance.name)
|
1105 |
self._WriteConfig()
|
1106 |
|
1107 |
def _EnsureUUID(self, item, ec_id): |
1108 |
"""Ensures a given object has a valid UUID.
|
1109 |
|
1110 |
@param item: the instance or node to be checked
|
1111 |
@param ec_id: the execution context id for the uuid reservation
|
1112 |
|
1113 |
"""
|
1114 |
if not item.uuid: |
1115 |
item.uuid = self._GenerateUniqueID(ec_id)
|
1116 |
elif item.uuid in self._AllIDs(include_temporary=True): |
1117 |
raise errors.ConfigurationError("Cannot add '%s': UUID %s already" |
1118 |
" in use" % (item.name, item.uuid))
|
1119 |
|
1120 |
def _SetInstanceStatus(self, instance_name, status): |
1121 |
"""Set the instance's status to a given value.
|
1122 |
|
1123 |
"""
|
1124 |
assert isinstance(status, bool), \ |
1125 |
"Invalid status '%s' passed to SetInstanceStatus" % (status,)
|
1126 |
|
1127 |
if instance_name not in self._config_data.instances: |
1128 |
raise errors.ConfigurationError("Unknown instance '%s'" % |
1129 |
instance_name) |
1130 |
instance = self._config_data.instances[instance_name]
|
1131 |
if instance.admin_up != status:
|
1132 |
instance.admin_up = status |
1133 |
instance.serial_no += 1
|
1134 |
instance.mtime = time.time() |
1135 |
self._WriteConfig()
|
1136 |
|
1137 |
@locking.ssynchronized(_config_lock)
|
1138 |
def MarkInstanceUp(self, instance_name): |
1139 |
"""Mark the instance status to up in the config.
|
1140 |
|
1141 |
"""
|
1142 |
self._SetInstanceStatus(instance_name, True) |
1143 |
|
1144 |
@locking.ssynchronized(_config_lock)
|
1145 |
def RemoveInstance(self, instance_name): |
1146 |
"""Remove the instance from the configuration.
|
1147 |
|
1148 |
"""
|
1149 |
if instance_name not in self._config_data.instances: |
1150 |
raise errors.ConfigurationError("Unknown instance '%s'" % instance_name) |
1151 |
del self._config_data.instances[instance_name] |
1152 |
self._config_data.cluster.serial_no += 1 |
1153 |
self._WriteConfig()
|
1154 |
|
1155 |
@locking.ssynchronized(_config_lock)
|
1156 |
def RenameInstance(self, old_name, new_name): |
1157 |
"""Rename an instance.
|
1158 |
|
1159 |
This needs to be done in ConfigWriter and not by RemoveInstance
|
1160 |
combined with AddInstance as only we can guarantee an atomic
|
1161 |
rename.
|
1162 |
|
1163 |
"""
|
1164 |
if old_name not in self._config_data.instances: |
1165 |
raise errors.ConfigurationError("Unknown instance '%s'" % old_name) |
1166 |
inst = self._config_data.instances[old_name]
|
1167 |
del self._config_data.instances[old_name] |
1168 |
inst.name = new_name |
1169 |
|
1170 |
for disk in inst.disks: |
1171 |
if disk.dev_type == constants.LD_FILE:
|
1172 |
# rename the file paths in logical and physical id
|
1173 |
file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
|
1174 |
disk_fname = "disk%s" % disk.iv_name.split("/")[1] |
1175 |
disk.physical_id = disk.logical_id = (disk.logical_id[0],
|
1176 |
utils.PathJoin(file_storage_dir, |
1177 |
inst.name, |
1178 |
disk_fname)) |
1179 |
|
1180 |
# Force update of ssconf files
|
1181 |
self._config_data.cluster.serial_no += 1 |
1182 |
|
1183 |
self._config_data.instances[inst.name] = inst
|
1184 |
self._WriteConfig()
|
1185 |
|
1186 |
@locking.ssynchronized(_config_lock)
|
1187 |
def MarkInstanceDown(self, instance_name): |
1188 |
"""Mark the status of an instance to down in the configuration.
|
1189 |
|
1190 |
"""
|
1191 |
self._SetInstanceStatus(instance_name, False) |
1192 |
|
1193 |
def _UnlockedGetInstanceList(self): |
1194 |
"""Get the list of instances.
|
1195 |
|
1196 |
This function is for internal use, when the config lock is already held.
|
1197 |
|
1198 |
"""
|
1199 |
return self._config_data.instances.keys() |
1200 |
|
1201 |
@locking.ssynchronized(_config_lock, shared=1) |
1202 |
def GetInstanceList(self): |
1203 |
"""Get the list of instances.
|
1204 |
|
1205 |
@return: array of instances, ex. ['instance2.example.com',
|
1206 |
'instance1.example.com']
|
1207 |
|
1208 |
"""
|
1209 |
return self._UnlockedGetInstanceList() |
1210 |
|
1211 |
def ExpandInstanceName(self, short_name): |
1212 |
"""Attempt to expand an incomplete instance name.
|
1213 |
|
1214 |
"""
|
1215 |
# Locking is done in L{ConfigWriter.GetInstanceList}
|
1216 |
return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList()) |
1217 |
|
1218 |
def _UnlockedGetInstanceInfo(self, instance_name): |
1219 |
"""Returns information about an instance.
|
1220 |
|
1221 |
This function is for internal use, when the config lock is already held.
|
1222 |
|
1223 |
"""
|
1224 |
if instance_name not in self._config_data.instances: |
1225 |
return None |
1226 |
|
1227 |
return self._config_data.instances[instance_name] |
1228 |
|
1229 |
@locking.ssynchronized(_config_lock, shared=1) |
1230 |
def GetInstanceInfo(self, instance_name): |
1231 |
"""Returns information about an instance.
|
1232 |
|
1233 |
It takes the information from the configuration file. Other information of
|
1234 |
an instance are taken from the live systems.
|
1235 |
|
1236 |
@param instance_name: name of the instance, e.g.
|
1237 |
I{instance1.example.com}
|
1238 |
|
1239 |
@rtype: L{objects.Instance}
|
1240 |
@return: the instance object
|
1241 |
|
1242 |
"""
|
1243 |
return self._UnlockedGetInstanceInfo(instance_name) |
1244 |
|
1245 |
@locking.ssynchronized(_config_lock, shared=1) |
1246 |
def GetAllInstancesInfo(self): |
1247 |
"""Get the configuration of all instances.
|
1248 |
|
1249 |
@rtype: dict
|
1250 |
@return: dict of (instance, instance_info), where instance_info is what
|
1251 |
would GetInstanceInfo return for the node
|
1252 |
|
1253 |
"""
|
1254 |
my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance)) |
1255 |
for instance in self._UnlockedGetInstanceList()]) |
1256 |
return my_dict
|
1257 |
|
1258 |
@locking.ssynchronized(_config_lock)
|
1259 |
def AddNode(self, node, ec_id): |
1260 |
"""Add a node to the configuration.
|
1261 |
|
1262 |
@type node: L{objects.Node}
|
1263 |
@param node: a Node instance
|
1264 |
|
1265 |
"""
|
1266 |
logging.info("Adding node %s to configuration", node.name)
|
1267 |
|
1268 |
self._EnsureUUID(node, ec_id)
|
1269 |
|
1270 |
node.serial_no = 1
|
1271 |
node.ctime = node.mtime = time.time() |
1272 |
self._UnlockedAddNodeToGroup(node.name, node.group)
|
1273 |
self._config_data.nodes[node.name] = node
|
1274 |
self._config_data.cluster.serial_no += 1 |
1275 |
self._WriteConfig()
|
1276 |
|
1277 |
@locking.ssynchronized(_config_lock)
|
1278 |
def RemoveNode(self, node_name): |
1279 |
"""Remove a node from the configuration.
|
1280 |
|
1281 |
"""
|
1282 |
logging.info("Removing node %s from configuration", node_name)
|
1283 |
|
1284 |
if node_name not in self._config_data.nodes: |
1285 |
raise errors.ConfigurationError("Unknown node '%s'" % node_name) |
1286 |
|
1287 |
self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name]) |
1288 |
del self._config_data.nodes[node_name] |
1289 |
self._config_data.cluster.serial_no += 1 |
1290 |
self._WriteConfig()
|
1291 |
|
1292 |
def ExpandNodeName(self, short_name): |
1293 |
"""Attempt to expand an incomplete node name.
|
1294 |
|
1295 |
"""
|
1296 |
# Locking is done in L{ConfigWriter.GetNodeList}
|
1297 |
return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList()) |
1298 |
|
1299 |
def _UnlockedGetNodeInfo(self, node_name): |
1300 |
"""Get the configuration of a node, as stored in the config.
|
1301 |
|
1302 |
This function is for internal use, when the config lock is already
|
1303 |
held.
|
1304 |
|
1305 |
@param node_name: the node name, e.g. I{node1.example.com}
|
1306 |
|
1307 |
@rtype: L{objects.Node}
|
1308 |
@return: the node object
|
1309 |
|
1310 |
"""
|
1311 |
if node_name not in self._config_data.nodes: |
1312 |
return None |
1313 |
|
1314 |
return self._config_data.nodes[node_name] |
1315 |
|
1316 |
@locking.ssynchronized(_config_lock, shared=1) |
1317 |
def GetNodeInfo(self, node_name): |
1318 |
"""Get the configuration of a node, as stored in the config.
|
1319 |
|
1320 |
This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
|
1321 |
|
1322 |
@param node_name: the node name, e.g. I{node1.example.com}
|
1323 |
|
1324 |
@rtype: L{objects.Node}
|
1325 |
@return: the node object
|
1326 |
|
1327 |
"""
|
1328 |
return self._UnlockedGetNodeInfo(node_name) |
1329 |
|
1330 |
@locking.ssynchronized(_config_lock, shared=1) |
1331 |
def GetNodeInstances(self, node_name): |
1332 |
"""Get the instances of a node, as stored in the config.
|
1333 |
|
1334 |
@param node_name: the node name, e.g. I{node1.example.com}
|
1335 |
|
1336 |
@rtype: (list, list)
|
1337 |
@return: a tuple with two lists: the primary and the secondary instances
|
1338 |
|
1339 |
"""
|
1340 |
pri = [] |
1341 |
sec = [] |
1342 |
for inst in self._config_data.instances.values(): |
1343 |
if inst.primary_node == node_name:
|
1344 |
pri.append(inst.name) |
1345 |
if node_name in inst.secondary_nodes: |
1346 |
sec.append(inst.name) |
1347 |
return (pri, sec)
|
1348 |
|
1349 |
def _UnlockedGetNodeList(self): |
1350 |
"""Return the list of nodes which are in the configuration.
|
1351 |
|
1352 |
This function is for internal use, when the config lock is already
|
1353 |
held.
|
1354 |
|
1355 |
@rtype: list
|
1356 |
|
1357 |
"""
|
1358 |
return self._config_data.nodes.keys() |
1359 |
|
1360 |
@locking.ssynchronized(_config_lock, shared=1) |
1361 |
def GetNodeList(self): |
1362 |
"""Return the list of nodes which are in the configuration.
|
1363 |
|
1364 |
"""
|
1365 |
return self._UnlockedGetNodeList() |
1366 |
|
1367 |
def _UnlockedGetOnlineNodeList(self): |
1368 |
"""Return the list of nodes which are online.
|
1369 |
|
1370 |
"""
|
1371 |
all_nodes = [self._UnlockedGetNodeInfo(node)
|
1372 |
for node in self._UnlockedGetNodeList()] |
1373 |
return [node.name for node in all_nodes if not node.offline] |
1374 |
|
1375 |
@locking.ssynchronized(_config_lock, shared=1) |
1376 |
def GetOnlineNodeList(self): |
1377 |
"""Return the list of nodes which are online.
|
1378 |
|
1379 |
"""
|
1380 |
return self._UnlockedGetOnlineNodeList() |
1381 |
|
1382 |
@locking.ssynchronized(_config_lock, shared=1) |
1383 |
def GetVmCapableNodeList(self): |
1384 |
"""Return the list of nodes which are not vm capable.
|
1385 |
|
1386 |
"""
|
1387 |
all_nodes = [self._UnlockedGetNodeInfo(node)
|
1388 |
for node in self._UnlockedGetNodeList()] |
1389 |
return [node.name for node in all_nodes if node.vm_capable] |
1390 |
|
1391 |
@locking.ssynchronized(_config_lock, shared=1) |
1392 |
def GetNonVmCapableNodeList(self): |
1393 |
"""Return the list of nodes which are not vm capable.
|
1394 |
|
1395 |
"""
|
1396 |
all_nodes = [self._UnlockedGetNodeInfo(node)
|
1397 |
for node in self._UnlockedGetNodeList()] |
1398 |
return [node.name for node in all_nodes if not node.vm_capable] |
1399 |
|
1400 |
@locking.ssynchronized(_config_lock, shared=1) |
1401 |
def GetAllNodesInfo(self): |
1402 |
"""Get the configuration of all nodes.
|
1403 |
|
1404 |
@rtype: dict
|
1405 |
@return: dict of (node, node_info), where node_info is what
|
1406 |
would GetNodeInfo return for the node
|
1407 |
|
1408 |
"""
|
1409 |
my_dict = dict([(node, self._UnlockedGetNodeInfo(node)) |
1410 |
for node in self._UnlockedGetNodeList()]) |
1411 |
return my_dict
|
1412 |
|
1413 |
def _UnlockedGetMasterCandidateStats(self, exceptions=None): |
1414 |
"""Get the number of current and maximum desired and possible candidates.
|
1415 |
|
1416 |
@type exceptions: list
|
1417 |
@param exceptions: if passed, list of nodes that should be ignored
|
1418 |
@rtype: tuple
|
1419 |
@return: tuple of (current, desired and possible, possible)
|
1420 |
|
1421 |
"""
|
1422 |
mc_now = mc_should = mc_max = 0
|
1423 |
for node in self._config_data.nodes.values(): |
1424 |
if exceptions and node.name in exceptions: |
1425 |
continue
|
1426 |
if not (node.offline or node.drained) and node.master_capable: |
1427 |
mc_max += 1
|
1428 |
if node.master_candidate:
|
1429 |
mc_now += 1
|
1430 |
mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size) |
1431 |
return (mc_now, mc_should, mc_max)
|
1432 |
|
1433 |
@locking.ssynchronized(_config_lock, shared=1) |
1434 |
def GetMasterCandidateStats(self, exceptions=None): |
1435 |
"""Get the number of current and maximum possible candidates.
|
1436 |
|
1437 |
This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
|
1438 |
|
1439 |
@type exceptions: list
|
1440 |
@param exceptions: if passed, list of nodes that should be ignored
|
1441 |
@rtype: tuple
|
1442 |
@return: tuple of (current, max)
|
1443 |
|
1444 |
"""
|
1445 |
return self._UnlockedGetMasterCandidateStats(exceptions) |
1446 |
|
1447 |
@locking.ssynchronized(_config_lock)
|
1448 |
def MaintainCandidatePool(self, exceptions): |
1449 |
"""Try to grow the candidate pool to the desired size.
|
1450 |
|
1451 |
@type exceptions: list
|
1452 |
@param exceptions: if passed, list of nodes that should be ignored
|
1453 |
@rtype: list
|
1454 |
@return: list with the adjusted nodes (L{objects.Node} instances)
|
1455 |
|
1456 |
"""
|
1457 |
mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
|
1458 |
mod_list = [] |
1459 |
if mc_now < mc_max:
|
1460 |
node_list = self._config_data.nodes.keys()
|
1461 |
random.shuffle(node_list) |
1462 |
for name in node_list: |
1463 |
if mc_now >= mc_max:
|
1464 |
break
|
1465 |
node = self._config_data.nodes[name]
|
1466 |
if (node.master_candidate or node.offline or node.drained or |
1467 |
node.name in exceptions or not node.master_capable): |
1468 |
continue
|
1469 |
mod_list.append(node) |
1470 |
node.master_candidate = True
|
1471 |
node.serial_no += 1
|
1472 |
mc_now += 1
|
1473 |
if mc_now != mc_max:
|
1474 |
# this should not happen
|
1475 |
logging.warning("Warning: MaintainCandidatePool didn't manage to"
|
1476 |
" fill the candidate pool (%d/%d)", mc_now, mc_max)
|
1477 |
if mod_list:
|
1478 |
self._config_data.cluster.serial_no += 1 |
1479 |
self._WriteConfig()
|
1480 |
|
1481 |
return mod_list
|
1482 |
|
1483 |
def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid): |
1484 |
"""Add a given node to the specified group.
|
1485 |
|
1486 |
"""
|
1487 |
if nodegroup_uuid not in self._config_data.nodegroups: |
1488 |
# This can happen if a node group gets deleted between its lookup and
|
1489 |
# when we're adding the first node to it, since we don't keep a lock in
|
1490 |
# the meantime. It's ok though, as we'll fail cleanly if the node group
|
1491 |
# is not found anymore.
|
1492 |
raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid) |
1493 |
if node_name not in self._config_data.nodegroups[nodegroup_uuid].members: |
1494 |
self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
|
1495 |
|
1496 |
def _UnlockedRemoveNodeFromGroup(self, node): |
1497 |
"""Remove a given node from its group.
|
1498 |
|
1499 |
"""
|
1500 |
nodegroup = node.group |
1501 |
if nodegroup not in self._config_data.nodegroups: |
1502 |
logging.warning("Warning: node '%s' has unknown node group '%s'"
|
1503 |
" (while being removed from it)", node.name, nodegroup)
|
1504 |
nodegroup_obj = self._config_data.nodegroups[nodegroup]
|
1505 |
if node.name not in nodegroup_obj.members: |
1506 |
logging.warning("Warning: node '%s' not a member of its node group '%s'"
|
1507 |
" (while being removed from it)", node.name, nodegroup)
|
1508 |
else:
|
1509 |
nodegroup_obj.members.remove(node.name) |
1510 |
|
1511 |
def _BumpSerialNo(self): |
1512 |
"""Bump up the serial number of the config.
|
1513 |
|
1514 |
"""
|
1515 |
self._config_data.serial_no += 1 |
1516 |
self._config_data.mtime = time.time()
|
1517 |
|
1518 |
def _AllUUIDObjects(self): |
1519 |
"""Returns all objects with uuid attributes.
|
1520 |
|
1521 |
"""
|
1522 |
return (self._config_data.instances.values() + |
1523 |
self._config_data.nodes.values() +
|
1524 |
self._config_data.nodegroups.values() +
|
1525 |
[self._config_data.cluster])
|
1526 |
|
1527 |
def _OpenConfig(self, accept_foreign): |
1528 |
"""Read the config data from disk.
|
1529 |
|
1530 |
"""
|
1531 |
raw_data = utils.ReadFile(self._cfg_file)
|
1532 |
|
1533 |
try:
|
1534 |
data = objects.ConfigData.FromDict(serializer.Load(raw_data)) |
1535 |
except Exception, err: |
1536 |
raise errors.ConfigurationError(err)
|
1537 |
|
1538 |
# Make sure the configuration has the right version
|
1539 |
_ValidateConfig(data) |
1540 |
|
1541 |
if (not hasattr(data, 'cluster') or |
1542 |
not hasattr(data.cluster, 'rsahostkeypub')): |
1543 |
raise errors.ConfigurationError("Incomplete configuration" |
1544 |
" (missing cluster.rsahostkeypub)")
|
1545 |
|
1546 |
if data.cluster.master_node != self._my_hostname and not accept_foreign: |
1547 |
msg = ("The configuration denotes node %s as master, while my"
|
1548 |
" hostname is %s; opening a foreign configuration is only"
|
1549 |
" possible in accept_foreign mode" %
|
1550 |
(data.cluster.master_node, self._my_hostname))
|
1551 |
raise errors.ConfigurationError(msg)
|
1552 |
|
1553 |
# Upgrade configuration if needed
|
1554 |
data.UpgradeConfig() |
1555 |
|
1556 |
self._config_data = data
|
1557 |
# reset the last serial as -1 so that the next write will cause
|
1558 |
# ssconf update
|
1559 |
self._last_cluster_serial = -1 |
1560 |
|
1561 |
# And finally run our (custom) config upgrade sequence
|
1562 |
self._UpgradeConfig()
|
1563 |
|
1564 |
self._cfg_id = utils.GetFileID(path=self._cfg_file) |
1565 |
|
1566 |
def _UpgradeConfig(self): |
1567 |
"""Run upgrade steps that cannot be done purely in the objects.
|
1568 |
|
1569 |
This is because some data elements need uniqueness across the
|
1570 |
whole configuration, etc.
|
1571 |
|
1572 |
@warning: this function will call L{_WriteConfig()}, but also
|
1573 |
L{DropECReservations} so it needs to be called only from a
|
1574 |
"safe" place (the constructor). If one wanted to call it with
|
1575 |
the lock held, a DropECReservationUnlocked would need to be
|
1576 |
created first, to avoid causing deadlock.
|
1577 |
|
1578 |
"""
|
1579 |
modified = False
|
1580 |
for item in self._AllUUIDObjects(): |
1581 |
if item.uuid is None: |
1582 |
item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
|
1583 |
modified = True
|
1584 |
if not self._config_data.nodegroups: |
1585 |
default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME |
1586 |
default_nodegroup = objects.NodeGroup(name=default_nodegroup_name, |
1587 |
members=[]) |
1588 |
self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True) |
1589 |
modified = True
|
1590 |
for node in self._config_data.nodes.values(): |
1591 |
if not node.group: |
1592 |
node.group = self.LookupNodeGroup(None) |
1593 |
modified = True
|
1594 |
# This is technically *not* an upgrade, but needs to be done both when
|
1595 |
# nodegroups are being added, and upon normally loading the config,
|
1596 |
# because the members list of a node group is discarded upon
|
1597 |
# serializing/deserializing the object.
|
1598 |
self._UnlockedAddNodeToGroup(node.name, node.group)
|
1599 |
if modified:
|
1600 |
self._WriteConfig()
|
1601 |
# This is ok even if it acquires the internal lock, as _UpgradeConfig is
|
1602 |
# only called at config init time, without the lock held
|
1603 |
self.DropECReservations(_UPGRADE_CONFIG_JID)
|
1604 |
|
1605 |
def _DistributeConfig(self, feedback_fn): |
1606 |
"""Distribute the configuration to the other nodes.
|
1607 |
|
1608 |
Currently, this only copies the configuration file. In the future,
|
1609 |
it could be used to encapsulate the 2/3-phase update mechanism.
|
1610 |
|
1611 |
"""
|
1612 |
if self._offline: |
1613 |
return True |
1614 |
|
1615 |
bad = False
|
1616 |
|
1617 |
node_list = [] |
1618 |
addr_list = [] |
1619 |
myhostname = self._my_hostname
|
1620 |
# we can skip checking whether _UnlockedGetNodeInfo returns None
|
1621 |
# since the node list comes from _UnlocketGetNodeList, and we are
|
1622 |
# called with the lock held, so no modifications should take place
|
1623 |
# in between
|
1624 |
for node_name in self._UnlockedGetNodeList(): |
1625 |
if node_name == myhostname:
|
1626 |
continue
|
1627 |
node_info = self._UnlockedGetNodeInfo(node_name)
|
1628 |
if not node_info.master_candidate: |
1629 |
continue
|
1630 |
node_list.append(node_info.name) |
1631 |
addr_list.append(node_info.primary_ip) |
1632 |
|
1633 |
result = rpc.RpcRunner.call_upload_file(node_list, self._cfg_file,
|
1634 |
address_list=addr_list) |
1635 |
for to_node, to_result in result.items(): |
1636 |
msg = to_result.fail_msg |
1637 |
if msg:
|
1638 |
msg = ("Copy of file %s to node %s failed: %s" %
|
1639 |
(self._cfg_file, to_node, msg))
|
1640 |
logging.error(msg) |
1641 |
|
1642 |
if feedback_fn:
|
1643 |
feedback_fn(msg) |
1644 |
|
1645 |
bad = True
|
1646 |
|
1647 |
return not bad |
1648 |
|
1649 |
def _WriteConfig(self, destination=None, feedback_fn=None): |
1650 |
"""Write the configuration data to persistent storage.
|
1651 |
|
1652 |
"""
|
1653 |
assert feedback_fn is None or callable(feedback_fn) |
1654 |
|
1655 |
# Warn on config errors, but don't abort the save - the
|
1656 |
# configuration has already been modified, and we can't revert;
|
1657 |
# the best we can do is to warn the user and save as is, leaving
|
1658 |
# recovery to the user
|
1659 |
config_errors = self._UnlockedVerifyConfig()
|
1660 |
if config_errors:
|
1661 |
errmsg = ("Configuration data is not consistent: %s" %
|
1662 |
(utils.CommaJoin(config_errors))) |
1663 |
logging.critical(errmsg) |
1664 |
if feedback_fn:
|
1665 |
feedback_fn(errmsg) |
1666 |
|
1667 |
if destination is None: |
1668 |
destination = self._cfg_file
|
1669 |
self._BumpSerialNo()
|
1670 |
txt = serializer.Dump(self._config_data.ToDict())
|
1671 |
|
1672 |
getents = self._getents()
|
1673 |
try:
|
1674 |
fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
|
1675 |
close=False, gid=getents.confd_gid, mode=0640) |
1676 |
except errors.LockError:
|
1677 |
raise errors.ConfigurationError("The configuration file has been" |
1678 |
" modified since the last write, cannot"
|
1679 |
" update")
|
1680 |
try:
|
1681 |
self._cfg_id = utils.GetFileID(fd=fd)
|
1682 |
finally:
|
1683 |
os.close(fd) |
1684 |
|
1685 |
self.write_count += 1 |
1686 |
|
1687 |
# and redistribute the config file to master candidates
|
1688 |
self._DistributeConfig(feedback_fn)
|
1689 |
|
1690 |
# Write ssconf files on all nodes (including locally)
|
1691 |
if self._last_cluster_serial < self._config_data.cluster.serial_no: |
1692 |
if not self._offline: |
1693 |
result = rpc.RpcRunner.call_write_ssconf_files( |
1694 |
self._UnlockedGetOnlineNodeList(),
|
1695 |
self._UnlockedGetSsconfValues())
|
1696 |
|
1697 |
for nname, nresu in result.items(): |
1698 |
msg = nresu.fail_msg |
1699 |
if msg:
|
1700 |
errmsg = ("Error while uploading ssconf files to"
|
1701 |
" node %s: %s" % (nname, msg))
|
1702 |
logging.warning(errmsg) |
1703 |
|
1704 |
if feedback_fn:
|
1705 |
feedback_fn(errmsg) |
1706 |
|
1707 |
self._last_cluster_serial = self._config_data.cluster.serial_no |
1708 |
|
1709 |
def _UnlockedGetSsconfValues(self): |
1710 |
"""Return the values needed by ssconf.
|
1711 |
|
1712 |
@rtype: dict
|
1713 |
@return: a dictionary with keys the ssconf names and values their
|
1714 |
associated value
|
1715 |
|
1716 |
"""
|
1717 |
fn = "\n".join
|
1718 |
instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
|
1719 |
node_names = utils.NiceSort(self._UnlockedGetNodeList())
|
1720 |
node_info = [self._UnlockedGetNodeInfo(name) for name in node_names] |
1721 |
node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
|
1722 |
for ninfo in node_info] |
1723 |
node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
|
1724 |
for ninfo in node_info] |
1725 |
|
1726 |
instance_data = fn(instance_names) |
1727 |
off_data = fn(node.name for node in node_info if node.offline) |
1728 |
on_data = fn(node.name for node in node_info if not node.offline) |
1729 |
mc_data = fn(node.name for node in node_info if node.master_candidate) |
1730 |
mc_ips_data = fn(node.primary_ip for node in node_info |
1731 |
if node.master_candidate)
|
1732 |
node_data = fn(node_names) |
1733 |
node_pri_ips_data = fn(node_pri_ips) |
1734 |
node_snd_ips_data = fn(node_snd_ips) |
1735 |
|
1736 |
cluster = self._config_data.cluster
|
1737 |
cluster_tags = fn(cluster.GetTags()) |
1738 |
|
1739 |
hypervisor_list = fn(cluster.enabled_hypervisors) |
1740 |
|
1741 |
uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
|
1742 |
|
1743 |
nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in |
1744 |
self._config_data.nodegroups.values()]
|
1745 |
nodegroups_data = fn(utils.NiceSort(nodegroups)) |
1746 |
|
1747 |
return {
|
1748 |
constants.SS_CLUSTER_NAME: cluster.cluster_name, |
1749 |
constants.SS_CLUSTER_TAGS: cluster_tags, |
1750 |
constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir, |
1751 |
constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir, |
1752 |
constants.SS_MASTER_CANDIDATES: mc_data, |
1753 |
constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data, |
1754 |
constants.SS_MASTER_IP: cluster.master_ip, |
1755 |
constants.SS_MASTER_NETDEV: cluster.master_netdev, |
1756 |
constants.SS_MASTER_NODE: cluster.master_node, |
1757 |
constants.SS_NODE_LIST: node_data, |
1758 |
constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data, |
1759 |
constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data, |
1760 |
constants.SS_OFFLINE_NODES: off_data, |
1761 |
constants.SS_ONLINE_NODES: on_data, |
1762 |
constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
|
1763 |
constants.SS_INSTANCE_LIST: instance_data, |
1764 |
constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION, |
1765 |
constants.SS_HYPERVISOR_LIST: hypervisor_list, |
1766 |
constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
|
1767 |
constants.SS_UID_POOL: uid_pool, |
1768 |
constants.SS_NODEGROUPS: nodegroups_data, |
1769 |
} |
1770 |
|
1771 |
@locking.ssynchronized(_config_lock, shared=1) |
1772 |
def GetSsconfValues(self): |
1773 |
"""Wrapper using lock around _UnlockedGetSsconf().
|
1774 |
|
1775 |
"""
|
1776 |
return self._UnlockedGetSsconfValues() |
1777 |
|
1778 |
@locking.ssynchronized(_config_lock, shared=1) |
1779 |
def GetVGName(self): |
1780 |
"""Return the volume group name.
|
1781 |
|
1782 |
"""
|
1783 |
return self._config_data.cluster.volume_group_name |
1784 |
|
1785 |
@locking.ssynchronized(_config_lock)
|
1786 |
def SetVGName(self, vg_name): |
1787 |
"""Set the volume group name.
|
1788 |
|
1789 |
"""
|
1790 |
self._config_data.cluster.volume_group_name = vg_name
|
1791 |
self._config_data.cluster.serial_no += 1 |
1792 |
self._WriteConfig()
|
1793 |
|
1794 |
@locking.ssynchronized(_config_lock, shared=1) |
1795 |
def GetDRBDHelper(self): |
1796 |
"""Return DRBD usermode helper.
|
1797 |
|
1798 |
"""
|
1799 |
return self._config_data.cluster.drbd_usermode_helper |
1800 |
|
1801 |
@locking.ssynchronized(_config_lock)
|
1802 |
def SetDRBDHelper(self, drbd_helper): |
1803 |
"""Set DRBD usermode helper.
|
1804 |
|
1805 |
"""
|
1806 |
self._config_data.cluster.drbd_usermode_helper = drbd_helper
|
1807 |
self._config_data.cluster.serial_no += 1 |
1808 |
self._WriteConfig()
|
1809 |
|
1810 |
@locking.ssynchronized(_config_lock, shared=1) |
1811 |
def GetMACPrefix(self): |
1812 |
"""Return the mac prefix.
|
1813 |
|
1814 |
"""
|
1815 |
return self._config_data.cluster.mac_prefix |
1816 |
|
1817 |
@locking.ssynchronized(_config_lock, shared=1) |
1818 |
def GetClusterInfo(self): |
1819 |
"""Returns information about the cluster
|
1820 |
|
1821 |
@rtype: L{objects.Cluster}
|
1822 |
@return: the cluster object
|
1823 |
|
1824 |
"""
|
1825 |
return self._config_data.cluster |
1826 |
|
1827 |
@locking.ssynchronized(_config_lock, shared=1) |
1828 |
def HasAnyDiskOfType(self, dev_type): |
1829 |
"""Check if in there is at disk of the given type in the configuration.
|
1830 |
|
1831 |
"""
|
1832 |
return self._config_data.HasAnyDiskOfType(dev_type) |
1833 |
|
1834 |
@locking.ssynchronized(_config_lock)
|
1835 |
def Update(self, target, feedback_fn): |
1836 |
"""Notify function to be called after updates.
|
1837 |
|
1838 |
This function must be called when an object (as returned by
|
1839 |
GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
|
1840 |
caller wants the modifications saved to the backing store. Note
|
1841 |
that all modified objects will be saved, but the target argument
|
1842 |
is the one the caller wants to ensure that it's saved.
|
1843 |
|
1844 |
@param target: an instance of either L{objects.Cluster},
|
1845 |
L{objects.Node} or L{objects.Instance} which is existing in
|
1846 |
the cluster
|
1847 |
@param feedback_fn: Callable feedback function
|
1848 |
|
1849 |
"""
|
1850 |
if self._config_data is None: |
1851 |
raise errors.ProgrammerError("Configuration file not read," |
1852 |
" cannot save.")
|
1853 |
update_serial = False
|
1854 |
if isinstance(target, objects.Cluster): |
1855 |
test = target == self._config_data.cluster
|
1856 |
elif isinstance(target, objects.Node): |
1857 |
test = target in self._config_data.nodes.values() |
1858 |
update_serial = True
|
1859 |
elif isinstance(target, objects.Instance): |
1860 |
test = target in self._config_data.instances.values() |
1861 |
elif isinstance(target, objects.NodeGroup): |
1862 |
test = target in self._config_data.nodegroups.values() |
1863 |
else:
|
1864 |
raise errors.ProgrammerError("Invalid object type (%s) passed to" |
1865 |
" ConfigWriter.Update" % type(target)) |
1866 |
if not test: |
1867 |
raise errors.ConfigurationError("Configuration updated since object" |
1868 |
" has been read or unknown object")
|
1869 |
target.serial_no += 1
|
1870 |
target.mtime = now = time.time() |
1871 |
|
1872 |
if update_serial:
|
1873 |
# for node updates, we need to increase the cluster serial too
|
1874 |
self._config_data.cluster.serial_no += 1 |
1875 |
self._config_data.cluster.mtime = now
|
1876 |
|
1877 |
if isinstance(target, objects.Instance): |
1878 |
self._UnlockedReleaseDRBDMinors(target.name)
|
1879 |
|
1880 |
self._WriteConfig(feedback_fn=feedback_fn)
|
1881 |
|
1882 |
@locking.ssynchronized(_config_lock)
|
1883 |
def DropECReservations(self, ec_id): |
1884 |
"""Drop per-execution-context reservations
|
1885 |
|
1886 |
"""
|
1887 |
for rm in self._all_rms: |
1888 |
rm.DropECReservations(ec_id) |