root / lib / bootstrap.py @ 425f0f54
History | View | Annotate | Download (24 kB)
1 |
#
|
---|---|
2 |
#
|
3 |
|
4 |
# Copyright (C) 2006, 2007, 2008 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 |
"""Functions to bootstrap a new cluster.
|
23 |
|
24 |
"""
|
25 |
|
26 |
import os |
27 |
import os.path |
28 |
import re |
29 |
import logging |
30 |
import time |
31 |
|
32 |
from ganeti import rpc |
33 |
from ganeti import ssh |
34 |
from ganeti import utils |
35 |
from ganeti import errors |
36 |
from ganeti import config |
37 |
from ganeti import constants |
38 |
from ganeti import objects |
39 |
from ganeti import ssconf |
40 |
from ganeti import serializer |
41 |
from ganeti import hypervisor |
42 |
from ganeti import bdev |
43 |
|
44 |
|
45 |
def _InitSSHSetup(): |
46 |
"""Setup the SSH configuration for the cluster.
|
47 |
|
48 |
This generates a dsa keypair for root, adds the pub key to the
|
49 |
permitted hosts and adds the hostkey to its own known hosts.
|
50 |
|
51 |
"""
|
52 |
priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS) |
53 |
|
54 |
for name in priv_key, pub_key: |
55 |
if os.path.exists(name):
|
56 |
utils.CreateBackup(name) |
57 |
utils.RemoveFile(name) |
58 |
|
59 |
result = utils.RunCmd(["ssh-keygen", "-t", "dsa", |
60 |
"-f", priv_key,
|
61 |
"-q", "-N", ""]) |
62 |
if result.failed:
|
63 |
raise errors.OpExecError("Could not generate ssh keypair, error %s" % |
64 |
result.output) |
65 |
|
66 |
utils.AddAuthorizedKey(auth_keys, utils.ReadFile(pub_key)) |
67 |
|
68 |
|
69 |
def GenerateHmacKey(file_name): |
70 |
"""Writes a new HMAC key.
|
71 |
|
72 |
@type file_name: str
|
73 |
@param file_name: Path to output file
|
74 |
|
75 |
"""
|
76 |
utils.WriteFile(file_name, data="%s\n" % utils.GenerateSecret(), mode=0400, |
77 |
backup=True)
|
78 |
|
79 |
|
80 |
def GenerateClusterCrypto(new_cluster_cert, new_rapi_cert, new_confd_hmac_key, |
81 |
new_cds, rapi_cert_pem=None, cds=None, |
82 |
nodecert_file=constants.NODED_CERT_FILE, |
83 |
rapicert_file=constants.RAPI_CERT_FILE, |
84 |
hmackey_file=constants.CONFD_HMAC_KEY, |
85 |
cds_file=constants.CLUSTER_DOMAIN_SECRET_FILE): |
86 |
"""Updates the cluster certificates, keys and secrets.
|
87 |
|
88 |
@type new_cluster_cert: bool
|
89 |
@param new_cluster_cert: Whether to generate a new cluster certificate
|
90 |
@type new_rapi_cert: bool
|
91 |
@param new_rapi_cert: Whether to generate a new RAPI certificate
|
92 |
@type new_confd_hmac_key: bool
|
93 |
@param new_confd_hmac_key: Whether to generate a new HMAC key
|
94 |
@type new_cds: bool
|
95 |
@param new_cds: Whether to generate a new cluster domain secret
|
96 |
@type rapi_cert_pem: string
|
97 |
@param rapi_cert_pem: New RAPI certificate in PEM format
|
98 |
@type cds: string
|
99 |
@param cds: New cluster domain secret
|
100 |
@type nodecert_file: string
|
101 |
@param nodecert_file: optional override of the node cert file path
|
102 |
@type rapicert_file: string
|
103 |
@param rapicert_file: optional override of the rapi cert file path
|
104 |
@type hmackey_file: string
|
105 |
@param hmackey_file: optional override of the hmac key file path
|
106 |
|
107 |
"""
|
108 |
# noded SSL certificate
|
109 |
cluster_cert_exists = os.path.exists(nodecert_file) |
110 |
if new_cluster_cert or not cluster_cert_exists: |
111 |
if cluster_cert_exists:
|
112 |
utils.CreateBackup(nodecert_file) |
113 |
|
114 |
logging.debug("Generating new cluster certificate at %s", nodecert_file)
|
115 |
utils.GenerateSelfSignedSslCert(nodecert_file) |
116 |
|
117 |
# confd HMAC key
|
118 |
if new_confd_hmac_key or not os.path.exists(hmackey_file): |
119 |
logging.debug("Writing new confd HMAC key to %s", hmackey_file)
|
120 |
GenerateHmacKey(hmackey_file) |
121 |
|
122 |
# RAPI
|
123 |
rapi_cert_exists = os.path.exists(rapicert_file) |
124 |
|
125 |
if rapi_cert_pem:
|
126 |
# Assume rapi_pem contains a valid PEM-formatted certificate and key
|
127 |
logging.debug("Writing RAPI certificate at %s", rapicert_file)
|
128 |
utils.WriteFile(rapicert_file, data=rapi_cert_pem, backup=True)
|
129 |
|
130 |
elif new_rapi_cert or not rapi_cert_exists: |
131 |
if rapi_cert_exists:
|
132 |
utils.CreateBackup(rapicert_file) |
133 |
|
134 |
logging.debug("Generating new RAPI certificate at %s", rapicert_file)
|
135 |
utils.GenerateSelfSignedSslCert(rapicert_file) |
136 |
|
137 |
# Cluster domain secret
|
138 |
if cds:
|
139 |
logging.debug("Writing cluster domain secret to %s", cds_file)
|
140 |
utils.WriteFile(cds_file, data=cds, backup=True)
|
141 |
|
142 |
elif new_cds or not os.path.exists(cds_file): |
143 |
logging.debug("Generating new cluster domain secret at %s", cds_file)
|
144 |
GenerateHmacKey(cds_file) |
145 |
|
146 |
|
147 |
def _InitGanetiServerSetup(master_name): |
148 |
"""Setup the necessary configuration for the initial node daemon.
|
149 |
|
150 |
This creates the nodepass file containing the shared password for
|
151 |
the cluster and also generates the SSL certificate.
|
152 |
|
153 |
"""
|
154 |
# Generate cluster secrets
|
155 |
GenerateClusterCrypto(True, False, False, False) |
156 |
|
157 |
result = utils.RunCmd([constants.DAEMON_UTIL, "start", constants.NODED])
|
158 |
if result.failed:
|
159 |
raise errors.OpExecError("Could not start the node daemon, command %s" |
160 |
" had exitcode %s and error %s" %
|
161 |
(result.cmd, result.exit_code, result.output)) |
162 |
|
163 |
_WaitForNodeDaemon(master_name) |
164 |
|
165 |
|
166 |
def _WaitForNodeDaemon(node_name): |
167 |
"""Wait for node daemon to become responsive.
|
168 |
|
169 |
"""
|
170 |
def _CheckNodeDaemon(): |
171 |
result = rpc.RpcRunner.call_version([node_name])[node_name] |
172 |
if result.fail_msg:
|
173 |
raise utils.RetryAgain()
|
174 |
|
175 |
try:
|
176 |
utils.Retry(_CheckNodeDaemon, 1.0, 10.0) |
177 |
except utils.RetryTimeout:
|
178 |
raise errors.OpExecError("Node daemon on %s didn't answer queries within" |
179 |
" 10 seconds" % node_name)
|
180 |
|
181 |
|
182 |
def _InitFileStorage(file_storage_dir): |
183 |
"""Initialize if needed the file storage.
|
184 |
|
185 |
@param file_storage_dir: the user-supplied value
|
186 |
@return: either empty string (if file storage was disabled at build
|
187 |
time) or the normalized path to the storage directory
|
188 |
|
189 |
"""
|
190 |
if not constants.ENABLE_FILE_STORAGE: |
191 |
return "" |
192 |
|
193 |
file_storage_dir = os.path.normpath(file_storage_dir) |
194 |
|
195 |
if not os.path.isabs(file_storage_dir): |
196 |
raise errors.OpPrereqError("The file storage directory you passed is" |
197 |
" not an absolute path.", errors.ECODE_INVAL)
|
198 |
|
199 |
if not os.path.exists(file_storage_dir): |
200 |
try:
|
201 |
os.makedirs(file_storage_dir, 0750)
|
202 |
except OSError, err: |
203 |
raise errors.OpPrereqError("Cannot create file storage directory" |
204 |
" '%s': %s" % (file_storage_dir, err),
|
205 |
errors.ECODE_ENVIRON) |
206 |
|
207 |
if not os.path.isdir(file_storage_dir): |
208 |
raise errors.OpPrereqError("The file storage directory '%s' is not" |
209 |
" a directory." % file_storage_dir,
|
210 |
errors.ECODE_ENVIRON) |
211 |
return file_storage_dir
|
212 |
|
213 |
|
214 |
#pylint: disable-msg=R0913
|
215 |
def InitCluster(cluster_name, mac_prefix, |
216 |
master_netdev, file_storage_dir, candidate_pool_size, |
217 |
secondary_ip=None, vg_name=None, beparams=None, |
218 |
nicparams=None, hvparams=None, enabled_hypervisors=None, |
219 |
modify_etc_hosts=True, modify_ssh_setup=True, |
220 |
maintain_node_health=False, drbd_helper=None, |
221 |
uid_pool=None):
|
222 |
"""Initialise the cluster.
|
223 |
|
224 |
@type candidate_pool_size: int
|
225 |
@param candidate_pool_size: master candidate pool size
|
226 |
|
227 |
"""
|
228 |
# TODO: complete the docstring
|
229 |
if config.ConfigWriter.IsCluster():
|
230 |
raise errors.OpPrereqError("Cluster is already initialised", |
231 |
errors.ECODE_STATE) |
232 |
|
233 |
if not enabled_hypervisors: |
234 |
raise errors.OpPrereqError("Enabled hypervisors list must contain at" |
235 |
" least one member", errors.ECODE_INVAL)
|
236 |
invalid_hvs = set(enabled_hypervisors) - constants.HYPER_TYPES
|
237 |
if invalid_hvs:
|
238 |
raise errors.OpPrereqError("Enabled hypervisors contains invalid" |
239 |
" entries: %s" % invalid_hvs,
|
240 |
errors.ECODE_INVAL) |
241 |
|
242 |
hostname = utils.GetHostInfo() |
243 |
|
244 |
if hostname.ip.startswith("127."): |
245 |
raise errors.OpPrereqError("This host's IP resolves to the private" |
246 |
" range (%s). Please fix DNS or %s." %
|
247 |
(hostname.ip, constants.ETC_HOSTS), |
248 |
errors.ECODE_ENVIRON) |
249 |
|
250 |
if not utils.OwnIpAddress(hostname.ip): |
251 |
raise errors.OpPrereqError("Inconsistency: this host's name resolves" |
252 |
" to %s,\nbut this ip address does not"
|
253 |
" belong to this host. Aborting." %
|
254 |
hostname.ip, errors.ECODE_ENVIRON) |
255 |
|
256 |
clustername = utils.GetHostInfo(utils.HostInfo.NormalizeName(cluster_name)) |
257 |
|
258 |
if utils.TcpPing(clustername.ip, constants.DEFAULT_NODED_PORT,
|
259 |
timeout=5):
|
260 |
raise errors.OpPrereqError("Cluster IP already active. Aborting.", |
261 |
errors.ECODE_NOTUNIQUE) |
262 |
|
263 |
if secondary_ip:
|
264 |
if not utils.IsValidIP4(secondary_ip): |
265 |
raise errors.OpPrereqError("Invalid secondary ip given", |
266 |
errors.ECODE_INVAL) |
267 |
if (secondary_ip != hostname.ip and |
268 |
not utils.OwnIpAddress(secondary_ip)):
|
269 |
raise errors.OpPrereqError("You gave %s as secondary IP," |
270 |
" but it does not belong to this host." %
|
271 |
secondary_ip, errors.ECODE_ENVIRON) |
272 |
else:
|
273 |
secondary_ip = hostname.ip |
274 |
|
275 |
if vg_name is not None: |
276 |
# Check if volume group is valid
|
277 |
vgstatus = utils.CheckVolumeGroupSize(utils.ListVolumeGroups(), vg_name, |
278 |
constants.MIN_VG_SIZE) |
279 |
if vgstatus:
|
280 |
raise errors.OpPrereqError("Error: %s\nspecify --no-lvm-storage if" |
281 |
" you are not using lvm" % vgstatus,
|
282 |
errors.ECODE_INVAL) |
283 |
|
284 |
if drbd_helper is not None: |
285 |
try:
|
286 |
curr_helper = bdev.BaseDRBD.GetUsermodeHelper() |
287 |
except errors.BlockDeviceError, err:
|
288 |
raise errors.OpPrereqError("Error while checking drbd helper" |
289 |
" (specify --no-drbd-storage if you are not"
|
290 |
" using drbd): %s" % str(err), |
291 |
errors.ECODE_ENVIRON) |
292 |
if drbd_helper != curr_helper:
|
293 |
raise errors.OpPrereqError("Error: requiring %s as drbd helper but %s" |
294 |
" is the current helper" % (drbd_helper,
|
295 |
curr_helper), |
296 |
errors.ECODE_INVAL) |
297 |
|
298 |
file_storage_dir = _InitFileStorage(file_storage_dir) |
299 |
|
300 |
if not re.match("^[0-9a-z]{2}:[0-9a-z]{2}:[0-9a-z]{2}$", mac_prefix): |
301 |
raise errors.OpPrereqError("Invalid mac prefix given '%s'" % mac_prefix, |
302 |
errors.ECODE_INVAL) |
303 |
|
304 |
result = utils.RunCmd(["ip", "link", "show", "dev", master_netdev]) |
305 |
if result.failed:
|
306 |
raise errors.OpPrereqError("Invalid master netdev given (%s): '%s'" % |
307 |
(master_netdev, |
308 |
result.output.strip()), errors.ECODE_INVAL) |
309 |
|
310 |
dirs = [(constants.RUN_GANETI_DIR, constants.RUN_DIRS_MODE)] |
311 |
utils.EnsureDirs(dirs) |
312 |
|
313 |
utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES) |
314 |
utils.ForceDictType(nicparams, constants.NICS_PARAMETER_TYPES) |
315 |
objects.NIC.CheckParameterSyntax(nicparams) |
316 |
|
317 |
# hvparams is a mapping of hypervisor->hvparams dict
|
318 |
for hv_name, hv_params in hvparams.iteritems(): |
319 |
utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES) |
320 |
hv_class = hypervisor.GetHypervisor(hv_name) |
321 |
hv_class.CheckParameterSyntax(hv_params) |
322 |
|
323 |
# set up the inter-node password and certificate
|
324 |
_InitGanetiServerSetup(hostname.name) |
325 |
|
326 |
# set up ssh config and /etc/hosts
|
327 |
sshline = utils.ReadFile(constants.SSH_HOST_RSA_PUB) |
328 |
sshkey = sshline.split(" ")[1] |
329 |
|
330 |
if modify_etc_hosts:
|
331 |
utils.AddHostToEtcHosts(hostname.name) |
332 |
|
333 |
if modify_ssh_setup:
|
334 |
_InitSSHSetup() |
335 |
|
336 |
now = time.time() |
337 |
|
338 |
# init of cluster config file
|
339 |
cluster_config = objects.Cluster( |
340 |
serial_no=1,
|
341 |
rsahostkeypub=sshkey, |
342 |
highest_used_port=(constants.FIRST_DRBD_PORT - 1),
|
343 |
mac_prefix=mac_prefix, |
344 |
volume_group_name=vg_name, |
345 |
tcpudp_port_pool=set(),
|
346 |
master_node=hostname.name, |
347 |
master_ip=clustername.ip, |
348 |
master_netdev=master_netdev, |
349 |
cluster_name=clustername.name, |
350 |
file_storage_dir=file_storage_dir, |
351 |
enabled_hypervisors=enabled_hypervisors, |
352 |
beparams={constants.PP_DEFAULT: beparams}, |
353 |
nicparams={constants.PP_DEFAULT: nicparams}, |
354 |
hvparams=hvparams, |
355 |
candidate_pool_size=candidate_pool_size, |
356 |
modify_etc_hosts=modify_etc_hosts, |
357 |
modify_ssh_setup=modify_ssh_setup, |
358 |
uid_pool=uid_pool, |
359 |
ctime=now, |
360 |
mtime=now, |
361 |
uuid=utils.NewUUID(), |
362 |
maintain_node_health=maintain_node_health, |
363 |
drbd_usermode_helper=drbd_helper, |
364 |
) |
365 |
master_node_config = objects.Node(name=hostname.name, |
366 |
primary_ip=hostname.ip, |
367 |
secondary_ip=secondary_ip, |
368 |
serial_no=1,
|
369 |
master_candidate=True,
|
370 |
offline=False, drained=False, |
371 |
) |
372 |
InitConfig(constants.CONFIG_VERSION, cluster_config, master_node_config) |
373 |
cfg = config.ConfigWriter() |
374 |
ssh.WriteKnownHostsFile(cfg, constants.SSH_KNOWN_HOSTS_FILE) |
375 |
cfg.Update(cfg.GetClusterInfo(), logging.error) |
376 |
|
377 |
# start the master ip
|
378 |
# TODO: Review rpc call from bootstrap
|
379 |
# TODO: Warn on failed start master
|
380 |
rpc.RpcRunner.call_node_start_master(hostname.name, True, False) |
381 |
|
382 |
|
383 |
def InitConfig(version, cluster_config, master_node_config, |
384 |
cfg_file=constants.CLUSTER_CONF_FILE): |
385 |
"""Create the initial cluster configuration.
|
386 |
|
387 |
It will contain the current node, which will also be the master
|
388 |
node, and no instances.
|
389 |
|
390 |
@type version: int
|
391 |
@param version: configuration version
|
392 |
@type cluster_config: L{objects.Cluster}
|
393 |
@param cluster_config: cluster configuration
|
394 |
@type master_node_config: L{objects.Node}
|
395 |
@param master_node_config: master node configuration
|
396 |
@type cfg_file: string
|
397 |
@param cfg_file: configuration file path
|
398 |
|
399 |
"""
|
400 |
nodes = { |
401 |
master_node_config.name: master_node_config, |
402 |
} |
403 |
|
404 |
now = time.time() |
405 |
config_data = objects.ConfigData(version=version, |
406 |
cluster=cluster_config, |
407 |
nodes=nodes, |
408 |
instances={}, |
409 |
serial_no=1,
|
410 |
ctime=now, mtime=now) |
411 |
utils.WriteFile(cfg_file, |
412 |
data=serializer.Dump(config_data.ToDict()), |
413 |
mode=0600)
|
414 |
|
415 |
|
416 |
def FinalizeClusterDestroy(master): |
417 |
"""Execute the last steps of cluster destroy
|
418 |
|
419 |
This function shuts down all the daemons, completing the destroy
|
420 |
begun in cmdlib.LUDestroyOpcode.
|
421 |
|
422 |
"""
|
423 |
cfg = config.ConfigWriter() |
424 |
modify_ssh_setup = cfg.GetClusterInfo().modify_ssh_setup |
425 |
result = rpc.RpcRunner.call_node_stop_master(master, True)
|
426 |
msg = result.fail_msg |
427 |
if msg:
|
428 |
logging.warning("Could not disable the master role: %s", msg)
|
429 |
result = rpc.RpcRunner.call_node_leave_cluster(master, modify_ssh_setup) |
430 |
msg = result.fail_msg |
431 |
if msg:
|
432 |
logging.warning("Could not shutdown the node daemon and cleanup"
|
433 |
" the node: %s", msg)
|
434 |
|
435 |
|
436 |
def SetupNodeDaemon(cluster_name, node, ssh_key_check): |
437 |
"""Add a node to the cluster.
|
438 |
|
439 |
This function must be called before the actual opcode, and will ssh
|
440 |
to the remote node, copy the needed files, and start ganeti-noded,
|
441 |
allowing the master to do the rest via normal rpc calls.
|
442 |
|
443 |
@param cluster_name: the cluster name
|
444 |
@param node: the name of the new node
|
445 |
@param ssh_key_check: whether to do a strict key check
|
446 |
|
447 |
"""
|
448 |
sshrunner = ssh.SshRunner(cluster_name) |
449 |
|
450 |
noded_cert = utils.ReadFile(constants.NODED_CERT_FILE) |
451 |
rapi_cert = utils.ReadFile(constants.RAPI_CERT_FILE) |
452 |
confd_hmac_key = utils.ReadFile(constants.CONFD_HMAC_KEY) |
453 |
|
454 |
# in the base64 pem encoding, neither '!' nor '.' are valid chars,
|
455 |
# so we use this to detect an invalid certificate; as long as the
|
456 |
# cert doesn't contain this, the here-document will be correctly
|
457 |
# parsed by the shell sequence below. HMAC keys are hexadecimal strings,
|
458 |
# so the same restrictions apply.
|
459 |
for content in (noded_cert, rapi_cert, confd_hmac_key): |
460 |
if re.search('^!EOF\.', content, re.MULTILINE): |
461 |
raise errors.OpExecError("invalid SSL certificate or HMAC key") |
462 |
|
463 |
if not noded_cert.endswith("\n"): |
464 |
noded_cert += "\n"
|
465 |
if not rapi_cert.endswith("\n"): |
466 |
rapi_cert += "\n"
|
467 |
if not confd_hmac_key.endswith("\n"): |
468 |
confd_hmac_key += "\n"
|
469 |
|
470 |
# set up inter-node password and certificate and restarts the node daemon
|
471 |
# and then connect with ssh to set password and start ganeti-noded
|
472 |
# note that all the below variables are sanitized at this point,
|
473 |
# either by being constants or by the checks above
|
474 |
# TODO: Could this command exceed a shell's maximum command length?
|
475 |
mycommand = ("umask 077 && "
|
476 |
"cat > '%s' << '!EOF.' && \n"
|
477 |
"%s!EOF.\n"
|
478 |
"cat > '%s' << '!EOF.' && \n"
|
479 |
"%s!EOF.\n"
|
480 |
"cat > '%s' << '!EOF.' && \n"
|
481 |
"%s!EOF.\n"
|
482 |
"chmod 0400 %s %s %s && "
|
483 |
"%s start %s" %
|
484 |
(constants.NODED_CERT_FILE, noded_cert, |
485 |
constants.RAPI_CERT_FILE, rapi_cert, |
486 |
constants.CONFD_HMAC_KEY, confd_hmac_key, |
487 |
constants.NODED_CERT_FILE, constants.RAPI_CERT_FILE, |
488 |
constants.CONFD_HMAC_KEY, |
489 |
constants.DAEMON_UTIL, constants.NODED)) |
490 |
|
491 |
result = sshrunner.Run(node, 'root', mycommand, batch=False, |
492 |
ask_key=ssh_key_check, |
493 |
use_cluster_key=False,
|
494 |
strict_host_check=ssh_key_check) |
495 |
if result.failed:
|
496 |
raise errors.OpExecError("Remote command on node %s, error: %s," |
497 |
" output: %s" %
|
498 |
(node, result.fail_reason, result.output)) |
499 |
|
500 |
_WaitForNodeDaemon(node) |
501 |
|
502 |
|
503 |
def MasterFailover(no_voting=False): |
504 |
"""Failover the master node.
|
505 |
|
506 |
This checks that we are not already the master, and will cause the
|
507 |
current master to cease being master, and the non-master to become
|
508 |
new master.
|
509 |
|
510 |
@type no_voting: boolean
|
511 |
@param no_voting: force the operation without remote nodes agreement
|
512 |
(dangerous)
|
513 |
|
514 |
"""
|
515 |
sstore = ssconf.SimpleStore() |
516 |
|
517 |
old_master, new_master = ssconf.GetMasterAndMyself(sstore) |
518 |
node_list = sstore.GetNodeList() |
519 |
mc_list = sstore.GetMasterCandidates() |
520 |
|
521 |
if old_master == new_master:
|
522 |
raise errors.OpPrereqError("This commands must be run on the node" |
523 |
" where you want the new master to be."
|
524 |
" %s is already the master" %
|
525 |
old_master, errors.ECODE_INVAL) |
526 |
|
527 |
if new_master not in mc_list: |
528 |
mc_no_master = [name for name in mc_list if name != old_master] |
529 |
raise errors.OpPrereqError("This node is not among the nodes marked" |
530 |
" as master candidates. Only these nodes"
|
531 |
" can become masters. Current list of"
|
532 |
" master candidates is:\n"
|
533 |
"%s" % ('\n'.join(mc_no_master)), |
534 |
errors.ECODE_STATE) |
535 |
|
536 |
if not no_voting: |
537 |
vote_list = GatherMasterVotes(node_list) |
538 |
|
539 |
if vote_list:
|
540 |
voted_master = vote_list[0][0] |
541 |
if voted_master is None: |
542 |
raise errors.OpPrereqError("Cluster is inconsistent, most nodes did" |
543 |
" not respond.", errors.ECODE_ENVIRON)
|
544 |
elif voted_master != old_master:
|
545 |
raise errors.OpPrereqError("I have a wrong configuration, I believe" |
546 |
" the master is %s but the other nodes"
|
547 |
" voted %s. Please resync the configuration"
|
548 |
" of this node." %
|
549 |
(old_master, voted_master), |
550 |
errors.ECODE_STATE) |
551 |
# end checks
|
552 |
|
553 |
rcode = 0
|
554 |
|
555 |
logging.info("Setting master to %s, old master: %s", new_master, old_master)
|
556 |
|
557 |
result = rpc.RpcRunner.call_node_stop_master(old_master, True)
|
558 |
msg = result.fail_msg |
559 |
if msg:
|
560 |
logging.error("Could not disable the master role on the old master"
|
561 |
" %s, please disable manually: %s", old_master, msg)
|
562 |
|
563 |
master_ip = sstore.GetMasterIP() |
564 |
total_timeout = 30
|
565 |
# Here we have a phase where no master should be running
|
566 |
def _check_ip(): |
567 |
if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
|
568 |
raise utils.RetryAgain()
|
569 |
|
570 |
try:
|
571 |
utils.Retry(_check_ip, (1, 1.5, 5), total_timeout) |
572 |
except utils.RetryTimeout:
|
573 |
logging.warning("The master IP is still reachable after %s seconds,"
|
574 |
" continuing but activating the master on the current"
|
575 |
" node will probably fail", total_timeout)
|
576 |
|
577 |
# instantiate a real config writer, as we now know we have the
|
578 |
# configuration data
|
579 |
cfg = config.ConfigWriter() |
580 |
|
581 |
cluster_info = cfg.GetClusterInfo() |
582 |
cluster_info.master_node = new_master |
583 |
# this will also regenerate the ssconf files, since we updated the
|
584 |
# cluster info
|
585 |
cfg.Update(cluster_info, logging.error) |
586 |
|
587 |
result = rpc.RpcRunner.call_node_start_master(new_master, True, no_voting)
|
588 |
msg = result.fail_msg |
589 |
if msg:
|
590 |
logging.error("Could not start the master role on the new master"
|
591 |
" %s, please check: %s", new_master, msg)
|
592 |
rcode = 1
|
593 |
|
594 |
return rcode
|
595 |
|
596 |
|
597 |
def GetMaster(): |
598 |
"""Returns the current master node.
|
599 |
|
600 |
This is a separate function in bootstrap since it's needed by
|
601 |
gnt-cluster, and instead of importing directly ssconf, it's better
|
602 |
to abstract it in bootstrap, where we do use ssconf in other
|
603 |
functions too.
|
604 |
|
605 |
"""
|
606 |
sstore = ssconf.SimpleStore() |
607 |
|
608 |
old_master, _ = ssconf.GetMasterAndMyself(sstore) |
609 |
|
610 |
return old_master
|
611 |
|
612 |
|
613 |
def GatherMasterVotes(node_list): |
614 |
"""Check the agreement on who is the master.
|
615 |
|
616 |
This function will return a list of (node, number of votes), ordered
|
617 |
by the number of votes. Errors will be denoted by the key 'None'.
|
618 |
|
619 |
Note that the sum of votes is the number of nodes this machine
|
620 |
knows, whereas the number of entries in the list could be different
|
621 |
(if some nodes vote for another master).
|
622 |
|
623 |
We remove ourselves from the list since we know that (bugs aside)
|
624 |
since we use the same source for configuration information for both
|
625 |
backend and boostrap, we'll always vote for ourselves.
|
626 |
|
627 |
@type node_list: list
|
628 |
@param node_list: the list of nodes to query for master info; the current
|
629 |
node will be removed if it is in the list
|
630 |
@rtype: list
|
631 |
@return: list of (node, votes)
|
632 |
|
633 |
"""
|
634 |
myself = utils.HostInfo().name |
635 |
try:
|
636 |
node_list.remove(myself) |
637 |
except ValueError: |
638 |
pass
|
639 |
if not node_list: |
640 |
# no nodes left (eventually after removing myself)
|
641 |
return []
|
642 |
results = rpc.RpcRunner.call_master_info(node_list) |
643 |
if not isinstance(results, dict): |
644 |
# this should not happen (unless internal error in rpc)
|
645 |
logging.critical("Can't complete rpc call, aborting master startup")
|
646 |
return [(None, len(node_list))] |
647 |
votes = {} |
648 |
for node in results: |
649 |
nres = results[node] |
650 |
data = nres.payload |
651 |
msg = nres.fail_msg |
652 |
fail = False
|
653 |
if msg:
|
654 |
logging.warning("Error contacting node %s: %s", node, msg)
|
655 |
fail = True
|
656 |
elif not isinstance(data, (tuple, list)) or len(data) < 3: |
657 |
logging.warning("Invalid data received from node %s: %s", node, data)
|
658 |
fail = True
|
659 |
if fail:
|
660 |
if None not in votes: |
661 |
votes[None] = 0 |
662 |
votes[None] += 1 |
663 |
continue
|
664 |
master_node = data[2]
|
665 |
if master_node not in votes: |
666 |
votes[master_node] = 0
|
667 |
votes[master_node] += 1
|
668 |
|
669 |
vote_list = [v for v in votes.items()] |
670 |
# sort first on number of votes then on name, since we want None
|
671 |
# sorted later if we have the half of the nodes not responding, and
|
672 |
# half voting all for the same master
|
673 |
vote_list.sort(key=lambda x: (x[1], x[0]), reverse=True) |
674 |
|
675 |
return vote_list
|