Statistics
| Branch: | Tag: | Revision:

root / lib / bootstrap.py @ bf4af505

History | View | Annotate | Download (24.5 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, default_iallocator=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
  if default_iallocator is not None:
337
    alloc_script = utils.FindFile(default_iallocator,
338
                                  constants.IALLOCATOR_SEARCH_PATH,
339
                                  os.path.isfile)
340
    if alloc_script is None:
341
      raise errors.OpPrereqError("Invalid default iallocator script '%s'"
342
                                 " specified" % default_iallocator,
343
                                 errors.ECODE_INVAL)
344

    
345
  now = time.time()
346

    
347
  # init of cluster config file
348
  cluster_config = objects.Cluster(
349
    serial_no=1,
350
    rsahostkeypub=sshkey,
351
    highest_used_port=(constants.FIRST_DRBD_PORT - 1),
352
    mac_prefix=mac_prefix,
353
    volume_group_name=vg_name,
354
    tcpudp_port_pool=set(),
355
    master_node=hostname.name,
356
    master_ip=clustername.ip,
357
    master_netdev=master_netdev,
358
    cluster_name=clustername.name,
359
    file_storage_dir=file_storage_dir,
360
    enabled_hypervisors=enabled_hypervisors,
361
    beparams={constants.PP_DEFAULT: beparams},
362
    nicparams={constants.PP_DEFAULT: nicparams},
363
    hvparams=hvparams,
364
    candidate_pool_size=candidate_pool_size,
365
    modify_etc_hosts=modify_etc_hosts,
366
    modify_ssh_setup=modify_ssh_setup,
367
    uid_pool=uid_pool,
368
    ctime=now,
369
    mtime=now,
370
    uuid=utils.NewUUID(),
371
    maintain_node_health=maintain_node_health,
372
    drbd_usermode_helper=drbd_helper,
373
    default_iallocator=default_iallocator,
374
    )
375
  master_node_config = objects.Node(name=hostname.name,
376
                                    primary_ip=hostname.ip,
377
                                    secondary_ip=secondary_ip,
378
                                    serial_no=1,
379
                                    master_candidate=True,
380
                                    offline=False, drained=False,
381
                                    )
382
  InitConfig(constants.CONFIG_VERSION, cluster_config, master_node_config)
383
  cfg = config.ConfigWriter()
384
  ssh.WriteKnownHostsFile(cfg, constants.SSH_KNOWN_HOSTS_FILE)
385
  cfg.Update(cfg.GetClusterInfo(), logging.error)
386

    
387
  # start the master ip
388
  # TODO: Review rpc call from bootstrap
389
  # TODO: Warn on failed start master
390
  rpc.RpcRunner.call_node_start_master(hostname.name, True, False)
391

    
392

    
393
def InitConfig(version, cluster_config, master_node_config,
394
               cfg_file=constants.CLUSTER_CONF_FILE):
395
  """Create the initial cluster configuration.
396

397
  It will contain the current node, which will also be the master
398
  node, and no instances.
399

400
  @type version: int
401
  @param version: configuration version
402
  @type cluster_config: L{objects.Cluster}
403
  @param cluster_config: cluster configuration
404
  @type master_node_config: L{objects.Node}
405
  @param master_node_config: master node configuration
406
  @type cfg_file: string
407
  @param cfg_file: configuration file path
408

409
  """
410
  nodes = {
411
    master_node_config.name: master_node_config,
412
    }
413

    
414
  now = time.time()
415
  config_data = objects.ConfigData(version=version,
416
                                   cluster=cluster_config,
417
                                   nodes=nodes,
418
                                   instances={},
419
                                   serial_no=1,
420
                                   ctime=now, mtime=now)
421
  utils.WriteFile(cfg_file,
422
                  data=serializer.Dump(config_data.ToDict()),
423
                  mode=0600)
424

    
425

    
426
def FinalizeClusterDestroy(master):
427
  """Execute the last steps of cluster destroy
428

429
  This function shuts down all the daemons, completing the destroy
430
  begun in cmdlib.LUDestroyOpcode.
431

432
  """
433
  cfg = config.ConfigWriter()
434
  modify_ssh_setup = cfg.GetClusterInfo().modify_ssh_setup
435
  result = rpc.RpcRunner.call_node_stop_master(master, True)
436
  msg = result.fail_msg
437
  if msg:
438
    logging.warning("Could not disable the master role: %s", msg)
439
  result = rpc.RpcRunner.call_node_leave_cluster(master, modify_ssh_setup)
440
  msg = result.fail_msg
441
  if msg:
442
    logging.warning("Could not shutdown the node daemon and cleanup"
443
                    " the node: %s", msg)
444

    
445

    
446
def SetupNodeDaemon(cluster_name, node, ssh_key_check):
447
  """Add a node to the cluster.
448

449
  This function must be called before the actual opcode, and will ssh
450
  to the remote node, copy the needed files, and start ganeti-noded,
451
  allowing the master to do the rest via normal rpc calls.
452

453
  @param cluster_name: the cluster name
454
  @param node: the name of the new node
455
  @param ssh_key_check: whether to do a strict key check
456

457
  """
458
  sshrunner = ssh.SshRunner(cluster_name)
459

    
460
  noded_cert = utils.ReadFile(constants.NODED_CERT_FILE)
461
  rapi_cert = utils.ReadFile(constants.RAPI_CERT_FILE)
462
  confd_hmac_key = utils.ReadFile(constants.CONFD_HMAC_KEY)
463

    
464
  # in the base64 pem encoding, neither '!' nor '.' are valid chars,
465
  # so we use this to detect an invalid certificate; as long as the
466
  # cert doesn't contain this, the here-document will be correctly
467
  # parsed by the shell sequence below. HMAC keys are hexadecimal strings,
468
  # so the same restrictions apply.
469
  for content in (noded_cert, rapi_cert, confd_hmac_key):
470
    if re.search('^!EOF\.', content, re.MULTILINE):
471
      raise errors.OpExecError("invalid SSL certificate or HMAC key")
472

    
473
  if not noded_cert.endswith("\n"):
474
    noded_cert += "\n"
475
  if not rapi_cert.endswith("\n"):
476
    rapi_cert += "\n"
477
  if not confd_hmac_key.endswith("\n"):
478
    confd_hmac_key += "\n"
479

    
480
  # set up inter-node password and certificate and restarts the node daemon
481
  # and then connect with ssh to set password and start ganeti-noded
482
  # note that all the below variables are sanitized at this point,
483
  # either by being constants or by the checks above
484
  # TODO: Could this command exceed a shell's maximum command length?
485
  mycommand = ("umask 077 && "
486
               "cat > '%s' << '!EOF.' && \n"
487
               "%s!EOF.\n"
488
               "cat > '%s' << '!EOF.' && \n"
489
               "%s!EOF.\n"
490
               "cat > '%s' << '!EOF.' && \n"
491
               "%s!EOF.\n"
492
               "chmod 0400 %s %s %s && "
493
               "%s start %s" %
494
               (constants.NODED_CERT_FILE, noded_cert,
495
                constants.RAPI_CERT_FILE, rapi_cert,
496
                constants.CONFD_HMAC_KEY, confd_hmac_key,
497
                constants.NODED_CERT_FILE, constants.RAPI_CERT_FILE,
498
                constants.CONFD_HMAC_KEY,
499
                constants.DAEMON_UTIL, constants.NODED))
500

    
501
  result = sshrunner.Run(node, 'root', mycommand, batch=False,
502
                         ask_key=ssh_key_check,
503
                         use_cluster_key=False,
504
                         strict_host_check=ssh_key_check)
505
  if result.failed:
506
    raise errors.OpExecError("Remote command on node %s, error: %s,"
507
                             " output: %s" %
508
                             (node, result.fail_reason, result.output))
509

    
510
  _WaitForNodeDaemon(node)
511

    
512

    
513
def MasterFailover(no_voting=False):
514
  """Failover the master node.
515

516
  This checks that we are not already the master, and will cause the
517
  current master to cease being master, and the non-master to become
518
  new master.
519

520
  @type no_voting: boolean
521
  @param no_voting: force the operation without remote nodes agreement
522
                      (dangerous)
523

524
  """
525
  sstore = ssconf.SimpleStore()
526

    
527
  old_master, new_master = ssconf.GetMasterAndMyself(sstore)
528
  node_list = sstore.GetNodeList()
529
  mc_list = sstore.GetMasterCandidates()
530

    
531
  if old_master == new_master:
532
    raise errors.OpPrereqError("This commands must be run on the node"
533
                               " where you want the new master to be."
534
                               " %s is already the master" %
535
                               old_master, errors.ECODE_INVAL)
536

    
537
  if new_master not in mc_list:
538
    mc_no_master = [name for name in mc_list if name != old_master]
539
    raise errors.OpPrereqError("This node is not among the nodes marked"
540
                               " as master candidates. Only these nodes"
541
                               " can become masters. Current list of"
542
                               " master candidates is:\n"
543
                               "%s" % ('\n'.join(mc_no_master)),
544
                               errors.ECODE_STATE)
545

    
546
  if not no_voting:
547
    vote_list = GatherMasterVotes(node_list)
548

    
549
    if vote_list:
550
      voted_master = vote_list[0][0]
551
      if voted_master is None:
552
        raise errors.OpPrereqError("Cluster is inconsistent, most nodes did"
553
                                   " not respond.", errors.ECODE_ENVIRON)
554
      elif voted_master != old_master:
555
        raise errors.OpPrereqError("I have a wrong configuration, I believe"
556
                                   " the master is %s but the other nodes"
557
                                   " voted %s. Please resync the configuration"
558
                                   " of this node." %
559
                                   (old_master, voted_master),
560
                                   errors.ECODE_STATE)
561
  # end checks
562

    
563
  rcode = 0
564

    
565
  logging.info("Setting master to %s, old master: %s", new_master, old_master)
566

    
567
  result = rpc.RpcRunner.call_node_stop_master(old_master, True)
568
  msg = result.fail_msg
569
  if msg:
570
    logging.error("Could not disable the master role on the old master"
571
                 " %s, please disable manually: %s", old_master, msg)
572

    
573
  master_ip = sstore.GetMasterIP()
574
  total_timeout = 30
575
  # Here we have a phase where no master should be running
576
  def _check_ip():
577
    if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
578
      raise utils.RetryAgain()
579

    
580
  try:
581
    utils.Retry(_check_ip, (1, 1.5, 5), total_timeout)
582
  except utils.RetryTimeout:
583
    logging.warning("The master IP is still reachable after %s seconds,"
584
                    " continuing but activating the master on the current"
585
                    " node will probably fail", total_timeout)
586

    
587
  # instantiate a real config writer, as we now know we have the
588
  # configuration data
589
  cfg = config.ConfigWriter()
590

    
591
  cluster_info = cfg.GetClusterInfo()
592
  cluster_info.master_node = new_master
593
  # this will also regenerate the ssconf files, since we updated the
594
  # cluster info
595
  cfg.Update(cluster_info, logging.error)
596

    
597
  result = rpc.RpcRunner.call_node_start_master(new_master, True, no_voting)
598
  msg = result.fail_msg
599
  if msg:
600
    logging.error("Could not start the master role on the new master"
601
                  " %s, please check: %s", new_master, msg)
602
    rcode = 1
603

    
604
  return rcode
605

    
606

    
607
def GetMaster():
608
  """Returns the current master node.
609

610
  This is a separate function in bootstrap since it's needed by
611
  gnt-cluster, and instead of importing directly ssconf, it's better
612
  to abstract it in bootstrap, where we do use ssconf in other
613
  functions too.
614

615
  """
616
  sstore = ssconf.SimpleStore()
617

    
618
  old_master, _ = ssconf.GetMasterAndMyself(sstore)
619

    
620
  return old_master
621

    
622

    
623
def GatherMasterVotes(node_list):
624
  """Check the agreement on who is the master.
625

626
  This function will return a list of (node, number of votes), ordered
627
  by the number of votes. Errors will be denoted by the key 'None'.
628

629
  Note that the sum of votes is the number of nodes this machine
630
  knows, whereas the number of entries in the list could be different
631
  (if some nodes vote for another master).
632

633
  We remove ourselves from the list since we know that (bugs aside)
634
  since we use the same source for configuration information for both
635
  backend and boostrap, we'll always vote for ourselves.
636

637
  @type node_list: list
638
  @param node_list: the list of nodes to query for master info; the current
639
      node will be removed if it is in the list
640
  @rtype: list
641
  @return: list of (node, votes)
642

643
  """
644
  myself = utils.HostInfo().name
645
  try:
646
    node_list.remove(myself)
647
  except ValueError:
648
    pass
649
  if not node_list:
650
    # no nodes left (eventually after removing myself)
651
    return []
652
  results = rpc.RpcRunner.call_master_info(node_list)
653
  if not isinstance(results, dict):
654
    # this should not happen (unless internal error in rpc)
655
    logging.critical("Can't complete rpc call, aborting master startup")
656
    return [(None, len(node_list))]
657
  votes = {}
658
  for node in results:
659
    nres = results[node]
660
    data = nres.payload
661
    msg = nres.fail_msg
662
    fail = False
663
    if msg:
664
      logging.warning("Error contacting node %s: %s", node, msg)
665
      fail = True
666
    elif not isinstance(data, (tuple, list)) or len(data) < 3:
667
      logging.warning("Invalid data received from node %s: %s", node, data)
668
      fail = True
669
    if fail:
670
      if None not in votes:
671
        votes[None] = 0
672
      votes[None] += 1
673
      continue
674
    master_node = data[2]
675
    if master_node not in votes:
676
      votes[master_node] = 0
677
    votes[master_node] += 1
678

    
679
  vote_list = [v for v in votes.items()]
680
  # sort first on number of votes then on name, since we want None
681
  # sorted later if we have the half of the nodes not responding, and
682
  # half voting all for the same master
683
  vote_list.sort(key=lambda x: (x[1], x[0]), reverse=True)
684

    
685
  return vote_list