root / lib / config.py @ beb81ea5
History | View | Annotate | Download (84.2 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Google Inc.
|
5 |
#
|
6 |
# This program is free software; you can redistribute it and/or modify
|
7 |
# it under the terms of the GNU General Public License as published by
|
8 |
# the Free Software Foundation; either version 2 of the License, or
|
9 |
# (at your option) any later version.
|
10 |
#
|
11 |
# This program is distributed in the hope that it will be useful, but
|
12 |
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
14 |
# General Public License for more details.
|
15 |
#
|
16 |
# You should have received a copy of the GNU General Public License
|
17 |
# along with this program; if not, write to the Free Software
|
18 |
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
|
19 |
# 02110-1301, USA.
|
20 |
|
21 |
|
22 |
"""Configuration management for Ganeti
|
23 |
|
24 |
This module provides the interface to the Ganeti cluster configuration.
|
25 |
|
26 |
The configuration data is stored on every node but is updated on the master
|
27 |
only. After each update, the master distributes the data to the other nodes.
|
28 |
|
29 |
Currently, the data storage format is JSON. YAML was slow and consuming too
|
30 |
much memory.
|
31 |
|
32 |
"""
|
33 |
|
34 |
# pylint: disable=R0904
|
35 |
# R0904: Too many public methods
|
36 |
|
37 |
import os |
38 |
import random |
39 |
import logging |
40 |
import time |
41 |
import itertools |
42 |
from functools import wraps |
43 |
|
44 |
from ganeti import errors |
45 |
from ganeti import locking |
46 |
from ganeti import utils |
47 |
from ganeti import constants |
48 |
from ganeti import rpc |
49 |
from ganeti import objects |
50 |
from ganeti import serializer |
51 |
from ganeti import uidpool |
52 |
from ganeti import netutils |
53 |
from ganeti import runtime |
54 |
from ganeti import pathutils |
55 |
from ganeti import network |
56 |
|
57 |
|
58 |
_config_lock = locking.SharedLock("ConfigWriter")
|
59 |
|
60 |
# job id used for resource management at config upgrade time
|
61 |
_UPGRADE_CONFIG_JID = "jid-cfg-upgrade"
|
62 |
|
63 |
|
64 |
def _ValidateConfig(data): |
65 |
"""Verifies that a configuration objects looks valid.
|
66 |
|
67 |
This only verifies the version of the configuration.
|
68 |
|
69 |
@raise errors.ConfigurationError: if the version differs from what
|
70 |
we expect
|
71 |
|
72 |
"""
|
73 |
if data.version != constants.CONFIG_VERSION:
|
74 |
raise errors.ConfigVersionMismatch(constants.CONFIG_VERSION, data.version)
|
75 |
|
76 |
|
77 |
class TemporaryReservationManager: |
78 |
"""A temporary resource reservation manager.
|
79 |
|
80 |
This is used to reserve resources in a job, before using them, making sure
|
81 |
other jobs cannot get them in the meantime.
|
82 |
|
83 |
"""
|
84 |
def __init__(self): |
85 |
self._ec_reserved = {}
|
86 |
|
87 |
def Reserved(self, resource): |
88 |
for holder_reserved in self._ec_reserved.values(): |
89 |
if resource in holder_reserved: |
90 |
return True |
91 |
return False |
92 |
|
93 |
def Reserve(self, ec_id, resource): |
94 |
if self.Reserved(resource): |
95 |
raise errors.ReservationError("Duplicate reservation for resource '%s'" |
96 |
% str(resource))
|
97 |
if ec_id not in self._ec_reserved: |
98 |
self._ec_reserved[ec_id] = set([resource]) |
99 |
else:
|
100 |
self._ec_reserved[ec_id].add(resource)
|
101 |
|
102 |
def DropECReservations(self, ec_id): |
103 |
if ec_id in self._ec_reserved: |
104 |
del self._ec_reserved[ec_id] |
105 |
|
106 |
def GetReserved(self): |
107 |
all_reserved = set()
|
108 |
for holder_reserved in self._ec_reserved.values(): |
109 |
all_reserved.update(holder_reserved) |
110 |
return all_reserved
|
111 |
|
112 |
def GetECReserved(self, ec_id): |
113 |
ec_reserved = set()
|
114 |
if ec_id in self._ec_reserved: |
115 |
ec_reserved.update(self._ec_reserved[ec_id])
|
116 |
return ec_reserved
|
117 |
|
118 |
|
119 |
def Generate(self, existing, generate_one_fn, ec_id): |
120 |
"""Generate a new resource of this type
|
121 |
|
122 |
"""
|
123 |
assert callable(generate_one_fn) |
124 |
|
125 |
all_elems = self.GetReserved()
|
126 |
all_elems.update(existing) |
127 |
retries = 64
|
128 |
while retries > 0: |
129 |
new_resource = generate_one_fn() |
130 |
if new_resource is not None and new_resource not in all_elems: |
131 |
break
|
132 |
else:
|
133 |
raise errors.ConfigurationError("Not able generate new resource" |
134 |
" (last tried: %s)" % new_resource)
|
135 |
self.Reserve(ec_id, new_resource)
|
136 |
return new_resource
|
137 |
|
138 |
|
139 |
def _MatchNameComponentIgnoreCase(short_name, names): |
140 |
"""Wrapper around L{utils.text.MatchNameComponent}.
|
141 |
|
142 |
"""
|
143 |
return utils.MatchNameComponent(short_name, names, case_sensitive=False) |
144 |
|
145 |
|
146 |
def _CheckInstanceDiskIvNames(disks): |
147 |
"""Checks if instance's disks' C{iv_name} attributes are in order.
|
148 |
|
149 |
@type disks: list of L{objects.Disk}
|
150 |
@param disks: List of disks
|
151 |
@rtype: list of tuples; (int, string, string)
|
152 |
@return: List of wrongly named disks, each tuple contains disk index,
|
153 |
expected and actual name
|
154 |
|
155 |
"""
|
156 |
result = [] |
157 |
|
158 |
for (idx, disk) in enumerate(disks): |
159 |
exp_iv_name = "disk/%s" % idx
|
160 |
if disk.iv_name != exp_iv_name:
|
161 |
result.append((idx, exp_iv_name, disk.iv_name)) |
162 |
|
163 |
return result
|
164 |
|
165 |
def _GenerateMACSuffix(): |
166 |
"""Generate one mac address
|
167 |
|
168 |
"""
|
169 |
byte1 = random.randrange(0, 256) |
170 |
byte2 = random.randrange(0, 256) |
171 |
byte3 = random.randrange(0, 256) |
172 |
suffix = "%02x:%02x:%02x" % (byte1, byte2, byte3)
|
173 |
return suffix
|
174 |
|
175 |
|
176 |
class ConfigWriter: |
177 |
"""The interface to the cluster configuration.
|
178 |
|
179 |
@ivar _temporary_lvs: reservation manager for temporary LVs
|
180 |
@ivar _all_rms: a list of all temporary reservation managers
|
181 |
|
182 |
"""
|
183 |
def __init__(self, cfg_file=None, offline=False, _getents=runtime.GetEnts, |
184 |
accept_foreign=False):
|
185 |
self.write_count = 0 |
186 |
self._lock = _config_lock
|
187 |
self._config_data = None |
188 |
self._offline = offline
|
189 |
if cfg_file is None: |
190 |
self._cfg_file = pathutils.CLUSTER_CONF_FILE
|
191 |
else:
|
192 |
self._cfg_file = cfg_file
|
193 |
self._getents = _getents
|
194 |
self._temporary_ids = TemporaryReservationManager()
|
195 |
self._temporary_drbds = {}
|
196 |
self._temporary_macs = TemporaryReservationManager()
|
197 |
self._temporary_secrets = TemporaryReservationManager()
|
198 |
self._temporary_lvs = TemporaryReservationManager()
|
199 |
self._temporary_ips = TemporaryReservationManager()
|
200 |
self._all_rms = [self._temporary_ids, self._temporary_macs, |
201 |
self._temporary_secrets, self._temporary_lvs, |
202 |
self._temporary_ips]
|
203 |
# Note: in order to prevent errors when resolving our name in
|
204 |
# _DistributeConfig, we compute it here once and reuse it; it's
|
205 |
# better to raise an error before starting to modify the config
|
206 |
# file than after it was modified
|
207 |
self._my_hostname = netutils.Hostname.GetSysName()
|
208 |
self._last_cluster_serial = -1 |
209 |
self._cfg_id = None |
210 |
self._context = None |
211 |
self._OpenConfig(accept_foreign)
|
212 |
|
213 |
def _GetRpc(self, address_list): |
214 |
"""Returns RPC runner for configuration.
|
215 |
|
216 |
"""
|
217 |
return rpc.ConfigRunner(self._context, address_list) |
218 |
|
219 |
def SetContext(self, context): |
220 |
"""Sets Ganeti context.
|
221 |
|
222 |
"""
|
223 |
self._context = context
|
224 |
|
225 |
# this method needs to be static, so that we can call it on the class
|
226 |
@staticmethod
|
227 |
def IsCluster(): |
228 |
"""Check if the cluster is configured.
|
229 |
|
230 |
"""
|
231 |
return os.path.exists(pathutils.CLUSTER_CONF_FILE)
|
232 |
|
233 |
def _GenerateMACPrefix(self, net=None): |
234 |
def _get_mac_prefix(view_func): |
235 |
def _decorator(*args, **kwargs): |
236 |
prefix = self._config_data.cluster.mac_prefix
|
237 |
if net:
|
238 |
net_uuid = self._UnlockedLookupNetwork(net)
|
239 |
if net_uuid:
|
240 |
nobj = self._UnlockedGetNetwork(net_uuid)
|
241 |
if nobj.mac_prefix:
|
242 |
prefix = nobj.mac_prefix |
243 |
suffix = view_func(*args, **kwargs) |
244 |
return prefix+':'+suffix |
245 |
return wraps(view_func)(_decorator)
|
246 |
return _get_mac_prefix
|
247 |
|
248 |
@locking.ssynchronized(_config_lock, shared=1) |
249 |
def GetNdParams(self, node): |
250 |
"""Get the node params populated with cluster defaults.
|
251 |
|
252 |
@type node: L{objects.Node}
|
253 |
@param node: The node we want to know the params for
|
254 |
@return: A dict with the filled in node params
|
255 |
|
256 |
"""
|
257 |
nodegroup = self._UnlockedGetNodeGroup(node.group)
|
258 |
return self._config_data.cluster.FillND(node, nodegroup) |
259 |
|
260 |
@locking.ssynchronized(_config_lock, shared=1) |
261 |
def GetInstanceDiskParams(self, instance): |
262 |
"""Get the disk params populated with inherit chain.
|
263 |
|
264 |
@type instance: L{objects.Instance}
|
265 |
@param instance: The instance we want to know the params for
|
266 |
@return: A dict with the filled in disk params
|
267 |
|
268 |
"""
|
269 |
node = self._UnlockedGetNodeInfo(instance.primary_node)
|
270 |
nodegroup = self._UnlockedGetNodeGroup(node.group)
|
271 |
return self._UnlockedGetGroupDiskParams(nodegroup) |
272 |
|
273 |
@locking.ssynchronized(_config_lock, shared=1) |
274 |
def GetGroupDiskParams(self, group): |
275 |
"""Get the disk params populated with inherit chain.
|
276 |
|
277 |
@type group: L{objects.NodeGroup}
|
278 |
@param group: The group we want to know the params for
|
279 |
@return: A dict with the filled in disk params
|
280 |
|
281 |
"""
|
282 |
return self._UnlockedGetGroupDiskParams(group) |
283 |
|
284 |
def _UnlockedGetGroupDiskParams(self, group): |
285 |
"""Get the disk params populated with inherit chain down to node-group.
|
286 |
|
287 |
@type group: L{objects.NodeGroup}
|
288 |
@param group: The group we want to know the params for
|
289 |
@return: A dict with the filled in disk params
|
290 |
|
291 |
"""
|
292 |
return self._config_data.cluster.SimpleFillDP(group.diskparams) |
293 |
|
294 |
@locking.ssynchronized(_config_lock, shared=1) |
295 |
def GenerateMAC(self, net, ec_id): |
296 |
"""Generate a MAC for an instance.
|
297 |
|
298 |
This should check the current instances for duplicates.
|
299 |
|
300 |
"""
|
301 |
existing = self._AllMACs()
|
302 |
gen_mac = self._GenerateMACPrefix(net)(_GenerateMACSuffix)
|
303 |
return self._temporary_ids.Generate(existing, gen_mac, ec_id) |
304 |
|
305 |
@locking.ssynchronized(_config_lock, shared=1) |
306 |
def ReserveMAC(self, mac, ec_id): |
307 |
"""Reserve a MAC for an instance.
|
308 |
|
309 |
This only checks instances managed by this cluster, it does not
|
310 |
check for potential collisions elsewhere.
|
311 |
|
312 |
"""
|
313 |
all_macs = self._AllMACs()
|
314 |
if mac in all_macs: |
315 |
raise errors.ReservationError("mac already in use") |
316 |
else:
|
317 |
self._temporary_macs.Reserve(ec_id, mac)
|
318 |
|
319 |
def _UnlockedCommitTemporaryIps(self, ec_id): |
320 |
"""Commit all reserved IP address to their respective pools
|
321 |
|
322 |
"""
|
323 |
for action, address, net_uuid in self._temporary_ips.GetECReserved(ec_id): |
324 |
self._UnlockedCommitIp(action, net_uuid, address)
|
325 |
|
326 |
def _UnlockedCommitIp(self, action, net_uuid, address): |
327 |
"""Commit a reserved IP address to an IP pool.
|
328 |
|
329 |
The IP address is taken from the network's IP pool and marked as reserved.
|
330 |
|
331 |
"""
|
332 |
nobj = self._UnlockedGetNetwork(net_uuid)
|
333 |
pool = network.AddressPool(nobj) |
334 |
if action == 'reserve': |
335 |
pool.Reserve(address) |
336 |
elif action == 'release': |
337 |
pool.Release(address) |
338 |
|
339 |
def _UnlockedReleaseIp(self, net_uuid, address, ec_id): |
340 |
"""Give a specific IP address back to an IP pool.
|
341 |
|
342 |
The IP address is returned to the IP pool designated by pool_id and marked
|
343 |
as reserved.
|
344 |
|
345 |
"""
|
346 |
self._temporary_ips.Reserve(ec_id, ('release', address, net_uuid)) |
347 |
|
348 |
@locking.ssynchronized(_config_lock, shared=1) |
349 |
def ReleaseIp(self, net, address, ec_id): |
350 |
"""Give a specified IP address back to an IP pool.
|
351 |
|
352 |
This is just a wrapper around _UnlockedReleaseIp.
|
353 |
|
354 |
"""
|
355 |
net_uuid = self._UnlockedLookupNetwork(net)
|
356 |
if net_uuid:
|
357 |
self._UnlockedReleaseIp(net_uuid, address, ec_id)
|
358 |
|
359 |
@locking.ssynchronized(_config_lock, shared=1) |
360 |
def GenerateIp(self, net, ec_id): |
361 |
"""Find a free IPv4 address for an instance.
|
362 |
|
363 |
"""
|
364 |
net_uuid = self._UnlockedLookupNetwork(net)
|
365 |
nobj = self._UnlockedGetNetwork(net_uuid)
|
366 |
pool = network.AddressPool(nobj) |
367 |
gen_free = pool.GenerateFree() |
368 |
|
369 |
def gen_one(): |
370 |
try:
|
371 |
ip = gen_free() |
372 |
except StopIteration: |
373 |
raise errors.ReservationError("Cannot generate IP. Network is full") |
374 |
return ("reserve", ip, net_uuid) |
375 |
|
376 |
_, address, _ = self._temporary_ips.Generate([], gen_one, ec_id)
|
377 |
return address
|
378 |
|
379 |
def _UnlockedReserveIp(self, net_uuid, address, ec_id): |
380 |
"""Reserve a given IPv4 address for use by an instance.
|
381 |
|
382 |
"""
|
383 |
nobj = self._UnlockedGetNetwork(net_uuid)
|
384 |
pool = network.AddressPool(nobj) |
385 |
try:
|
386 |
isreserved = pool.IsReserved(address) |
387 |
except errors.AddressPoolError:
|
388 |
raise errors.ReservationError("IP address not in network") |
389 |
if isreserved:
|
390 |
raise errors.ReservationError("IP address already in use") |
391 |
|
392 |
return self._temporary_ips.Reserve(ec_id, ('reserve', address, net_uuid)) |
393 |
|
394 |
|
395 |
@locking.ssynchronized(_config_lock, shared=1) |
396 |
def ReserveIp(self, net, address, ec_id): |
397 |
"""Reserve a given IPv4 address for use by an instance.
|
398 |
|
399 |
"""
|
400 |
net_uuid = self._UnlockedLookupNetwork(net)
|
401 |
if net_uuid:
|
402 |
return self._UnlockedReserveIp(net_uuid, address, ec_id) |
403 |
|
404 |
@locking.ssynchronized(_config_lock, shared=1) |
405 |
def ReserveLV(self, lv_name, ec_id): |
406 |
"""Reserve an VG/LV pair for an instance.
|
407 |
|
408 |
@type lv_name: string
|
409 |
@param lv_name: the logical volume name to reserve
|
410 |
|
411 |
"""
|
412 |
all_lvs = self._AllLVs()
|
413 |
if lv_name in all_lvs: |
414 |
raise errors.ReservationError("LV already in use") |
415 |
else:
|
416 |
self._temporary_lvs.Reserve(ec_id, lv_name)
|
417 |
|
418 |
@locking.ssynchronized(_config_lock, shared=1) |
419 |
def GenerateDRBDSecret(self, ec_id): |
420 |
"""Generate a DRBD secret.
|
421 |
|
422 |
This checks the current disks for duplicates.
|
423 |
|
424 |
"""
|
425 |
return self._temporary_secrets.Generate(self._AllDRBDSecrets(), |
426 |
utils.GenerateSecret, |
427 |
ec_id) |
428 |
|
429 |
def _AllLVs(self): |
430 |
"""Compute the list of all LVs.
|
431 |
|
432 |
"""
|
433 |
lvnames = set()
|
434 |
for instance in self._config_data.instances.values(): |
435 |
node_data = instance.MapLVsByNode() |
436 |
for lv_list in node_data.values(): |
437 |
lvnames.update(lv_list) |
438 |
return lvnames
|
439 |
|
440 |
def _AllIDs(self, include_temporary): |
441 |
"""Compute the list of all UUIDs and names we have.
|
442 |
|
443 |
@type include_temporary: boolean
|
444 |
@param include_temporary: whether to include the _temporary_ids set
|
445 |
@rtype: set
|
446 |
@return: a set of IDs
|
447 |
|
448 |
"""
|
449 |
existing = set()
|
450 |
if include_temporary:
|
451 |
existing.update(self._temporary_ids.GetReserved())
|
452 |
existing.update(self._AllLVs())
|
453 |
existing.update(self._config_data.instances.keys())
|
454 |
existing.update(self._config_data.nodes.keys())
|
455 |
existing.update([i.uuid for i in self._AllUUIDObjects() if i.uuid]) |
456 |
return existing
|
457 |
|
458 |
def _GenerateUniqueID(self, ec_id): |
459 |
"""Generate an unique UUID.
|
460 |
|
461 |
This checks the current node, instances and disk names for
|
462 |
duplicates.
|
463 |
|
464 |
@rtype: string
|
465 |
@return: the unique id
|
466 |
|
467 |
"""
|
468 |
existing = self._AllIDs(include_temporary=False) |
469 |
return self._temporary_ids.Generate(existing, utils.NewUUID, ec_id) |
470 |
|
471 |
@locking.ssynchronized(_config_lock, shared=1) |
472 |
def GenerateUniqueID(self, ec_id): |
473 |
"""Generate an unique ID.
|
474 |
|
475 |
This is just a wrapper over the unlocked version.
|
476 |
|
477 |
@type ec_id: string
|
478 |
@param ec_id: unique id for the job to reserve the id to
|
479 |
|
480 |
"""
|
481 |
return self._GenerateUniqueID(ec_id) |
482 |
|
483 |
def _AllMACs(self): |
484 |
"""Return all MACs present in the config.
|
485 |
|
486 |
@rtype: list
|
487 |
@return: the list of all MACs
|
488 |
|
489 |
"""
|
490 |
result = [] |
491 |
for instance in self._config_data.instances.values(): |
492 |
for nic in instance.nics: |
493 |
result.append(nic.mac) |
494 |
|
495 |
return result
|
496 |
|
497 |
def _AllDRBDSecrets(self): |
498 |
"""Return all DRBD secrets present in the config.
|
499 |
|
500 |
@rtype: list
|
501 |
@return: the list of all DRBD secrets
|
502 |
|
503 |
"""
|
504 |
def helper(disk, result): |
505 |
"""Recursively gather secrets from this disk."""
|
506 |
if disk.dev_type == constants.DT_DRBD8:
|
507 |
result.append(disk.logical_id[5])
|
508 |
if disk.children:
|
509 |
for child in disk.children: |
510 |
helper(child, result) |
511 |
|
512 |
result = [] |
513 |
for instance in self._config_data.instances.values(): |
514 |
for disk in instance.disks: |
515 |
helper(disk, result) |
516 |
|
517 |
return result
|
518 |
|
519 |
def _CheckDiskIDs(self, disk, l_ids, p_ids): |
520 |
"""Compute duplicate disk IDs
|
521 |
|
522 |
@type disk: L{objects.Disk}
|
523 |
@param disk: the disk at which to start searching
|
524 |
@type l_ids: list
|
525 |
@param l_ids: list of current logical ids
|
526 |
@type p_ids: list
|
527 |
@param p_ids: list of current physical ids
|
528 |
@rtype: list
|
529 |
@return: a list of error messages
|
530 |
|
531 |
"""
|
532 |
result = [] |
533 |
if disk.logical_id is not None: |
534 |
if disk.logical_id in l_ids: |
535 |
result.append("duplicate logical id %s" % str(disk.logical_id)) |
536 |
else:
|
537 |
l_ids.append(disk.logical_id) |
538 |
if disk.physical_id is not None: |
539 |
if disk.physical_id in p_ids: |
540 |
result.append("duplicate physical id %s" % str(disk.physical_id)) |
541 |
else:
|
542 |
p_ids.append(disk.physical_id) |
543 |
|
544 |
if disk.children:
|
545 |
for child in disk.children: |
546 |
result.extend(self._CheckDiskIDs(child, l_ids, p_ids))
|
547 |
return result
|
548 |
|
549 |
def _UnlockedVerifyConfig(self): |
550 |
"""Verify function.
|
551 |
|
552 |
@rtype: list
|
553 |
@return: a list of error messages; a non-empty list signifies
|
554 |
configuration errors
|
555 |
|
556 |
"""
|
557 |
# pylint: disable=R0914
|
558 |
result = [] |
559 |
seen_macs = [] |
560 |
ports = {} |
561 |
data = self._config_data
|
562 |
cluster = data.cluster |
563 |
seen_lids = [] |
564 |
seen_pids = [] |
565 |
|
566 |
# global cluster checks
|
567 |
if not cluster.enabled_hypervisors: |
568 |
result.append("enabled hypervisors list doesn't have any entries")
|
569 |
invalid_hvs = set(cluster.enabled_hypervisors) - constants.HYPER_TYPES
|
570 |
if invalid_hvs:
|
571 |
result.append("enabled hypervisors contains invalid entries: %s" %
|
572 |
invalid_hvs) |
573 |
missing_hvp = (set(cluster.enabled_hypervisors) -
|
574 |
set(cluster.hvparams.keys()))
|
575 |
if missing_hvp:
|
576 |
result.append("hypervisor parameters missing for the enabled"
|
577 |
" hypervisor(s) %s" % utils.CommaJoin(missing_hvp))
|
578 |
|
579 |
if cluster.master_node not in data.nodes: |
580 |
result.append("cluster has invalid primary node '%s'" %
|
581 |
cluster.master_node) |
582 |
|
583 |
def _helper(owner, attr, value, template): |
584 |
try:
|
585 |
utils.ForceDictType(value, template) |
586 |
except errors.GenericError, err:
|
587 |
result.append("%s has invalid %s: %s" % (owner, attr, err))
|
588 |
|
589 |
def _helper_nic(owner, params): |
590 |
try:
|
591 |
objects.NIC.CheckParameterSyntax(params) |
592 |
except errors.ConfigurationError, err:
|
593 |
result.append("%s has invalid nicparams: %s" % (owner, err))
|
594 |
|
595 |
def _helper_ipolicy(owner, params, check_std): |
596 |
try:
|
597 |
objects.InstancePolicy.CheckParameterSyntax(params, check_std) |
598 |
except errors.ConfigurationError, err:
|
599 |
result.append("%s has invalid instance policy: %s" % (owner, err))
|
600 |
|
601 |
def _helper_ispecs(owner, params): |
602 |
for key, value in params.items(): |
603 |
if key in constants.IPOLICY_ISPECS: |
604 |
fullkey = "ipolicy/" + key
|
605 |
_helper(owner, fullkey, value, constants.ISPECS_PARAMETER_TYPES) |
606 |
else:
|
607 |
# FIXME: assuming list type
|
608 |
if key in constants.IPOLICY_PARAMETERS: |
609 |
exp_type = float
|
610 |
else:
|
611 |
exp_type = list
|
612 |
if not isinstance(value, exp_type): |
613 |
result.append("%s has invalid instance policy: for %s,"
|
614 |
" expecting %s, got %s" %
|
615 |
(owner, key, exp_type.__name__, type(value)))
|
616 |
|
617 |
# check cluster parameters
|
618 |
_helper("cluster", "beparams", cluster.SimpleFillBE({}), |
619 |
constants.BES_PARAMETER_TYPES) |
620 |
_helper("cluster", "nicparams", cluster.SimpleFillNIC({}), |
621 |
constants.NICS_PARAMETER_TYPES) |
622 |
_helper_nic("cluster", cluster.SimpleFillNIC({}))
|
623 |
_helper("cluster", "ndparams", cluster.SimpleFillND({}), |
624 |
constants.NDS_PARAMETER_TYPES) |
625 |
_helper_ipolicy("cluster", cluster.SimpleFillIPolicy({}), True) |
626 |
_helper_ispecs("cluster", cluster.SimpleFillIPolicy({}))
|
627 |
|
628 |
# per-instance checks
|
629 |
for instance_name in data.instances: |
630 |
instance = data.instances[instance_name] |
631 |
if instance.name != instance_name:
|
632 |
result.append("instance '%s' is indexed by wrong name '%s'" %
|
633 |
(instance.name, instance_name)) |
634 |
if instance.primary_node not in data.nodes: |
635 |
result.append("instance '%s' has invalid primary node '%s'" %
|
636 |
(instance_name, instance.primary_node)) |
637 |
for snode in instance.secondary_nodes: |
638 |
if snode not in data.nodes: |
639 |
result.append("instance '%s' has invalid secondary node '%s'" %
|
640 |
(instance_name, snode)) |
641 |
for idx, nic in enumerate(instance.nics): |
642 |
if nic.mac in seen_macs: |
643 |
result.append("instance '%s' has NIC %d mac %s duplicate" %
|
644 |
(instance_name, idx, nic.mac)) |
645 |
else:
|
646 |
seen_macs.append(nic.mac) |
647 |
if nic.nicparams:
|
648 |
filled = cluster.SimpleFillNIC(nic.nicparams) |
649 |
owner = "instance %s nic %d" % (instance.name, idx)
|
650 |
_helper(owner, "nicparams",
|
651 |
filled, constants.NICS_PARAMETER_TYPES) |
652 |
_helper_nic(owner, filled) |
653 |
|
654 |
# parameter checks
|
655 |
if instance.beparams:
|
656 |
_helper("instance %s" % instance.name, "beparams", |
657 |
cluster.FillBE(instance), constants.BES_PARAMETER_TYPES) |
658 |
|
659 |
# gather the drbd ports for duplicate checks
|
660 |
for (idx, dsk) in enumerate(instance.disks): |
661 |
if dsk.dev_type in constants.LDS_DRBD: |
662 |
tcp_port = dsk.logical_id[2]
|
663 |
if tcp_port not in ports: |
664 |
ports[tcp_port] = [] |
665 |
ports[tcp_port].append((instance.name, "drbd disk %s" % idx))
|
666 |
# gather network port reservation
|
667 |
net_port = getattr(instance, "network_port", None) |
668 |
if net_port is not None: |
669 |
if net_port not in ports: |
670 |
ports[net_port] = [] |
671 |
ports[net_port].append((instance.name, "network port"))
|
672 |
|
673 |
# instance disk verify
|
674 |
for idx, disk in enumerate(instance.disks): |
675 |
result.extend(["instance '%s' disk %d error: %s" %
|
676 |
(instance.name, idx, msg) for msg in disk.Verify()]) |
677 |
result.extend(self._CheckDiskIDs(disk, seen_lids, seen_pids))
|
678 |
|
679 |
wrong_names = _CheckInstanceDiskIvNames(instance.disks) |
680 |
if wrong_names:
|
681 |
tmp = "; ".join(("name of disk %s should be '%s', but is '%s'" % |
682 |
(idx, exp_name, actual_name)) |
683 |
for (idx, exp_name, actual_name) in wrong_names) |
684 |
|
685 |
result.append("Instance '%s' has wrongly named disks: %s" %
|
686 |
(instance.name, tmp)) |
687 |
|
688 |
# cluster-wide pool of free ports
|
689 |
for free_port in cluster.tcpudp_port_pool: |
690 |
if free_port not in ports: |
691 |
ports[free_port] = [] |
692 |
ports[free_port].append(("cluster", "port marked as free")) |
693 |
|
694 |
# compute tcp/udp duplicate ports
|
695 |
keys = ports.keys() |
696 |
keys.sort() |
697 |
for pnum in keys: |
698 |
pdata = ports[pnum] |
699 |
if len(pdata) > 1: |
700 |
txt = utils.CommaJoin(["%s/%s" % val for val in pdata]) |
701 |
result.append("tcp/udp port %s has duplicates: %s" % (pnum, txt))
|
702 |
|
703 |
# highest used tcp port check
|
704 |
if keys:
|
705 |
if keys[-1] > cluster.highest_used_port: |
706 |
result.append("Highest used port mismatch, saved %s, computed %s" %
|
707 |
(cluster.highest_used_port, keys[-1]))
|
708 |
|
709 |
if not data.nodes[cluster.master_node].master_candidate: |
710 |
result.append("Master node is not a master candidate")
|
711 |
|
712 |
# master candidate checks
|
713 |
mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats()
|
714 |
if mc_now < mc_max:
|
715 |
result.append("Not enough master candidates: actual %d, target %d" %
|
716 |
(mc_now, mc_max)) |
717 |
|
718 |
# node checks
|
719 |
for node_name, node in data.nodes.items(): |
720 |
if node.name != node_name:
|
721 |
result.append("Node '%s' is indexed by wrong name '%s'" %
|
722 |
(node.name, node_name)) |
723 |
if [node.master_candidate, node.drained, node.offline].count(True) > 1: |
724 |
result.append("Node %s state is invalid: master_candidate=%s,"
|
725 |
" drain=%s, offline=%s" %
|
726 |
(node.name, node.master_candidate, node.drained, |
727 |
node.offline)) |
728 |
if node.group not in data.nodegroups: |
729 |
result.append("Node '%s' has invalid group '%s'" %
|
730 |
(node.name, node.group)) |
731 |
else:
|
732 |
_helper("node %s" % node.name, "ndparams", |
733 |
cluster.FillND(node, data.nodegroups[node.group]), |
734 |
constants.NDS_PARAMETER_TYPES) |
735 |
|
736 |
# nodegroups checks
|
737 |
nodegroups_names = set()
|
738 |
for nodegroup_uuid in data.nodegroups: |
739 |
nodegroup = data.nodegroups[nodegroup_uuid] |
740 |
if nodegroup.uuid != nodegroup_uuid:
|
741 |
result.append("node group '%s' (uuid: '%s') indexed by wrong uuid '%s'"
|
742 |
% (nodegroup.name, nodegroup.uuid, nodegroup_uuid)) |
743 |
if utils.UUID_RE.match(nodegroup.name.lower()):
|
744 |
result.append("node group '%s' (uuid: '%s') has uuid-like name" %
|
745 |
(nodegroup.name, nodegroup.uuid)) |
746 |
if nodegroup.name in nodegroups_names: |
747 |
result.append("duplicate node group name '%s'" % nodegroup.name)
|
748 |
else:
|
749 |
nodegroups_names.add(nodegroup.name) |
750 |
group_name = "group %s" % nodegroup.name
|
751 |
_helper_ipolicy(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy), |
752 |
False)
|
753 |
_helper_ispecs(group_name, cluster.SimpleFillIPolicy(nodegroup.ipolicy)) |
754 |
if nodegroup.ndparams:
|
755 |
_helper(group_name, "ndparams",
|
756 |
cluster.SimpleFillND(nodegroup.ndparams), |
757 |
constants.NDS_PARAMETER_TYPES) |
758 |
|
759 |
# drbd minors check
|
760 |
_, duplicates = self._UnlockedComputeDRBDMap()
|
761 |
for node, minor, instance_a, instance_b in duplicates: |
762 |
result.append("DRBD minor %d on node %s is assigned twice to instances"
|
763 |
" %s and %s" % (minor, node, instance_a, instance_b))
|
764 |
|
765 |
# IP checks
|
766 |
default_nicparams = cluster.nicparams[constants.PP_DEFAULT] |
767 |
ips = {} |
768 |
|
769 |
def _AddIpAddress(ip, name): |
770 |
ips.setdefault(ip, []).append(name) |
771 |
|
772 |
_AddIpAddress(cluster.master_ip, "cluster_ip")
|
773 |
|
774 |
for node in data.nodes.values(): |
775 |
_AddIpAddress(node.primary_ip, "node:%s/primary" % node.name)
|
776 |
if node.secondary_ip != node.primary_ip:
|
777 |
_AddIpAddress(node.secondary_ip, "node:%s/secondary" % node.name)
|
778 |
|
779 |
for instance in data.instances.values(): |
780 |
for idx, nic in enumerate(instance.nics): |
781 |
if nic.ip is None: |
782 |
continue
|
783 |
|
784 |
nicparams = objects.FillDict(default_nicparams, nic.nicparams) |
785 |
nic_mode = nicparams[constants.NIC_MODE] |
786 |
nic_link = nicparams[constants.NIC_LINK] |
787 |
|
788 |
if nic_mode == constants.NIC_MODE_BRIDGED:
|
789 |
link = "bridge:%s" % nic_link
|
790 |
elif nic_mode == constants.NIC_MODE_ROUTED:
|
791 |
link = "route:%s" % nic_link
|
792 |
else:
|
793 |
raise errors.ProgrammerError("NIC mode '%s' not handled" % nic_mode) |
794 |
|
795 |
_AddIpAddress("%s/%s/%s" % (link, nic.ip, nic.network),
|
796 |
"instance:%s/nic:%d" % (instance.name, idx))
|
797 |
|
798 |
for ip, owners in ips.items(): |
799 |
if len(owners) > 1: |
800 |
result.append("IP address %s is used by multiple owners: %s" %
|
801 |
(ip, utils.CommaJoin(owners))) |
802 |
|
803 |
return result
|
804 |
|
805 |
@locking.ssynchronized(_config_lock, shared=1) |
806 |
def VerifyConfig(self): |
807 |
"""Verify function.
|
808 |
|
809 |
This is just a wrapper over L{_UnlockedVerifyConfig}.
|
810 |
|
811 |
@rtype: list
|
812 |
@return: a list of error messages; a non-empty list signifies
|
813 |
configuration errors
|
814 |
|
815 |
"""
|
816 |
return self._UnlockedVerifyConfig() |
817 |
|
818 |
def _UnlockedSetDiskID(self, disk, node_name): |
819 |
"""Convert the unique ID to the ID needed on the target nodes.
|
820 |
|
821 |
This is used only for drbd, which needs ip/port configuration.
|
822 |
|
823 |
The routine descends down and updates its children also, because
|
824 |
this helps when the only the top device is passed to the remote
|
825 |
node.
|
826 |
|
827 |
This function is for internal use, when the config lock is already held.
|
828 |
|
829 |
"""
|
830 |
if disk.children:
|
831 |
for child in disk.children: |
832 |
self._UnlockedSetDiskID(child, node_name)
|
833 |
|
834 |
if disk.logical_id is None and disk.physical_id is not None: |
835 |
return
|
836 |
if disk.dev_type == constants.LD_DRBD8:
|
837 |
pnode, snode, port, pminor, sminor, secret = disk.logical_id |
838 |
if node_name not in (pnode, snode): |
839 |
raise errors.ConfigurationError("DRBD device not knowing node %s" % |
840 |
node_name) |
841 |
pnode_info = self._UnlockedGetNodeInfo(pnode)
|
842 |
snode_info = self._UnlockedGetNodeInfo(snode)
|
843 |
if pnode_info is None or snode_info is None: |
844 |
raise errors.ConfigurationError("Can't find primary or secondary node" |
845 |
" for %s" % str(disk)) |
846 |
p_data = (pnode_info.secondary_ip, port) |
847 |
s_data = (snode_info.secondary_ip, port) |
848 |
if pnode == node_name:
|
849 |
disk.physical_id = p_data + s_data + (pminor, secret) |
850 |
else: # it must be secondary, we tested above |
851 |
disk.physical_id = s_data + p_data + (sminor, secret) |
852 |
else:
|
853 |
disk.physical_id = disk.logical_id |
854 |
return
|
855 |
|
856 |
@locking.ssynchronized(_config_lock)
|
857 |
def SetDiskID(self, disk, node_name): |
858 |
"""Convert the unique ID to the ID needed on the target nodes.
|
859 |
|
860 |
This is used only for drbd, which needs ip/port configuration.
|
861 |
|
862 |
The routine descends down and updates its children also, because
|
863 |
this helps when the only the top device is passed to the remote
|
864 |
node.
|
865 |
|
866 |
"""
|
867 |
return self._UnlockedSetDiskID(disk, node_name) |
868 |
|
869 |
@locking.ssynchronized(_config_lock)
|
870 |
def AddTcpUdpPort(self, port): |
871 |
"""Adds a new port to the available port pool.
|
872 |
|
873 |
@warning: this method does not "flush" the configuration (via
|
874 |
L{_WriteConfig}); callers should do that themselves once the
|
875 |
configuration is stable
|
876 |
|
877 |
"""
|
878 |
if not isinstance(port, int): |
879 |
raise errors.ProgrammerError("Invalid type passed for port") |
880 |
|
881 |
self._config_data.cluster.tcpudp_port_pool.add(port)
|
882 |
|
883 |
@locking.ssynchronized(_config_lock, shared=1) |
884 |
def GetPortList(self): |
885 |
"""Returns a copy of the current port list.
|
886 |
|
887 |
"""
|
888 |
return self._config_data.cluster.tcpudp_port_pool.copy() |
889 |
|
890 |
@locking.ssynchronized(_config_lock)
|
891 |
def AllocatePort(self): |
892 |
"""Allocate a port.
|
893 |
|
894 |
The port will be taken from the available port pool or from the
|
895 |
default port range (and in this case we increase
|
896 |
highest_used_port).
|
897 |
|
898 |
"""
|
899 |
# If there are TCP/IP ports configured, we use them first.
|
900 |
if self._config_data.cluster.tcpudp_port_pool: |
901 |
port = self._config_data.cluster.tcpudp_port_pool.pop()
|
902 |
else:
|
903 |
port = self._config_data.cluster.highest_used_port + 1 |
904 |
if port >= constants.LAST_DRBD_PORT:
|
905 |
raise errors.ConfigurationError("The highest used port is greater" |
906 |
" than %s. Aborting." %
|
907 |
constants.LAST_DRBD_PORT) |
908 |
self._config_data.cluster.highest_used_port = port
|
909 |
|
910 |
self._WriteConfig()
|
911 |
return port
|
912 |
|
913 |
def _UnlockedComputeDRBDMap(self): |
914 |
"""Compute the used DRBD minor/nodes.
|
915 |
|
916 |
@rtype: (dict, list)
|
917 |
@return: dictionary of node_name: dict of minor: instance_name;
|
918 |
the returned dict will have all the nodes in it (even if with
|
919 |
an empty list), and a list of duplicates; if the duplicates
|
920 |
list is not empty, the configuration is corrupted and its caller
|
921 |
should raise an exception
|
922 |
|
923 |
"""
|
924 |
def _AppendUsedPorts(instance_name, disk, used): |
925 |
duplicates = [] |
926 |
if disk.dev_type == constants.LD_DRBD8 and len(disk.logical_id) >= 5: |
927 |
node_a, node_b, _, minor_a, minor_b = disk.logical_id[:5]
|
928 |
for node, port in ((node_a, minor_a), (node_b, minor_b)): |
929 |
assert node in used, ("Node '%s' of instance '%s' not found" |
930 |
" in node list" % (node, instance_name))
|
931 |
if port in used[node]: |
932 |
duplicates.append((node, port, instance_name, used[node][port])) |
933 |
else:
|
934 |
used[node][port] = instance_name |
935 |
if disk.children:
|
936 |
for child in disk.children: |
937 |
duplicates.extend(_AppendUsedPorts(instance_name, child, used)) |
938 |
return duplicates
|
939 |
|
940 |
duplicates = [] |
941 |
my_dict = dict((node, {}) for node in self._config_data.nodes) |
942 |
for instance in self._config_data.instances.itervalues(): |
943 |
for disk in instance.disks: |
944 |
duplicates.extend(_AppendUsedPorts(instance.name, disk, my_dict)) |
945 |
for (node, minor), instance in self._temporary_drbds.iteritems(): |
946 |
if minor in my_dict[node] and my_dict[node][minor] != instance: |
947 |
duplicates.append((node, minor, instance, my_dict[node][minor])) |
948 |
else:
|
949 |
my_dict[node][minor] = instance |
950 |
return my_dict, duplicates
|
951 |
|
952 |
@locking.ssynchronized(_config_lock)
|
953 |
def ComputeDRBDMap(self): |
954 |
"""Compute the used DRBD minor/nodes.
|
955 |
|
956 |
This is just a wrapper over L{_UnlockedComputeDRBDMap}.
|
957 |
|
958 |
@return: dictionary of node_name: dict of minor: instance_name;
|
959 |
the returned dict will have all the nodes in it (even if with
|
960 |
an empty list).
|
961 |
|
962 |
"""
|
963 |
d_map, duplicates = self._UnlockedComputeDRBDMap()
|
964 |
if duplicates:
|
965 |
raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" % |
966 |
str(duplicates))
|
967 |
return d_map
|
968 |
|
969 |
@locking.ssynchronized(_config_lock)
|
970 |
def AllocateDRBDMinor(self, nodes, instance): |
971 |
"""Allocate a drbd minor.
|
972 |
|
973 |
The free minor will be automatically computed from the existing
|
974 |
devices. A node can be given multiple times in order to allocate
|
975 |
multiple minors. The result is the list of minors, in the same
|
976 |
order as the passed nodes.
|
977 |
|
978 |
@type instance: string
|
979 |
@param instance: the instance for which we allocate minors
|
980 |
|
981 |
"""
|
982 |
assert isinstance(instance, basestring), \ |
983 |
"Invalid argument '%s' passed to AllocateDRBDMinor" % instance
|
984 |
|
985 |
d_map, duplicates = self._UnlockedComputeDRBDMap()
|
986 |
if duplicates:
|
987 |
raise errors.ConfigurationError("Duplicate DRBD ports detected: %s" % |
988 |
str(duplicates))
|
989 |
result = [] |
990 |
for nname in nodes: |
991 |
ndata = d_map[nname] |
992 |
if not ndata: |
993 |
# no minors used, we can start at 0
|
994 |
result.append(0)
|
995 |
ndata[0] = instance
|
996 |
self._temporary_drbds[(nname, 0)] = instance |
997 |
continue
|
998 |
keys = ndata.keys() |
999 |
keys.sort() |
1000 |
ffree = utils.FirstFree(keys) |
1001 |
if ffree is None: |
1002 |
# return the next minor
|
1003 |
# TODO: implement high-limit check
|
1004 |
minor = keys[-1] + 1 |
1005 |
else:
|
1006 |
minor = ffree |
1007 |
# double-check minor against current instances
|
1008 |
assert minor not in d_map[nname], \ |
1009 |
("Attempt to reuse allocated DRBD minor %d on node %s,"
|
1010 |
" already allocated to instance %s" %
|
1011 |
(minor, nname, d_map[nname][minor])) |
1012 |
ndata[minor] = instance |
1013 |
# double-check minor against reservation
|
1014 |
r_key = (nname, minor) |
1015 |
assert r_key not in self._temporary_drbds, \ |
1016 |
("Attempt to reuse reserved DRBD minor %d on node %s,"
|
1017 |
" reserved for instance %s" %
|
1018 |
(minor, nname, self._temporary_drbds[r_key]))
|
1019 |
self._temporary_drbds[r_key] = instance
|
1020 |
result.append(minor) |
1021 |
logging.debug("Request to allocate drbd minors, input: %s, returning %s",
|
1022 |
nodes, result) |
1023 |
return result
|
1024 |
|
1025 |
def _UnlockedReleaseDRBDMinors(self, instance): |
1026 |
"""Release temporary drbd minors allocated for a given instance.
|
1027 |
|
1028 |
@type instance: string
|
1029 |
@param instance: the instance for which temporary minors should be
|
1030 |
released
|
1031 |
|
1032 |
"""
|
1033 |
assert isinstance(instance, basestring), \ |
1034 |
"Invalid argument passed to ReleaseDRBDMinors"
|
1035 |
for key, name in self._temporary_drbds.items(): |
1036 |
if name == instance:
|
1037 |
del self._temporary_drbds[key] |
1038 |
|
1039 |
@locking.ssynchronized(_config_lock)
|
1040 |
def ReleaseDRBDMinors(self, instance): |
1041 |
"""Release temporary drbd minors allocated for a given instance.
|
1042 |
|
1043 |
This should be called on the error paths, on the success paths
|
1044 |
it's automatically called by the ConfigWriter add and update
|
1045 |
functions.
|
1046 |
|
1047 |
This function is just a wrapper over L{_UnlockedReleaseDRBDMinors}.
|
1048 |
|
1049 |
@type instance: string
|
1050 |
@param instance: the instance for which temporary minors should be
|
1051 |
released
|
1052 |
|
1053 |
"""
|
1054 |
self._UnlockedReleaseDRBDMinors(instance)
|
1055 |
|
1056 |
@locking.ssynchronized(_config_lock, shared=1) |
1057 |
def GetConfigVersion(self): |
1058 |
"""Get the configuration version.
|
1059 |
|
1060 |
@return: Config version
|
1061 |
|
1062 |
"""
|
1063 |
return self._config_data.version |
1064 |
|
1065 |
@locking.ssynchronized(_config_lock, shared=1) |
1066 |
def GetClusterName(self): |
1067 |
"""Get cluster name.
|
1068 |
|
1069 |
@return: Cluster name
|
1070 |
|
1071 |
"""
|
1072 |
return self._config_data.cluster.cluster_name |
1073 |
|
1074 |
@locking.ssynchronized(_config_lock, shared=1) |
1075 |
def GetMasterNode(self): |
1076 |
"""Get the hostname of the master node for this cluster.
|
1077 |
|
1078 |
@return: Master hostname
|
1079 |
|
1080 |
"""
|
1081 |
return self._config_data.cluster.master_node |
1082 |
|
1083 |
@locking.ssynchronized(_config_lock, shared=1) |
1084 |
def GetMasterIP(self): |
1085 |
"""Get the IP of the master node for this cluster.
|
1086 |
|
1087 |
@return: Master IP
|
1088 |
|
1089 |
"""
|
1090 |
return self._config_data.cluster.master_ip |
1091 |
|
1092 |
@locking.ssynchronized(_config_lock, shared=1) |
1093 |
def GetMasterNetdev(self): |
1094 |
"""Get the master network device for this cluster.
|
1095 |
|
1096 |
"""
|
1097 |
return self._config_data.cluster.master_netdev |
1098 |
|
1099 |
@locking.ssynchronized(_config_lock, shared=1) |
1100 |
def GetMasterNetmask(self): |
1101 |
"""Get the netmask of the master node for this cluster.
|
1102 |
|
1103 |
"""
|
1104 |
return self._config_data.cluster.master_netmask |
1105 |
|
1106 |
@locking.ssynchronized(_config_lock, shared=1) |
1107 |
def GetUseExternalMipScript(self): |
1108 |
"""Get flag representing whether to use the external master IP setup script.
|
1109 |
|
1110 |
"""
|
1111 |
return self._config_data.cluster.use_external_mip_script |
1112 |
|
1113 |
@locking.ssynchronized(_config_lock, shared=1) |
1114 |
def GetFileStorageDir(self): |
1115 |
"""Get the file storage dir for this cluster.
|
1116 |
|
1117 |
"""
|
1118 |
return self._config_data.cluster.file_storage_dir |
1119 |
|
1120 |
@locking.ssynchronized(_config_lock, shared=1) |
1121 |
def GetSharedFileStorageDir(self): |
1122 |
"""Get the shared file storage dir for this cluster.
|
1123 |
|
1124 |
"""
|
1125 |
return self._config_data.cluster.shared_file_storage_dir |
1126 |
|
1127 |
@locking.ssynchronized(_config_lock, shared=1) |
1128 |
def GetHypervisorType(self): |
1129 |
"""Get the hypervisor type for this cluster.
|
1130 |
|
1131 |
"""
|
1132 |
return self._config_data.cluster.enabled_hypervisors[0] |
1133 |
|
1134 |
@locking.ssynchronized(_config_lock, shared=1) |
1135 |
def GetHostKey(self): |
1136 |
"""Return the rsa hostkey from the config.
|
1137 |
|
1138 |
@rtype: string
|
1139 |
@return: the rsa hostkey
|
1140 |
|
1141 |
"""
|
1142 |
return self._config_data.cluster.rsahostkeypub |
1143 |
|
1144 |
@locking.ssynchronized(_config_lock, shared=1) |
1145 |
def GetDefaultIAllocator(self): |
1146 |
"""Get the default instance allocator for this cluster.
|
1147 |
|
1148 |
"""
|
1149 |
return self._config_data.cluster.default_iallocator |
1150 |
|
1151 |
@locking.ssynchronized(_config_lock, shared=1) |
1152 |
def GetPrimaryIPFamily(self): |
1153 |
"""Get cluster primary ip family.
|
1154 |
|
1155 |
@return: primary ip family
|
1156 |
|
1157 |
"""
|
1158 |
return self._config_data.cluster.primary_ip_family |
1159 |
|
1160 |
@locking.ssynchronized(_config_lock, shared=1) |
1161 |
def GetMasterNetworkParameters(self): |
1162 |
"""Get network parameters of the master node.
|
1163 |
|
1164 |
@rtype: L{object.MasterNetworkParameters}
|
1165 |
@return: network parameters of the master node
|
1166 |
|
1167 |
"""
|
1168 |
cluster = self._config_data.cluster
|
1169 |
result = objects.MasterNetworkParameters( |
1170 |
name=cluster.master_node, ip=cluster.master_ip, |
1171 |
netmask=cluster.master_netmask, netdev=cluster.master_netdev, |
1172 |
ip_family=cluster.primary_ip_family) |
1173 |
|
1174 |
return result
|
1175 |
|
1176 |
@locking.ssynchronized(_config_lock)
|
1177 |
def AddNodeGroup(self, group, ec_id, check_uuid=True): |
1178 |
"""Add a node group to the configuration.
|
1179 |
|
1180 |
This method calls group.UpgradeConfig() to fill any missing attributes
|
1181 |
according to their default values.
|
1182 |
|
1183 |
@type group: L{objects.NodeGroup}
|
1184 |
@param group: the NodeGroup object to add
|
1185 |
@type ec_id: string
|
1186 |
@param ec_id: unique id for the job to use when creating a missing UUID
|
1187 |
@type check_uuid: bool
|
1188 |
@param check_uuid: add an UUID to the group if it doesn't have one or, if
|
1189 |
it does, ensure that it does not exist in the
|
1190 |
configuration already
|
1191 |
|
1192 |
"""
|
1193 |
self._UnlockedAddNodeGroup(group, ec_id, check_uuid)
|
1194 |
self._WriteConfig()
|
1195 |
|
1196 |
def _UnlockedAddNodeGroup(self, group, ec_id, check_uuid): |
1197 |
"""Add a node group to the configuration.
|
1198 |
|
1199 |
"""
|
1200 |
logging.info("Adding node group %s to configuration", group.name)
|
1201 |
|
1202 |
# Some code might need to add a node group with a pre-populated UUID
|
1203 |
# generated with ConfigWriter.GenerateUniqueID(). We allow them to bypass
|
1204 |
# the "does this UUID" exist already check.
|
1205 |
if check_uuid:
|
1206 |
self._EnsureUUID(group, ec_id)
|
1207 |
|
1208 |
try:
|
1209 |
existing_uuid = self._UnlockedLookupNodeGroup(group.name)
|
1210 |
except errors.OpPrereqError:
|
1211 |
pass
|
1212 |
else:
|
1213 |
raise errors.OpPrereqError("Desired group name '%s' already exists as a" |
1214 |
" node group (UUID: %s)" %
|
1215 |
(group.name, existing_uuid), |
1216 |
errors.ECODE_EXISTS) |
1217 |
|
1218 |
group.serial_no = 1
|
1219 |
group.ctime = group.mtime = time.time() |
1220 |
group.UpgradeConfig() |
1221 |
|
1222 |
self._config_data.nodegroups[group.uuid] = group
|
1223 |
self._config_data.cluster.serial_no += 1 |
1224 |
|
1225 |
@locking.ssynchronized(_config_lock)
|
1226 |
def RemoveNodeGroup(self, group_uuid): |
1227 |
"""Remove a node group from the configuration.
|
1228 |
|
1229 |
@type group_uuid: string
|
1230 |
@param group_uuid: the UUID of the node group to remove
|
1231 |
|
1232 |
"""
|
1233 |
logging.info("Removing node group %s from configuration", group_uuid)
|
1234 |
|
1235 |
if group_uuid not in self._config_data.nodegroups: |
1236 |
raise errors.ConfigurationError("Unknown node group '%s'" % group_uuid) |
1237 |
|
1238 |
assert len(self._config_data.nodegroups) != 1, \ |
1239 |
"Group '%s' is the only group, cannot be removed" % group_uuid
|
1240 |
|
1241 |
del self._config_data.nodegroups[group_uuid] |
1242 |
self._config_data.cluster.serial_no += 1 |
1243 |
self._WriteConfig()
|
1244 |
|
1245 |
def _UnlockedLookupNodeGroup(self, target): |
1246 |
"""Lookup a node group's UUID.
|
1247 |
|
1248 |
@type target: string or None
|
1249 |
@param target: group name or UUID or None to look for the default
|
1250 |
@rtype: string
|
1251 |
@return: nodegroup UUID
|
1252 |
@raises errors.OpPrereqError: when the target group cannot be found
|
1253 |
|
1254 |
"""
|
1255 |
if target is None: |
1256 |
if len(self._config_data.nodegroups) != 1: |
1257 |
raise errors.OpPrereqError("More than one node group exists. Target" |
1258 |
" group must be specified explicitly.")
|
1259 |
else:
|
1260 |
return self._config_data.nodegroups.keys()[0] |
1261 |
if target in self._config_data.nodegroups: |
1262 |
return target
|
1263 |
for nodegroup in self._config_data.nodegroups.values(): |
1264 |
if nodegroup.name == target:
|
1265 |
return nodegroup.uuid
|
1266 |
raise errors.OpPrereqError("Node group '%s' not found" % target, |
1267 |
errors.ECODE_NOENT) |
1268 |
|
1269 |
@locking.ssynchronized(_config_lock, shared=1) |
1270 |
def LookupNodeGroup(self, target): |
1271 |
"""Lookup a node group's UUID.
|
1272 |
|
1273 |
This function is just a wrapper over L{_UnlockedLookupNodeGroup}.
|
1274 |
|
1275 |
@type target: string or None
|
1276 |
@param target: group name or UUID or None to look for the default
|
1277 |
@rtype: string
|
1278 |
@return: nodegroup UUID
|
1279 |
|
1280 |
"""
|
1281 |
return self._UnlockedLookupNodeGroup(target) |
1282 |
|
1283 |
def _UnlockedGetNodeGroup(self, uuid): |
1284 |
"""Lookup a node group.
|
1285 |
|
1286 |
@type uuid: string
|
1287 |
@param uuid: group UUID
|
1288 |
@rtype: L{objects.NodeGroup} or None
|
1289 |
@return: nodegroup object, or None if not found
|
1290 |
|
1291 |
"""
|
1292 |
if uuid not in self._config_data.nodegroups: |
1293 |
return None |
1294 |
|
1295 |
return self._config_data.nodegroups[uuid] |
1296 |
|
1297 |
@locking.ssynchronized(_config_lock, shared=1) |
1298 |
def GetNodeGroup(self, uuid): |
1299 |
"""Lookup a node group.
|
1300 |
|
1301 |
@type uuid: string
|
1302 |
@param uuid: group UUID
|
1303 |
@rtype: L{objects.NodeGroup} or None
|
1304 |
@return: nodegroup object, or None if not found
|
1305 |
|
1306 |
"""
|
1307 |
return self._UnlockedGetNodeGroup(uuid) |
1308 |
|
1309 |
@locking.ssynchronized(_config_lock, shared=1) |
1310 |
def GetAllNodeGroupsInfo(self): |
1311 |
"""Get the configuration of all node groups.
|
1312 |
|
1313 |
"""
|
1314 |
return dict(self._config_data.nodegroups) |
1315 |
|
1316 |
@locking.ssynchronized(_config_lock, shared=1) |
1317 |
def GetNodeGroupList(self): |
1318 |
"""Get a list of node groups.
|
1319 |
|
1320 |
"""
|
1321 |
return self._config_data.nodegroups.keys() |
1322 |
|
1323 |
@locking.ssynchronized(_config_lock, shared=1) |
1324 |
def GetNodeGroupMembersByNodes(self, nodes): |
1325 |
"""Get nodes which are member in the same nodegroups as the given nodes.
|
1326 |
|
1327 |
"""
|
1328 |
ngfn = lambda node_name: self._UnlockedGetNodeInfo(node_name).group |
1329 |
return frozenset(member_name |
1330 |
for node_name in nodes |
1331 |
for member_name in |
1332 |
self._UnlockedGetNodeGroup(ngfn(node_name)).members)
|
1333 |
|
1334 |
@locking.ssynchronized(_config_lock, shared=1) |
1335 |
def GetMultiNodeGroupInfo(self, group_uuids): |
1336 |
"""Get the configuration of multiple node groups.
|
1337 |
|
1338 |
@param group_uuids: List of node group UUIDs
|
1339 |
@rtype: list
|
1340 |
@return: List of tuples of (group_uuid, group_info)
|
1341 |
|
1342 |
"""
|
1343 |
return [(uuid, self._UnlockedGetNodeGroup(uuid)) for uuid in group_uuids] |
1344 |
|
1345 |
@locking.ssynchronized(_config_lock)
|
1346 |
def AddInstance(self, instance, ec_id): |
1347 |
"""Add an instance to the config.
|
1348 |
|
1349 |
This should be used after creating a new instance.
|
1350 |
|
1351 |
@type instance: L{objects.Instance}
|
1352 |
@param instance: the instance object
|
1353 |
|
1354 |
"""
|
1355 |
if not isinstance(instance, objects.Instance): |
1356 |
raise errors.ProgrammerError("Invalid type passed to AddInstance") |
1357 |
|
1358 |
if instance.disk_template != constants.DT_DISKLESS:
|
1359 |
all_lvs = instance.MapLVsByNode() |
1360 |
logging.info("Instance '%s' DISK_LAYOUT: %s", instance.name, all_lvs)
|
1361 |
|
1362 |
all_macs = self._AllMACs()
|
1363 |
for nic in instance.nics: |
1364 |
if nic.mac in all_macs: |
1365 |
raise errors.ConfigurationError("Cannot add instance %s:" |
1366 |
" MAC address '%s' already in use." %
|
1367 |
(instance.name, nic.mac)) |
1368 |
|
1369 |
self._EnsureUUID(instance, ec_id)
|
1370 |
|
1371 |
instance.serial_no = 1
|
1372 |
instance.ctime = instance.mtime = time.time() |
1373 |
self._config_data.instances[instance.name] = instance
|
1374 |
self._config_data.cluster.serial_no += 1 |
1375 |
self._UnlockedReleaseDRBDMinors(instance.name)
|
1376 |
self._UnlockedCommitTemporaryIps(ec_id)
|
1377 |
self._WriteConfig()
|
1378 |
|
1379 |
def _EnsureUUID(self, item, ec_id): |
1380 |
"""Ensures a given object has a valid UUID.
|
1381 |
|
1382 |
@param item: the instance or node to be checked
|
1383 |
@param ec_id: the execution context id for the uuid reservation
|
1384 |
|
1385 |
"""
|
1386 |
if not item.uuid: |
1387 |
item.uuid = self._GenerateUniqueID(ec_id)
|
1388 |
elif item.uuid in self._AllIDs(include_temporary=True): |
1389 |
raise errors.ConfigurationError("Cannot add '%s': UUID %s already" |
1390 |
" in use" % (item.name, item.uuid))
|
1391 |
|
1392 |
def _SetInstanceStatus(self, instance_name, status): |
1393 |
"""Set the instance's status to a given value.
|
1394 |
|
1395 |
"""
|
1396 |
assert status in constants.ADMINST_ALL, \ |
1397 |
"Invalid status '%s' passed to SetInstanceStatus" % (status,)
|
1398 |
|
1399 |
if instance_name not in self._config_data.instances: |
1400 |
raise errors.ConfigurationError("Unknown instance '%s'" % |
1401 |
instance_name) |
1402 |
instance = self._config_data.instances[instance_name]
|
1403 |
if instance.admin_state != status:
|
1404 |
instance.admin_state = status |
1405 |
instance.serial_no += 1
|
1406 |
instance.mtime = time.time() |
1407 |
self._WriteConfig()
|
1408 |
|
1409 |
@locking.ssynchronized(_config_lock)
|
1410 |
def MarkInstanceUp(self, instance_name): |
1411 |
"""Mark the instance status to up in the config.
|
1412 |
|
1413 |
"""
|
1414 |
self._SetInstanceStatus(instance_name, constants.ADMINST_UP)
|
1415 |
|
1416 |
@locking.ssynchronized(_config_lock)
|
1417 |
def MarkInstanceOffline(self, instance_name): |
1418 |
"""Mark the instance status to down in the config.
|
1419 |
|
1420 |
"""
|
1421 |
self._SetInstanceStatus(instance_name, constants.ADMINST_OFFLINE)
|
1422 |
|
1423 |
@locking.ssynchronized(_config_lock)
|
1424 |
def RemoveInstance(self, instance_name): |
1425 |
"""Remove the instance from the configuration.
|
1426 |
|
1427 |
"""
|
1428 |
if instance_name not in self._config_data.instances: |
1429 |
raise errors.ConfigurationError("Unknown instance '%s'" % instance_name) |
1430 |
|
1431 |
# If a network port has been allocated to the instance,
|
1432 |
# return it to the pool of free ports.
|
1433 |
inst = self._config_data.instances[instance_name]
|
1434 |
network_port = getattr(inst, "network_port", None) |
1435 |
if network_port is not None: |
1436 |
self._config_data.cluster.tcpudp_port_pool.add(network_port)
|
1437 |
|
1438 |
instance = self._UnlockedGetInstanceInfo(instance_name)
|
1439 |
|
1440 |
for nic in instance.nics: |
1441 |
if nic.network is not None and nic.ip is not None: |
1442 |
net_uuid = self._UnlockedLookupNetwork(nic.network)
|
1443 |
if net_uuid:
|
1444 |
# Return all IP addresses to the respective address pools
|
1445 |
self._UnlockedCommitIp('release', net_uuid, nic.ip) |
1446 |
|
1447 |
|
1448 |
del self._config_data.instances[instance_name] |
1449 |
self._config_data.cluster.serial_no += 1 |
1450 |
self._WriteConfig()
|
1451 |
|
1452 |
@locking.ssynchronized(_config_lock)
|
1453 |
def RenameInstance(self, old_name, new_name): |
1454 |
"""Rename an instance.
|
1455 |
|
1456 |
This needs to be done in ConfigWriter and not by RemoveInstance
|
1457 |
combined with AddInstance as only we can guarantee an atomic
|
1458 |
rename.
|
1459 |
|
1460 |
"""
|
1461 |
if old_name not in self._config_data.instances: |
1462 |
raise errors.ConfigurationError("Unknown instance '%s'" % old_name) |
1463 |
|
1464 |
# Operate on a copy to not loose instance object in case of a failure
|
1465 |
inst = self._config_data.instances[old_name].Copy()
|
1466 |
inst.name = new_name |
1467 |
|
1468 |
for (idx, disk) in enumerate(inst.disks): |
1469 |
if disk.dev_type == constants.LD_FILE:
|
1470 |
# rename the file paths in logical and physical id
|
1471 |
file_storage_dir = os.path.dirname(os.path.dirname(disk.logical_id[1]))
|
1472 |
disk.logical_id = (disk.logical_id[0],
|
1473 |
utils.PathJoin(file_storage_dir, inst.name, |
1474 |
"disk%s" % idx))
|
1475 |
disk.physical_id = disk.logical_id |
1476 |
|
1477 |
# Actually replace instance object
|
1478 |
del self._config_data.instances[old_name] |
1479 |
self._config_data.instances[inst.name] = inst
|
1480 |
|
1481 |
# Force update of ssconf files
|
1482 |
self._config_data.cluster.serial_no += 1 |
1483 |
|
1484 |
self._WriteConfig()
|
1485 |
|
1486 |
@locking.ssynchronized(_config_lock)
|
1487 |
def MarkInstanceDown(self, instance_name): |
1488 |
"""Mark the status of an instance to down in the configuration.
|
1489 |
|
1490 |
"""
|
1491 |
self._SetInstanceStatus(instance_name, constants.ADMINST_DOWN)
|
1492 |
|
1493 |
def _UnlockedGetInstanceList(self): |
1494 |
"""Get the list of instances.
|
1495 |
|
1496 |
This function is for internal use, when the config lock is already held.
|
1497 |
|
1498 |
"""
|
1499 |
return self._config_data.instances.keys() |
1500 |
|
1501 |
@locking.ssynchronized(_config_lock, shared=1) |
1502 |
def GetInstanceList(self): |
1503 |
"""Get the list of instances.
|
1504 |
|
1505 |
@return: array of instances, ex. ['instance2.example.com',
|
1506 |
'instance1.example.com']
|
1507 |
|
1508 |
"""
|
1509 |
return self._UnlockedGetInstanceList() |
1510 |
|
1511 |
def ExpandInstanceName(self, short_name): |
1512 |
"""Attempt to expand an incomplete instance name.
|
1513 |
|
1514 |
"""
|
1515 |
# Locking is done in L{ConfigWriter.GetInstanceList}
|
1516 |
return _MatchNameComponentIgnoreCase(short_name, self.GetInstanceList()) |
1517 |
|
1518 |
def _UnlockedGetInstanceInfo(self, instance_name): |
1519 |
"""Returns information about an instance.
|
1520 |
|
1521 |
This function is for internal use, when the config lock is already held.
|
1522 |
|
1523 |
"""
|
1524 |
if instance_name not in self._config_data.instances: |
1525 |
return None |
1526 |
|
1527 |
return self._config_data.instances[instance_name] |
1528 |
|
1529 |
@locking.ssynchronized(_config_lock, shared=1) |
1530 |
def GetInstanceInfo(self, instance_name): |
1531 |
"""Returns information about an instance.
|
1532 |
|
1533 |
It takes the information from the configuration file. Other information of
|
1534 |
an instance are taken from the live systems.
|
1535 |
|
1536 |
@param instance_name: name of the instance, e.g.
|
1537 |
I{instance1.example.com}
|
1538 |
|
1539 |
@rtype: L{objects.Instance}
|
1540 |
@return: the instance object
|
1541 |
|
1542 |
"""
|
1543 |
return self._UnlockedGetInstanceInfo(instance_name) |
1544 |
|
1545 |
@locking.ssynchronized(_config_lock, shared=1) |
1546 |
def GetInstanceNodeGroups(self, instance_name, primary_only=False): |
1547 |
"""Returns set of node group UUIDs for instance's nodes.
|
1548 |
|
1549 |
@rtype: frozenset
|
1550 |
|
1551 |
"""
|
1552 |
instance = self._UnlockedGetInstanceInfo(instance_name)
|
1553 |
if not instance: |
1554 |
raise errors.ConfigurationError("Unknown instance '%s'" % instance_name) |
1555 |
|
1556 |
if primary_only:
|
1557 |
nodes = [instance.primary_node] |
1558 |
else:
|
1559 |
nodes = instance.all_nodes |
1560 |
|
1561 |
return frozenset(self._UnlockedGetNodeInfo(node_name).group |
1562 |
for node_name in nodes) |
1563 |
|
1564 |
@locking.ssynchronized(_config_lock, shared=1) |
1565 |
def GetMultiInstanceInfo(self, instances): |
1566 |
"""Get the configuration of multiple instances.
|
1567 |
|
1568 |
@param instances: list of instance names
|
1569 |
@rtype: list
|
1570 |
@return: list of tuples (instance, instance_info), where
|
1571 |
instance_info is what would GetInstanceInfo return for the
|
1572 |
node, while keeping the original order
|
1573 |
|
1574 |
"""
|
1575 |
return [(name, self._UnlockedGetInstanceInfo(name)) for name in instances] |
1576 |
|
1577 |
@locking.ssynchronized(_config_lock, shared=1) |
1578 |
def GetAllInstancesInfo(self): |
1579 |
"""Get the configuration of all instances.
|
1580 |
|
1581 |
@rtype: dict
|
1582 |
@return: dict of (instance, instance_info), where instance_info is what
|
1583 |
would GetInstanceInfo return for the node
|
1584 |
|
1585 |
"""
|
1586 |
my_dict = dict([(instance, self._UnlockedGetInstanceInfo(instance)) |
1587 |
for instance in self._UnlockedGetInstanceList()]) |
1588 |
return my_dict
|
1589 |
|
1590 |
@locking.ssynchronized(_config_lock, shared=1) |
1591 |
def GetInstancesInfoByFilter(self, filter_fn): |
1592 |
"""Get instance configuration with a filter.
|
1593 |
|
1594 |
@type filter_fn: callable
|
1595 |
@param filter_fn: Filter function receiving instance object as parameter,
|
1596 |
returning boolean. Important: this function is called while the
|
1597 |
configuration locks is held. It must not do any complex work or call
|
1598 |
functions potentially leading to a deadlock. Ideally it doesn't call any
|
1599 |
other functions and just compares instance attributes.
|
1600 |
|
1601 |
"""
|
1602 |
return dict((name, inst) |
1603 |
for (name, inst) in self._config_data.instances.items() |
1604 |
if filter_fn(inst))
|
1605 |
|
1606 |
@locking.ssynchronized(_config_lock)
|
1607 |
def AddNode(self, node, ec_id): |
1608 |
"""Add a node to the configuration.
|
1609 |
|
1610 |
@type node: L{objects.Node}
|
1611 |
@param node: a Node instance
|
1612 |
|
1613 |
"""
|
1614 |
logging.info("Adding node %s to configuration", node.name)
|
1615 |
|
1616 |
self._EnsureUUID(node, ec_id)
|
1617 |
|
1618 |
node.serial_no = 1
|
1619 |
node.ctime = node.mtime = time.time() |
1620 |
self._UnlockedAddNodeToGroup(node.name, node.group)
|
1621 |
self._config_data.nodes[node.name] = node
|
1622 |
self._config_data.cluster.serial_no += 1 |
1623 |
self._WriteConfig()
|
1624 |
|
1625 |
@locking.ssynchronized(_config_lock)
|
1626 |
def RemoveNode(self, node_name): |
1627 |
"""Remove a node from the configuration.
|
1628 |
|
1629 |
"""
|
1630 |
logging.info("Removing node %s from configuration", node_name)
|
1631 |
|
1632 |
if node_name not in self._config_data.nodes: |
1633 |
raise errors.ConfigurationError("Unknown node '%s'" % node_name) |
1634 |
|
1635 |
self._UnlockedRemoveNodeFromGroup(self._config_data.nodes[node_name]) |
1636 |
del self._config_data.nodes[node_name] |
1637 |
self._config_data.cluster.serial_no += 1 |
1638 |
self._WriteConfig()
|
1639 |
|
1640 |
def ExpandNodeName(self, short_name): |
1641 |
"""Attempt to expand an incomplete node name.
|
1642 |
|
1643 |
"""
|
1644 |
# Locking is done in L{ConfigWriter.GetNodeList}
|
1645 |
return _MatchNameComponentIgnoreCase(short_name, self.GetNodeList()) |
1646 |
|
1647 |
def _UnlockedGetNodeInfo(self, node_name): |
1648 |
"""Get the configuration of a node, as stored in the config.
|
1649 |
|
1650 |
This function is for internal use, when the config lock is already
|
1651 |
held.
|
1652 |
|
1653 |
@param node_name: the node name, e.g. I{node1.example.com}
|
1654 |
|
1655 |
@rtype: L{objects.Node}
|
1656 |
@return: the node object
|
1657 |
|
1658 |
"""
|
1659 |
if node_name not in self._config_data.nodes: |
1660 |
return None |
1661 |
|
1662 |
return self._config_data.nodes[node_name] |
1663 |
|
1664 |
@locking.ssynchronized(_config_lock, shared=1) |
1665 |
def GetNodeInfo(self, node_name): |
1666 |
"""Get the configuration of a node, as stored in the config.
|
1667 |
|
1668 |
This is just a locked wrapper over L{_UnlockedGetNodeInfo}.
|
1669 |
|
1670 |
@param node_name: the node name, e.g. I{node1.example.com}
|
1671 |
|
1672 |
@rtype: L{objects.Node}
|
1673 |
@return: the node object
|
1674 |
|
1675 |
"""
|
1676 |
return self._UnlockedGetNodeInfo(node_name) |
1677 |
|
1678 |
@locking.ssynchronized(_config_lock, shared=1) |
1679 |
def GetNodeInstances(self, node_name): |
1680 |
"""Get the instances of a node, as stored in the config.
|
1681 |
|
1682 |
@param node_name: the node name, e.g. I{node1.example.com}
|
1683 |
|
1684 |
@rtype: (list, list)
|
1685 |
@return: a tuple with two lists: the primary and the secondary instances
|
1686 |
|
1687 |
"""
|
1688 |
pri = [] |
1689 |
sec = [] |
1690 |
for inst in self._config_data.instances.values(): |
1691 |
if inst.primary_node == node_name:
|
1692 |
pri.append(inst.name) |
1693 |
if node_name in inst.secondary_nodes: |
1694 |
sec.append(inst.name) |
1695 |
return (pri, sec)
|
1696 |
|
1697 |
@locking.ssynchronized(_config_lock, shared=1) |
1698 |
def GetNodeGroupInstances(self, uuid, primary_only=False): |
1699 |
"""Get the instances of a node group.
|
1700 |
|
1701 |
@param uuid: Node group UUID
|
1702 |
@param primary_only: Whether to only consider primary nodes
|
1703 |
@rtype: frozenset
|
1704 |
@return: List of instance names in node group
|
1705 |
|
1706 |
"""
|
1707 |
if primary_only:
|
1708 |
nodes_fn = lambda inst: [inst.primary_node]
|
1709 |
else:
|
1710 |
nodes_fn = lambda inst: inst.all_nodes
|
1711 |
|
1712 |
return frozenset(inst.name |
1713 |
for inst in self._config_data.instances.values() |
1714 |
for node_name in nodes_fn(inst) |
1715 |
if self._UnlockedGetNodeInfo(node_name).group == uuid) |
1716 |
|
1717 |
def _UnlockedGetNodeList(self): |
1718 |
"""Return the list of nodes which are in the configuration.
|
1719 |
|
1720 |
This function is for internal use, when the config lock is already
|
1721 |
held.
|
1722 |
|
1723 |
@rtype: list
|
1724 |
|
1725 |
"""
|
1726 |
return self._config_data.nodes.keys() |
1727 |
|
1728 |
@locking.ssynchronized(_config_lock, shared=1) |
1729 |
def GetNodeList(self): |
1730 |
"""Return the list of nodes which are in the configuration.
|
1731 |
|
1732 |
"""
|
1733 |
return self._UnlockedGetNodeList() |
1734 |
|
1735 |
def _UnlockedGetOnlineNodeList(self): |
1736 |
"""Return the list of nodes which are online.
|
1737 |
|
1738 |
"""
|
1739 |
all_nodes = [self._UnlockedGetNodeInfo(node)
|
1740 |
for node in self._UnlockedGetNodeList()] |
1741 |
return [node.name for node in all_nodes if not node.offline] |
1742 |
|
1743 |
@locking.ssynchronized(_config_lock, shared=1) |
1744 |
def GetOnlineNodeList(self): |
1745 |
"""Return the list of nodes which are online.
|
1746 |
|
1747 |
"""
|
1748 |
return self._UnlockedGetOnlineNodeList() |
1749 |
|
1750 |
@locking.ssynchronized(_config_lock, shared=1) |
1751 |
def GetVmCapableNodeList(self): |
1752 |
"""Return the list of nodes which are not vm capable.
|
1753 |
|
1754 |
"""
|
1755 |
all_nodes = [self._UnlockedGetNodeInfo(node)
|
1756 |
for node in self._UnlockedGetNodeList()] |
1757 |
return [node.name for node in all_nodes if node.vm_capable] |
1758 |
|
1759 |
@locking.ssynchronized(_config_lock, shared=1) |
1760 |
def GetNonVmCapableNodeList(self): |
1761 |
"""Return the list of nodes which are not vm capable.
|
1762 |
|
1763 |
"""
|
1764 |
all_nodes = [self._UnlockedGetNodeInfo(node)
|
1765 |
for node in self._UnlockedGetNodeList()] |
1766 |
return [node.name for node in all_nodes if not node.vm_capable] |
1767 |
|
1768 |
@locking.ssynchronized(_config_lock, shared=1) |
1769 |
def GetMultiNodeInfo(self, nodes): |
1770 |
"""Get the configuration of multiple nodes.
|
1771 |
|
1772 |
@param nodes: list of node names
|
1773 |
@rtype: list
|
1774 |
@return: list of tuples of (node, node_info), where node_info is
|
1775 |
what would GetNodeInfo return for the node, in the original
|
1776 |
order
|
1777 |
|
1778 |
"""
|
1779 |
return [(name, self._UnlockedGetNodeInfo(name)) for name in nodes] |
1780 |
|
1781 |
@locking.ssynchronized(_config_lock, shared=1) |
1782 |
def GetAllNodesInfo(self): |
1783 |
"""Get the configuration of all nodes.
|
1784 |
|
1785 |
@rtype: dict
|
1786 |
@return: dict of (node, node_info), where node_info is what
|
1787 |
would GetNodeInfo return for the node
|
1788 |
|
1789 |
"""
|
1790 |
return self._UnlockedGetAllNodesInfo() |
1791 |
|
1792 |
def _UnlockedGetAllNodesInfo(self): |
1793 |
"""Gets configuration of all nodes.
|
1794 |
|
1795 |
@note: See L{GetAllNodesInfo}
|
1796 |
|
1797 |
"""
|
1798 |
return dict([(node, self._UnlockedGetNodeInfo(node)) |
1799 |
for node in self._UnlockedGetNodeList()]) |
1800 |
|
1801 |
@locking.ssynchronized(_config_lock, shared=1) |
1802 |
def GetNodeGroupsFromNodes(self, nodes): |
1803 |
"""Returns groups for a list of nodes.
|
1804 |
|
1805 |
@type nodes: list of string
|
1806 |
@param nodes: List of node names
|
1807 |
@rtype: frozenset
|
1808 |
|
1809 |
"""
|
1810 |
return frozenset(self._UnlockedGetNodeInfo(name).group for name in nodes) |
1811 |
|
1812 |
def _UnlockedGetMasterCandidateStats(self, exceptions=None): |
1813 |
"""Get the number of current and maximum desired and possible candidates.
|
1814 |
|
1815 |
@type exceptions: list
|
1816 |
@param exceptions: if passed, list of nodes that should be ignored
|
1817 |
@rtype: tuple
|
1818 |
@return: tuple of (current, desired and possible, possible)
|
1819 |
|
1820 |
"""
|
1821 |
mc_now = mc_should = mc_max = 0
|
1822 |
for node in self._config_data.nodes.values(): |
1823 |
if exceptions and node.name in exceptions: |
1824 |
continue
|
1825 |
if not (node.offline or node.drained) and node.master_capable: |
1826 |
mc_max += 1
|
1827 |
if node.master_candidate:
|
1828 |
mc_now += 1
|
1829 |
mc_should = min(mc_max, self._config_data.cluster.candidate_pool_size) |
1830 |
return (mc_now, mc_should, mc_max)
|
1831 |
|
1832 |
@locking.ssynchronized(_config_lock, shared=1) |
1833 |
def GetMasterCandidateStats(self, exceptions=None): |
1834 |
"""Get the number of current and maximum possible candidates.
|
1835 |
|
1836 |
This is just a wrapper over L{_UnlockedGetMasterCandidateStats}.
|
1837 |
|
1838 |
@type exceptions: list
|
1839 |
@param exceptions: if passed, list of nodes that should be ignored
|
1840 |
@rtype: tuple
|
1841 |
@return: tuple of (current, max)
|
1842 |
|
1843 |
"""
|
1844 |
return self._UnlockedGetMasterCandidateStats(exceptions) |
1845 |
|
1846 |
@locking.ssynchronized(_config_lock)
|
1847 |
def MaintainCandidatePool(self, exceptions): |
1848 |
"""Try to grow the candidate pool to the desired size.
|
1849 |
|
1850 |
@type exceptions: list
|
1851 |
@param exceptions: if passed, list of nodes that should be ignored
|
1852 |
@rtype: list
|
1853 |
@return: list with the adjusted nodes (L{objects.Node} instances)
|
1854 |
|
1855 |
"""
|
1856 |
mc_now, mc_max, _ = self._UnlockedGetMasterCandidateStats(exceptions)
|
1857 |
mod_list = [] |
1858 |
if mc_now < mc_max:
|
1859 |
node_list = self._config_data.nodes.keys()
|
1860 |
random.shuffle(node_list) |
1861 |
for name in node_list: |
1862 |
if mc_now >= mc_max:
|
1863 |
break
|
1864 |
node = self._config_data.nodes[name]
|
1865 |
if (node.master_candidate or node.offline or node.drained or |
1866 |
node.name in exceptions or not node.master_capable): |
1867 |
continue
|
1868 |
mod_list.append(node) |
1869 |
node.master_candidate = True
|
1870 |
node.serial_no += 1
|
1871 |
mc_now += 1
|
1872 |
if mc_now != mc_max:
|
1873 |
# this should not happen
|
1874 |
logging.warning("Warning: MaintainCandidatePool didn't manage to"
|
1875 |
" fill the candidate pool (%d/%d)", mc_now, mc_max)
|
1876 |
if mod_list:
|
1877 |
self._config_data.cluster.serial_no += 1 |
1878 |
self._WriteConfig()
|
1879 |
|
1880 |
return mod_list
|
1881 |
|
1882 |
def _UnlockedAddNodeToGroup(self, node_name, nodegroup_uuid): |
1883 |
"""Add a given node to the specified group.
|
1884 |
|
1885 |
"""
|
1886 |
if nodegroup_uuid not in self._config_data.nodegroups: |
1887 |
# This can happen if a node group gets deleted between its lookup and
|
1888 |
# when we're adding the first node to it, since we don't keep a lock in
|
1889 |
# the meantime. It's ok though, as we'll fail cleanly if the node group
|
1890 |
# is not found anymore.
|
1891 |
raise errors.OpExecError("Unknown node group: %s" % nodegroup_uuid) |
1892 |
if node_name not in self._config_data.nodegroups[nodegroup_uuid].members: |
1893 |
self._config_data.nodegroups[nodegroup_uuid].members.append(node_name)
|
1894 |
|
1895 |
def _UnlockedRemoveNodeFromGroup(self, node): |
1896 |
"""Remove a given node from its group.
|
1897 |
|
1898 |
"""
|
1899 |
nodegroup = node.group |
1900 |
if nodegroup not in self._config_data.nodegroups: |
1901 |
logging.warning("Warning: node '%s' has unknown node group '%s'"
|
1902 |
" (while being removed from it)", node.name, nodegroup)
|
1903 |
nodegroup_obj = self._config_data.nodegroups[nodegroup]
|
1904 |
if node.name not in nodegroup_obj.members: |
1905 |
logging.warning("Warning: node '%s' not a member of its node group '%s'"
|
1906 |
" (while being removed from it)", node.name, nodegroup)
|
1907 |
else:
|
1908 |
nodegroup_obj.members.remove(node.name) |
1909 |
|
1910 |
@locking.ssynchronized(_config_lock)
|
1911 |
def AssignGroupNodes(self, mods): |
1912 |
"""Changes the group of a number of nodes.
|
1913 |
|
1914 |
@type mods: list of tuples; (node name, new group UUID)
|
1915 |
@param mods: Node membership modifications
|
1916 |
|
1917 |
"""
|
1918 |
groups = self._config_data.nodegroups
|
1919 |
nodes = self._config_data.nodes
|
1920 |
|
1921 |
resmod = [] |
1922 |
|
1923 |
# Try to resolve names/UUIDs first
|
1924 |
for (node_name, new_group_uuid) in mods: |
1925 |
try:
|
1926 |
node = nodes[node_name] |
1927 |
except KeyError: |
1928 |
raise errors.ConfigurationError("Unable to find node '%s'" % node_name) |
1929 |
|
1930 |
if node.group == new_group_uuid:
|
1931 |
# Node is being assigned to its current group
|
1932 |
logging.debug("Node '%s' was assigned to its current group (%s)",
|
1933 |
node_name, node.group) |
1934 |
continue
|
1935 |
|
1936 |
# Try to find current group of node
|
1937 |
try:
|
1938 |
old_group = groups[node.group] |
1939 |
except KeyError: |
1940 |
raise errors.ConfigurationError("Unable to find old group '%s'" % |
1941 |
node.group) |
1942 |
|
1943 |
# Try to find new group for node
|
1944 |
try:
|
1945 |
new_group = groups[new_group_uuid] |
1946 |
except KeyError: |
1947 |
raise errors.ConfigurationError("Unable to find new group '%s'" % |
1948 |
new_group_uuid) |
1949 |
|
1950 |
assert node.name in old_group.members, \ |
1951 |
("Inconsistent configuration: node '%s' not listed in members for its"
|
1952 |
" old group '%s'" % (node.name, old_group.uuid))
|
1953 |
assert node.name not in new_group.members, \ |
1954 |
("Inconsistent configuration: node '%s' already listed in members for"
|
1955 |
" its new group '%s'" % (node.name, new_group.uuid))
|
1956 |
|
1957 |
resmod.append((node, old_group, new_group)) |
1958 |
|
1959 |
# Apply changes
|
1960 |
for (node, old_group, new_group) in resmod: |
1961 |
assert node.uuid != new_group.uuid and old_group.uuid != new_group.uuid, \ |
1962 |
"Assigning to current group is not possible"
|
1963 |
|
1964 |
node.group = new_group.uuid |
1965 |
|
1966 |
# Update members of involved groups
|
1967 |
if node.name in old_group.members: |
1968 |
old_group.members.remove(node.name) |
1969 |
if node.name not in new_group.members: |
1970 |
new_group.members.append(node.name) |
1971 |
|
1972 |
# Update timestamps and serials (only once per node/group object)
|
1973 |
now = time.time() |
1974 |
for obj in frozenset(itertools.chain(*resmod)): # pylint: disable=W0142 |
1975 |
obj.serial_no += 1
|
1976 |
obj.mtime = now |
1977 |
|
1978 |
# Force ssconf update
|
1979 |
self._config_data.cluster.serial_no += 1 |
1980 |
|
1981 |
self._WriteConfig()
|
1982 |
|
1983 |
def _BumpSerialNo(self): |
1984 |
"""Bump up the serial number of the config.
|
1985 |
|
1986 |
"""
|
1987 |
self._config_data.serial_no += 1 |
1988 |
self._config_data.mtime = time.time()
|
1989 |
|
1990 |
def _AllUUIDObjects(self): |
1991 |
"""Returns all objects with uuid attributes.
|
1992 |
|
1993 |
"""
|
1994 |
return (self._config_data.instances.values() + |
1995 |
self._config_data.nodes.values() +
|
1996 |
self._config_data.nodegroups.values() +
|
1997 |
[self._config_data.cluster])
|
1998 |
|
1999 |
def _OpenConfig(self, accept_foreign): |
2000 |
"""Read the config data from disk.
|
2001 |
|
2002 |
"""
|
2003 |
raw_data = utils.ReadFile(self._cfg_file)
|
2004 |
|
2005 |
try:
|
2006 |
data = objects.ConfigData.FromDict(serializer.Load(raw_data)) |
2007 |
except Exception, err: |
2008 |
raise errors.ConfigurationError(err)
|
2009 |
|
2010 |
# Make sure the configuration has the right version
|
2011 |
_ValidateConfig(data) |
2012 |
|
2013 |
if (not hasattr(data, "cluster") or |
2014 |
not hasattr(data.cluster, "rsahostkeypub")): |
2015 |
raise errors.ConfigurationError("Incomplete configuration" |
2016 |
" (missing cluster.rsahostkeypub)")
|
2017 |
|
2018 |
if data.cluster.master_node != self._my_hostname and not accept_foreign: |
2019 |
msg = ("The configuration denotes node %s as master, while my"
|
2020 |
" hostname is %s; opening a foreign configuration is only"
|
2021 |
" possible in accept_foreign mode" %
|
2022 |
(data.cluster.master_node, self._my_hostname))
|
2023 |
raise errors.ConfigurationError(msg)
|
2024 |
|
2025 |
# Upgrade configuration if needed
|
2026 |
data.UpgradeConfig() |
2027 |
|
2028 |
self._config_data = data
|
2029 |
# reset the last serial as -1 so that the next write will cause
|
2030 |
# ssconf update
|
2031 |
self._last_cluster_serial = -1 |
2032 |
|
2033 |
# And finally run our (custom) config upgrade sequence
|
2034 |
self._UpgradeConfig()
|
2035 |
|
2036 |
self._cfg_id = utils.GetFileID(path=self._cfg_file) |
2037 |
|
2038 |
def _UpgradeConfig(self): |
2039 |
"""Run upgrade steps that cannot be done purely in the objects.
|
2040 |
|
2041 |
This is because some data elements need uniqueness across the
|
2042 |
whole configuration, etc.
|
2043 |
|
2044 |
@warning: this function will call L{_WriteConfig()}, but also
|
2045 |
L{DropECReservations} so it needs to be called only from a
|
2046 |
"safe" place (the constructor). If one wanted to call it with
|
2047 |
the lock held, a DropECReservationUnlocked would need to be
|
2048 |
created first, to avoid causing deadlock.
|
2049 |
|
2050 |
"""
|
2051 |
modified = False
|
2052 |
for item in self._AllUUIDObjects(): |
2053 |
if item.uuid is None: |
2054 |
item.uuid = self._GenerateUniqueID(_UPGRADE_CONFIG_JID)
|
2055 |
modified = True
|
2056 |
if not self._config_data.nodegroups: |
2057 |
default_nodegroup_name = constants.INITIAL_NODE_GROUP_NAME |
2058 |
default_nodegroup = objects.NodeGroup(name=default_nodegroup_name, |
2059 |
members=[]) |
2060 |
self._UnlockedAddNodeGroup(default_nodegroup, _UPGRADE_CONFIG_JID, True) |
2061 |
modified = True
|
2062 |
for node in self._config_data.nodes.values(): |
2063 |
if not node.group: |
2064 |
node.group = self.LookupNodeGroup(None) |
2065 |
modified = True
|
2066 |
# This is technically *not* an upgrade, but needs to be done both when
|
2067 |
# nodegroups are being added, and upon normally loading the config,
|
2068 |
# because the members list of a node group is discarded upon
|
2069 |
# serializing/deserializing the object.
|
2070 |
self._UnlockedAddNodeToGroup(node.name, node.group)
|
2071 |
if modified:
|
2072 |
self._WriteConfig()
|
2073 |
# This is ok even if it acquires the internal lock, as _UpgradeConfig is
|
2074 |
# only called at config init time, without the lock held
|
2075 |
self.DropECReservations(_UPGRADE_CONFIG_JID)
|
2076 |
|
2077 |
def _DistributeConfig(self, feedback_fn): |
2078 |
"""Distribute the configuration to the other nodes.
|
2079 |
|
2080 |
Currently, this only copies the configuration file. In the future,
|
2081 |
it could be used to encapsulate the 2/3-phase update mechanism.
|
2082 |
|
2083 |
"""
|
2084 |
if self._offline: |
2085 |
return True |
2086 |
|
2087 |
bad = False
|
2088 |
|
2089 |
node_list = [] |
2090 |
addr_list = [] |
2091 |
myhostname = self._my_hostname
|
2092 |
# we can skip checking whether _UnlockedGetNodeInfo returns None
|
2093 |
# since the node list comes from _UnlocketGetNodeList, and we are
|
2094 |
# called with the lock held, so no modifications should take place
|
2095 |
# in between
|
2096 |
for node_name in self._UnlockedGetNodeList(): |
2097 |
if node_name == myhostname:
|
2098 |
continue
|
2099 |
node_info = self._UnlockedGetNodeInfo(node_name)
|
2100 |
if not node_info.master_candidate: |
2101 |
continue
|
2102 |
node_list.append(node_info.name) |
2103 |
addr_list.append(node_info.primary_ip) |
2104 |
|
2105 |
# TODO: Use dedicated resolver talking to config writer for name resolution
|
2106 |
result = \ |
2107 |
self._GetRpc(addr_list).call_upload_file(node_list, self._cfg_file) |
2108 |
for to_node, to_result in result.items(): |
2109 |
msg = to_result.fail_msg |
2110 |
if msg:
|
2111 |
msg = ("Copy of file %s to node %s failed: %s" %
|
2112 |
(self._cfg_file, to_node, msg))
|
2113 |
logging.error(msg) |
2114 |
|
2115 |
if feedback_fn:
|
2116 |
feedback_fn(msg) |
2117 |
|
2118 |
bad = True
|
2119 |
|
2120 |
return not bad |
2121 |
|
2122 |
def _WriteConfig(self, destination=None, feedback_fn=None): |
2123 |
"""Write the configuration data to persistent storage.
|
2124 |
|
2125 |
"""
|
2126 |
assert feedback_fn is None or callable(feedback_fn) |
2127 |
|
2128 |
# Warn on config errors, but don't abort the save - the
|
2129 |
# configuration has already been modified, and we can't revert;
|
2130 |
# the best we can do is to warn the user and save as is, leaving
|
2131 |
# recovery to the user
|
2132 |
config_errors = self._UnlockedVerifyConfig()
|
2133 |
if config_errors:
|
2134 |
errmsg = ("Configuration data is not consistent: %s" %
|
2135 |
(utils.CommaJoin(config_errors))) |
2136 |
logging.critical(errmsg) |
2137 |
if feedback_fn:
|
2138 |
feedback_fn(errmsg) |
2139 |
|
2140 |
if destination is None: |
2141 |
destination = self._cfg_file
|
2142 |
self._BumpSerialNo()
|
2143 |
txt = serializer.Dump(self._config_data.ToDict())
|
2144 |
|
2145 |
getents = self._getents()
|
2146 |
try:
|
2147 |
fd = utils.SafeWriteFile(destination, self._cfg_id, data=txt,
|
2148 |
close=False, gid=getents.confd_gid, mode=0640) |
2149 |
except errors.LockError:
|
2150 |
raise errors.ConfigurationError("The configuration file has been" |
2151 |
" modified since the last write, cannot"
|
2152 |
" update")
|
2153 |
try:
|
2154 |
self._cfg_id = utils.GetFileID(fd=fd)
|
2155 |
finally:
|
2156 |
os.close(fd) |
2157 |
|
2158 |
self.write_count += 1 |
2159 |
|
2160 |
# and redistribute the config file to master candidates
|
2161 |
self._DistributeConfig(feedback_fn)
|
2162 |
|
2163 |
# Write ssconf files on all nodes (including locally)
|
2164 |
if self._last_cluster_serial < self._config_data.cluster.serial_no: |
2165 |
if not self._offline: |
2166 |
result = self._GetRpc(None).call_write_ssconf_files( |
2167 |
self._UnlockedGetOnlineNodeList(),
|
2168 |
self._UnlockedGetSsconfValues())
|
2169 |
|
2170 |
for nname, nresu in result.items(): |
2171 |
msg = nresu.fail_msg |
2172 |
if msg:
|
2173 |
errmsg = ("Error while uploading ssconf files to"
|
2174 |
" node %s: %s" % (nname, msg))
|
2175 |
logging.warning(errmsg) |
2176 |
|
2177 |
if feedback_fn:
|
2178 |
feedback_fn(errmsg) |
2179 |
|
2180 |
self._last_cluster_serial = self._config_data.cluster.serial_no |
2181 |
|
2182 |
def _UnlockedGetSsconfValues(self): |
2183 |
"""Return the values needed by ssconf.
|
2184 |
|
2185 |
@rtype: dict
|
2186 |
@return: a dictionary with keys the ssconf names and values their
|
2187 |
associated value
|
2188 |
|
2189 |
"""
|
2190 |
fn = "\n".join
|
2191 |
instance_names = utils.NiceSort(self._UnlockedGetInstanceList())
|
2192 |
node_names = utils.NiceSort(self._UnlockedGetNodeList())
|
2193 |
node_info = [self._UnlockedGetNodeInfo(name) for name in node_names] |
2194 |
node_pri_ips = ["%s %s" % (ninfo.name, ninfo.primary_ip)
|
2195 |
for ninfo in node_info] |
2196 |
node_snd_ips = ["%s %s" % (ninfo.name, ninfo.secondary_ip)
|
2197 |
for ninfo in node_info] |
2198 |
|
2199 |
instance_data = fn(instance_names) |
2200 |
off_data = fn(node.name for node in node_info if node.offline) |
2201 |
on_data = fn(node.name for node in node_info if not node.offline) |
2202 |
mc_data = fn(node.name for node in node_info if node.master_candidate) |
2203 |
mc_ips_data = fn(node.primary_ip for node in node_info |
2204 |
if node.master_candidate)
|
2205 |
node_data = fn(node_names) |
2206 |
node_pri_ips_data = fn(node_pri_ips) |
2207 |
node_snd_ips_data = fn(node_snd_ips) |
2208 |
|
2209 |
cluster = self._config_data.cluster
|
2210 |
cluster_tags = fn(cluster.GetTags()) |
2211 |
|
2212 |
hypervisor_list = fn(cluster.enabled_hypervisors) |
2213 |
|
2214 |
uid_pool = uidpool.FormatUidPool(cluster.uid_pool, separator="\n")
|
2215 |
|
2216 |
nodegroups = ["%s %s" % (nodegroup.uuid, nodegroup.name) for nodegroup in |
2217 |
self._config_data.nodegroups.values()]
|
2218 |
nodegroups_data = fn(utils.NiceSort(nodegroups)) |
2219 |
networks = ["%s %s" % (net.uuid, net.name) for net in |
2220 |
self._config_data.networks.values()]
|
2221 |
networks_data = fn(utils.NiceSort(networks)) |
2222 |
|
2223 |
ssconf_values = { |
2224 |
constants.SS_CLUSTER_NAME: cluster.cluster_name, |
2225 |
constants.SS_CLUSTER_TAGS: cluster_tags, |
2226 |
constants.SS_FILE_STORAGE_DIR: cluster.file_storage_dir, |
2227 |
constants.SS_SHARED_FILE_STORAGE_DIR: cluster.shared_file_storage_dir, |
2228 |
constants.SS_MASTER_CANDIDATES: mc_data, |
2229 |
constants.SS_MASTER_CANDIDATES_IPS: mc_ips_data, |
2230 |
constants.SS_MASTER_IP: cluster.master_ip, |
2231 |
constants.SS_MASTER_NETDEV: cluster.master_netdev, |
2232 |
constants.SS_MASTER_NETMASK: str(cluster.master_netmask),
|
2233 |
constants.SS_MASTER_NODE: cluster.master_node, |
2234 |
constants.SS_NODE_LIST: node_data, |
2235 |
constants.SS_NODE_PRIMARY_IPS: node_pri_ips_data, |
2236 |
constants.SS_NODE_SECONDARY_IPS: node_snd_ips_data, |
2237 |
constants.SS_OFFLINE_NODES: off_data, |
2238 |
constants.SS_ONLINE_NODES: on_data, |
2239 |
constants.SS_PRIMARY_IP_FAMILY: str(cluster.primary_ip_family),
|
2240 |
constants.SS_INSTANCE_LIST: instance_data, |
2241 |
constants.SS_RELEASE_VERSION: constants.RELEASE_VERSION, |
2242 |
constants.SS_HYPERVISOR_LIST: hypervisor_list, |
2243 |
constants.SS_MAINTAIN_NODE_HEALTH: str(cluster.maintain_node_health),
|
2244 |
constants.SS_UID_POOL: uid_pool, |
2245 |
constants.SS_NODEGROUPS: nodegroups_data, |
2246 |
constants.SS_NETWORKS: networks_data, |
2247 |
} |
2248 |
bad_values = [(k, v) for k, v in ssconf_values.items() |
2249 |
if not isinstance(v, (str, basestring))] |
2250 |
if bad_values:
|
2251 |
err = utils.CommaJoin("%s=%s" % (k, v) for k, v in bad_values) |
2252 |
raise errors.ConfigurationError("Some ssconf key(s) have non-string" |
2253 |
" values: %s" % err)
|
2254 |
return ssconf_values
|
2255 |
|
2256 |
@locking.ssynchronized(_config_lock, shared=1) |
2257 |
def GetSsconfValues(self): |
2258 |
"""Wrapper using lock around _UnlockedGetSsconf().
|
2259 |
|
2260 |
"""
|
2261 |
return self._UnlockedGetSsconfValues() |
2262 |
|
2263 |
@locking.ssynchronized(_config_lock, shared=1) |
2264 |
def GetVGName(self): |
2265 |
"""Return the volume group name.
|
2266 |
|
2267 |
"""
|
2268 |
return self._config_data.cluster.volume_group_name |
2269 |
|
2270 |
@locking.ssynchronized(_config_lock)
|
2271 |
def SetVGName(self, vg_name): |
2272 |
"""Set the volume group name.
|
2273 |
|
2274 |
"""
|
2275 |
self._config_data.cluster.volume_group_name = vg_name
|
2276 |
self._config_data.cluster.serial_no += 1 |
2277 |
self._WriteConfig()
|
2278 |
|
2279 |
@locking.ssynchronized(_config_lock, shared=1) |
2280 |
def GetDRBDHelper(self): |
2281 |
"""Return DRBD usermode helper.
|
2282 |
|
2283 |
"""
|
2284 |
return self._config_data.cluster.drbd_usermode_helper |
2285 |
|
2286 |
@locking.ssynchronized(_config_lock)
|
2287 |
def SetDRBDHelper(self, drbd_helper): |
2288 |
"""Set DRBD usermode helper.
|
2289 |
|
2290 |
"""
|
2291 |
self._config_data.cluster.drbd_usermode_helper = drbd_helper
|
2292 |
self._config_data.cluster.serial_no += 1 |
2293 |
self._WriteConfig()
|
2294 |
|
2295 |
@locking.ssynchronized(_config_lock, shared=1) |
2296 |
def GetMACPrefix(self): |
2297 |
"""Return the mac prefix.
|
2298 |
|
2299 |
"""
|
2300 |
return self._config_data.cluster.mac_prefix |
2301 |
|
2302 |
@locking.ssynchronized(_config_lock, shared=1) |
2303 |
def GetClusterInfo(self): |
2304 |
"""Returns information about the cluster
|
2305 |
|
2306 |
@rtype: L{objects.Cluster}
|
2307 |
@return: the cluster object
|
2308 |
|
2309 |
"""
|
2310 |
return self._config_data.cluster |
2311 |
|
2312 |
@locking.ssynchronized(_config_lock, shared=1) |
2313 |
def HasAnyDiskOfType(self, dev_type): |
2314 |
"""Check if in there is at disk of the given type in the configuration.
|
2315 |
|
2316 |
"""
|
2317 |
return self._config_data.HasAnyDiskOfType(dev_type) |
2318 |
|
2319 |
@locking.ssynchronized(_config_lock)
|
2320 |
def Update(self, target, feedback_fn, ec_id=None): |
2321 |
"""Notify function to be called after updates.
|
2322 |
|
2323 |
This function must be called when an object (as returned by
|
2324 |
GetInstanceInfo, GetNodeInfo, GetCluster) has been updated and the
|
2325 |
caller wants the modifications saved to the backing store. Note
|
2326 |
that all modified objects will be saved, but the target argument
|
2327 |
is the one the caller wants to ensure that it's saved.
|
2328 |
|
2329 |
@param target: an instance of either L{objects.Cluster},
|
2330 |
L{objects.Node} or L{objects.Instance} which is existing in
|
2331 |
the cluster
|
2332 |
@param feedback_fn: Callable feedback function
|
2333 |
|
2334 |
"""
|
2335 |
if self._config_data is None: |
2336 |
raise errors.ProgrammerError("Configuration file not read," |
2337 |
" cannot save.")
|
2338 |
update_serial = False
|
2339 |
if isinstance(target, objects.Cluster): |
2340 |
test = target == self._config_data.cluster
|
2341 |
elif isinstance(target, objects.Node): |
2342 |
test = target in self._config_data.nodes.values() |
2343 |
update_serial = True
|
2344 |
elif isinstance(target, objects.Instance): |
2345 |
test = target in self._config_data.instances.values() |
2346 |
elif isinstance(target, objects.NodeGroup): |
2347 |
test = target in self._config_data.nodegroups.values() |
2348 |
elif isinstance(target, objects.Network): |
2349 |
test = target in self._config_data.networks.values() |
2350 |
else:
|
2351 |
raise errors.ProgrammerError("Invalid object type (%s) passed to" |
2352 |
" ConfigWriter.Update" % type(target)) |
2353 |
if not test: |
2354 |
raise errors.ConfigurationError("Configuration updated since object" |
2355 |
" has been read or unknown object")
|
2356 |
target.serial_no += 1
|
2357 |
target.mtime = now = time.time() |
2358 |
|
2359 |
if update_serial:
|
2360 |
# for node updates, we need to increase the cluster serial too
|
2361 |
self._config_data.cluster.serial_no += 1 |
2362 |
self._config_data.cluster.mtime = now
|
2363 |
|
2364 |
if isinstance(target, objects.Instance): |
2365 |
self._UnlockedReleaseDRBDMinors(target.name)
|
2366 |
|
2367 |
if ec_id is not None: |
2368 |
# Commit all ips reserved by OpInstanceSetParams and OpGroupSetParams
|
2369 |
self._UnlockedCommitTemporaryIps(ec_id)
|
2370 |
|
2371 |
self._WriteConfig(feedback_fn=feedback_fn)
|
2372 |
|
2373 |
@locking.ssynchronized(_config_lock)
|
2374 |
def DropECReservations(self, ec_id): |
2375 |
"""Drop per-execution-context reservations
|
2376 |
|
2377 |
"""
|
2378 |
for rm in self._all_rms: |
2379 |
rm.DropECReservations(ec_id) |
2380 |
|
2381 |
@locking.ssynchronized(_config_lock, shared=1) |
2382 |
def GetAllNetworksInfo(self): |
2383 |
"""Get the configuration of all networks
|
2384 |
|
2385 |
"""
|
2386 |
return dict(self._config_data.networks) |
2387 |
|
2388 |
def _UnlockedGetNetworkList(self): |
2389 |
"""Get the list of networks.
|
2390 |
|
2391 |
This function is for internal use, when the config lock is already held.
|
2392 |
|
2393 |
"""
|
2394 |
return self._config_data.networks.keys() |
2395 |
|
2396 |
@locking.ssynchronized(_config_lock, shared=1) |
2397 |
def GetNetworkList(self): |
2398 |
"""Get the list of networks.
|
2399 |
|
2400 |
@return: array of networks, ex. ["main", "vlan100", "200]
|
2401 |
|
2402 |
"""
|
2403 |
return self._UnlockedGetNetworkList() |
2404 |
|
2405 |
@locking.ssynchronized(_config_lock, shared=1) |
2406 |
def GetNetworkNames(self): |
2407 |
"""Get a list of network names
|
2408 |
|
2409 |
"""
|
2410 |
names = [net.name |
2411 |
for net in self._config_data.networks.values()] |
2412 |
return names
|
2413 |
|
2414 |
def _UnlockedGetNetwork(self, uuid): |
2415 |
"""Returns information about a network.
|
2416 |
|
2417 |
This function is for internal use, when the config lock is already held.
|
2418 |
|
2419 |
"""
|
2420 |
if uuid not in self._config_data.networks: |
2421 |
return None |
2422 |
|
2423 |
return self._config_data.networks[uuid] |
2424 |
|
2425 |
@locking.ssynchronized(_config_lock, shared=1) |
2426 |
def GetNetwork(self, uuid): |
2427 |
"""Returns information about a network.
|
2428 |
|
2429 |
It takes the information from the configuration file.
|
2430 |
|
2431 |
@param uuid: UUID of the network
|
2432 |
|
2433 |
@rtype: L{objects.Network}
|
2434 |
@return: the network object
|
2435 |
|
2436 |
"""
|
2437 |
return self._UnlockedGetNetwork(uuid) |
2438 |
|
2439 |
@locking.ssynchronized(_config_lock)
|
2440 |
def AddNetwork(self, net, ec_id, check_uuid=True): |
2441 |
"""Add a network to the configuration.
|
2442 |
|
2443 |
@type net: L{objects.Network}
|
2444 |
@param net: the Network object to add
|
2445 |
@type ec_id: string
|
2446 |
@param ec_id: unique id for the job to use when creating a missing UUID
|
2447 |
|
2448 |
"""
|
2449 |
self._UnlockedAddNetwork(net, ec_id, check_uuid)
|
2450 |
self._WriteConfig()
|
2451 |
|
2452 |
def _UnlockedAddNetwork(self, net, ec_id, check_uuid): |
2453 |
"""Add a network to the configuration.
|
2454 |
|
2455 |
"""
|
2456 |
logging.info("Adding network %s to configuration", net.name)
|
2457 |
|
2458 |
if check_uuid:
|
2459 |
self._EnsureUUID(net, ec_id)
|
2460 |
|
2461 |
existing_uuid = self._UnlockedLookupNetwork(net.name)
|
2462 |
if existing_uuid:
|
2463 |
raise errors.OpPrereqError("Desired network name '%s' already" |
2464 |
" exists as a network (UUID: %s)" %
|
2465 |
(net.name, existing_uuid), |
2466 |
errors.ECODE_EXISTS) |
2467 |
net.serial_no = 1
|
2468 |
self._config_data.networks[net.uuid] = net
|
2469 |
self._config_data.cluster.serial_no += 1 |
2470 |
|
2471 |
def _UnlockedLookupNetwork(self, target): |
2472 |
"""Lookup a network's UUID.
|
2473 |
|
2474 |
@type target: string
|
2475 |
@param target: network name or UUID
|
2476 |
@rtype: string
|
2477 |
@return: network UUID
|
2478 |
@raises errors.OpPrereqError: when the target network cannot be found
|
2479 |
|
2480 |
"""
|
2481 |
if target in self._config_data.networks: |
2482 |
return target
|
2483 |
for net in self._config_data.networks.values(): |
2484 |
if net.name == target:
|
2485 |
return net.uuid
|
2486 |
return None |
2487 |
|
2488 |
@locking.ssynchronized(_config_lock, shared=1) |
2489 |
def LookupNetwork(self, target): |
2490 |
"""Lookup a network's UUID.
|
2491 |
|
2492 |
This function is just a wrapper over L{_UnlockedLookupNetwork}.
|
2493 |
|
2494 |
@type target: string
|
2495 |
@param target: network name or UUID
|
2496 |
@rtype: string
|
2497 |
@return: network UUID
|
2498 |
|
2499 |
"""
|
2500 |
return self._UnlockedLookupNetwork(target) |
2501 |
|
2502 |
@locking.ssynchronized(_config_lock)
|
2503 |
def RemoveNetwork(self, network_uuid): |
2504 |
"""Remove a network from the configuration.
|
2505 |
|
2506 |
@type network_uuid: string
|
2507 |
@param network_uuid: the UUID of the network to remove
|
2508 |
|
2509 |
"""
|
2510 |
logging.info("Removing network %s from configuration", network_uuid)
|
2511 |
|
2512 |
if network_uuid not in self._config_data.networks: |
2513 |
raise errors.ConfigurationError("Unknown network '%s'" % network_uuid) |
2514 |
|
2515 |
del self._config_data.networks[network_uuid] |
2516 |
self._config_data.cluster.serial_no += 1 |
2517 |
self._WriteConfig()
|
2518 |
|
2519 |
def _UnlockedGetGroupNetParams(self, net, node): |
2520 |
"""Get the netparams (mode, link) of a network.
|
2521 |
|
2522 |
Get a network's netparams for a given node.
|
2523 |
|
2524 |
@type net: string
|
2525 |
@param net: network name
|
2526 |
@type node: string
|
2527 |
@param node: node name
|
2528 |
@rtype: dict or None
|
2529 |
@return: netparams
|
2530 |
|
2531 |
"""
|
2532 |
net_uuid = self._UnlockedLookupNetwork(net)
|
2533 |
if net_uuid is None: |
2534 |
return None |
2535 |
|
2536 |
node_info = self._UnlockedGetNodeInfo(node)
|
2537 |
nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
|
2538 |
netparams = nodegroup_info.networks.get(net_uuid, None)
|
2539 |
|
2540 |
return netparams
|
2541 |
|
2542 |
@locking.ssynchronized(_config_lock, shared=1) |
2543 |
def GetGroupNetParams(self, net, node): |
2544 |
"""Locking wrapper of _UnlockedGetGroupNetParams()
|
2545 |
|
2546 |
"""
|
2547 |
return self._UnlockedGetGroupNetParams(net, node) |
2548 |
|
2549 |
|
2550 |
@locking.ssynchronized(_config_lock, shared=1) |
2551 |
def CheckIPInNodeGroup(self, ip, node): |
2552 |
"""Check for conflictig IP.
|
2553 |
|
2554 |
@type ip: string
|
2555 |
@param ip: ip address
|
2556 |
@type node: string
|
2557 |
@param node: node name
|
2558 |
@rtype: (string, dict) or (None, None)
|
2559 |
@return: (network name, netparams)
|
2560 |
|
2561 |
"""
|
2562 |
if ip is None: |
2563 |
return (None, None) |
2564 |
node_info = self._UnlockedGetNodeInfo(node)
|
2565 |
nodegroup_info = self._UnlockedGetNodeGroup(node_info.group)
|
2566 |
for net_uuid in nodegroup_info.networks.keys(): |
2567 |
net_info = self._UnlockedGetNetwork(net_uuid)
|
2568 |
pool = network.AddressPool(net_info) |
2569 |
if pool.Contains(ip):
|
2570 |
return (net_info.name, nodegroup_info.networks[net_uuid])
|
2571 |
|
2572 |
return (None, None) |