-
Notifications
You must be signed in to change notification settings - Fork 158
/
topology.py
2368 lines (2060 loc) · 102 KB
/
topology.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
"""
This module contains abstractions of MySQL replication functionality.
"""
import sys
import logging
import time
import operator
import os
from multiprocessing.pool import ThreadPool
from mysql.utilities.exception import FormatError, UtilError, UtilRplError
from mysql.utilities.common.lock import Lock
from mysql.utilities.common.my_print_defaults import MyDefaultsReader
from mysql.utilities.common.ip_parser import parse_connection
from mysql.utilities.common.options import parse_user_password
from mysql.utilities.common.replication import Master, Slave, Replication
from mysql.utilities.common.tools import execute_script
from mysql.utilities.common.format import print_list
from mysql.utilities.common.user import User
from mysql.utilities.common.server import (get_server_state, get_server,
get_connection_dictionary,
log_server_version, Server)
from mysql.utilities.common.messages import USER_PASSWORD_FORMAT
_HEALTH_COLS = ["host", "port", "role", "state", "gtid_mode", "health"]
_HEALTH_DETAIL_COLS = ["version", "master_log_file", "master_log_pos",
"IO_Thread", "SQL_Thread", "Secs_Behind",
"Remaining_Delay", "IO_Error_Num", "IO_Error",
"SQL_Error_Num", "SQL_Error", "Trans_Behind"]
_GTID_EXECUTED = "SELECT @@GLOBAL.GTID_EXECUTED"
_GTID_WAIT = "SELECT WAIT_UNTIL_SQL_THREAD_AFTER_GTIDS('%s', %s)"
_GTID_SUBTRACT_TO_EXECUTED = ("SELECT GTID_SUBTRACT('{0}', "
"@@GLOBAL.GTID_EXECUTED)")
_UPDATE_RPL_USER_QUERY = ("UPDATE mysql.user "
"SET password = PASSWORD('{passwd}')"
"where user ='{user}'")
# Query for server versions >= 5.7.6.
_UPDATE_RPL_USER_QUERY_5_7_6 = (
"ALTER USER IF EXISTS '{user}'@'{host}' IDENTIFIED BY '{passwd}'")
_SELECT_RPL_USER_PASS_QUERY = ("SELECT user, host, grant_priv, password, "
"Repl_slave_priv FROM mysql.user "
"WHERE user ='{user}' AND host ='{host}'")
# Query for server versions >= 5.7.6.
_SELECT_RPL_USER_PASS_QUERY_5_7_6 = (
"SELECT user, host, grant_priv, authentication_string, "
"Repl_slave_priv FROM mysql.user WHERE user ='{user}' AND host ='{host}'")
def parse_topology_connections(options, parse_candidates=True):
"""Parse the --master, --slaves, and --candidates options
This method returns a tuple with server connection dictionaries for
the master, slaves, and candidates lists.
If no master, will return (None, ...) for master element.
If no slaves, will return (..., [], ...) for slaves element.
If no canidates, will return (..., ..., []) for canidates element.
Will raise error if cannot parse connection options.
options[in] options from parser
Returns tuple - (master, slaves, candidates) dictionaries
"""
try:
timeout = options.conn_timeout
except:
timeout = None
if timeout and options.verbosity > 2:
print("Note: running with --connection-timeout={0}".format(timeout))
# Create a basic configuration reader, without looking for the tool
# my_print_defaults to avoid raising exceptions. This is used for
# optimization purposes, to reuse data and avoid repeating the execution of
# some methods in the parse_connection method (e.g. searching for
# my_print_defaults).
config_reader = MyDefaultsReader(options, False)
if options.master:
try:
master_val = parse_connection(options.master, config_reader,
options)
# Add connection timeout if present in options
if timeout:
master_val['connection_timeout'] = timeout
except FormatError as err:
msg = ("Master connection values invalid or cannot be parsed: %s "
"(%s)." % (options.master, err))
raise UtilRplError(msg)
except UtilError as err:
msg = ("Master connection values invalid or cannot be parsed: %s "
"(using login-path authentication: %s)" % (options.master,
err.errmsg))
raise UtilRplError(msg)
else:
master_val = None
slaves_val = []
if options.slaves:
slaves = options.slaves.split(",")
for slave in slaves:
try:
s_values = parse_connection(slave, config_reader, options)
# Add connection timeout if present in options
if timeout:
s_values['connection_timeout'] = timeout
slaves_val.append(s_values)
except FormatError as err:
msg = ("Slave connection values invalid or cannot be parsed: "
"%s (%s)" % (slave, err))
raise UtilRplError(msg)
except UtilError as err:
msg = ("Slave connection values invalid or cannot be parsed: "
"%s (%s)" % (slave, err.errmsg))
raise UtilRplError(msg)
candidates_val = []
if parse_candidates and options.candidates:
candidates = options.candidates.split(",")
for slave in candidates:
try:
s_values = parse_connection(slave, config_reader, options)
# Add connection timeout if present in options
if timeout:
s_values['connection_timeout'] = timeout
candidates_val.append(s_values)
except FormatError as err:
msg = "Candidate connection values invalid or " + \
"cannot be parsed: %s (%s)" % (slave, err)
raise UtilRplError(msg)
except UtilError as err:
msg = ("Candidate connection values invalid or cannot be "
"parsed: %s (%s)" % (slave, err.errmsg))
raise UtilRplError(msg)
return (master_val, slaves_val, candidates_val)
class Topology(Replication):
"""The Topology class supports administrative operations for an existing
master-to-many slave topology. It has the following capabilities:
- determine the health of the topology
- discover slaves connected to the master provided they have
--report-host and --report-port specified
- switchover from master to a candidate slave
- demote the master to a slave in the topology
- perform best slave election
- failover to a specific slave or best of slaves available
Notes:
- the switchover and demote methods work with versions prior to and
after 5.6.5.
- failover and best slave election require version 5.6.5 and later
and GTID_MODE=ON.
"""
def __init__(self, master_vals, slave_vals, options=None,
skip_conn_err=False):
"""Constructor
The slaves parameter requires a dictionary in the form:
master_vals[in] master server connection dictionary
slave_vals[in] list of slave server connection dictionaries
options[in] options dictionary
verbose print extra data during operations (optional)
Default = False
ping maximum number of seconds to ping
Default = 3
max_delay maximum delay in seconds slave and be behind
master and still be 'Ok'. Default = 0
max_position maximum position slave can be behind master's
binlog and still be 'Ok'. Default = 0
skip_conn_err[in] if True, do not fail on connection failure
Default = True
"""
super(Topology, self).__init__(master_vals, slave_vals, options or {})
# Get options needed
self.options = options or {}
self.verbosity = options.get("verbosity", 0)
self.verbose = self.verbosity > 0
self.quiet = self.options.get("quiet", False)
self.pingtime = self.options.get("ping", 3)
self.max_delay = self.options.get("max_delay", 0)
self.max_pos = self.options.get("max_position", 0)
self.force = self.options.get("force", False)
self.pedantic = self.options.get("pedantic", False)
self.before_script = self.options.get("before", None)
self.after_script = self.options.get("after", None)
self.timeout = int(self.options.get("timeout", 300))
self.logging = self.options.get("logging", False)
self.rpl_user = self.options.get("rpl_user", None)
self.script_threshold = self.options.get("script_threshold", None)
self.master_vals = None
# Attempt to connect to all servers
self.master, self.slaves = self._connect_to_servers(master_vals,
slave_vals,
self.options,
skip_conn_err)
self.discover_slaves(output_log=True)
def _report(self, message, level=logging.INFO, print_msg=True):
"""Log message if logging is on
This method will log the message presented if the log is turned on.
Specifically, if options['log_file'] is not None. It will also
print the message to stdout.
message[in] message to be printed
level[in] level of message to log. Default = INFO
print_msg[in] if True, print the message to stdout. Default = True
"""
# First, print the message.
if print_msg and not self.quiet:
print message
# Now log message if logging turned on
if self.logging:
logging.log(int(level), message.strip("#").strip(' '))
def _connect_to_servers(self, master_vals, slave_vals, options,
skip_conn_err=True):
"""Connect to the master and one or more slaves
This method will attempt to connect to the master and slaves provided.
For slaves, if the --force option is specified, it will skip slaves
that cannot be reached setting the slave dictionary to None
in the list instead of a Slave class instance.
The dictionary of the list of slaves returns is as follows.
slave_dict = {
'host' : # host name for slave
'port' : # port for slave
'instance' : Slave class instance or None if cannot connect
}
master_vals[in] master server connection dictionary
slave_vals[in] list of slave server connection dictionaries
options[in] options dictionary
verbose print extra data during operations (optional)
Default = False
ping maximum number of seconds to ping
Default = 3
max_delay maximum delay in seconds slave and be behind
master and still be 'Ok'. Default = 0
max_position maximum position slave can be behind master's
binlog and still be 'Ok'. Default = 0
skip_conn_err[in] if True, do not fail on connection failure
Default = True
Returns tuple - master instance, list of dictionary slave instances
"""
master = None
slaves = []
# Set verbose value.
verbose = self.options.get("verbosity", 0) > 0
# attempt to connect to the master
if master_vals:
master = get_server('master', master_vals, True, verbose=verbose)
if self.logging:
log_server_version(master)
for slave_val in slave_vals:
host = slave_val['host']
port = slave_val['port']
try:
slave = get_server('slave', slave_val, True, verbose=verbose)
if self.logging:
log_server_version(slave)
except:
msg = "Cannot connect to slave %s:%s as user '%s'." % \
(host, port, slave_val['user'])
if skip_conn_err:
if self.verbose:
self._report("# ERROR: %s" % msg, logging.ERROR)
slave = None
else:
raise UtilRplError(msg)
slave_dict = {
'host': host, # host name for slave
'port': port, # port for slave
'instance': slave, # Slave class instance or None
}
slaves.append(slave_dict)
return (master, slaves)
def _is_connected(self):
"""Check to see if all servers are connected.
Method will skip any slaves that do not have an instance (offline)
but requires the master be instantiated and connected.
The method will also skip the checks altogether if self.force is
specified.
Returns bool - True if all connected or self.force is specified.
"""
# Skip check if --force specified.
if self.force:
return True
if self.master is None or not self.master.is_alive():
return False
for slave_dict in self.slaves:
slave = slave_dict['instance']
if slave is not None and not slave.is_alive():
return False
return True
def remove_discovered_slaves(self):
"""Reset the slaves list to the original list at instantiation
This method is used in conjunction with discover_slaves to remove
any discovered slave from the slaves list. Once this is done,
a call to discover slaves will rediscover the slaves. This is helpful
for when failover occurs and a discovered slave is used for the new
master.
"""
new_list = []
for slave_dict in self.slaves:
if not slave_dict.get("discovered", False):
new_list.append(slave_dict)
self.slaves = new_list
def check_master_info_type(self, repo="TABLE"):
"""Check all slaves for master_info_repository=repo
repo[in] value for master info = "TABLE" or "FILE"
Default is "TABLE"
Returns bool - True if master_info_repository == repo
"""
for slave_dict in self.slaves:
slave = slave_dict['instance']
if slave is not None:
res = slave.show_server_variable("master_info_repository")
if not res or res[0][1].upper() != repo.upper():
return False
return True
def discover_slaves(self, skip_conn_err=True, output_log=False):
"""Discover slaves connected to the master
skip_conn_err[in] Skip connection errors to the slaves (i.e. log the
errors but do not raise an exception),
by default True.
output_log[in] Output the logged information (i.e. print the
information of discovered slave to the output),
by default False.
Returns bool - True if new slaves found
"""
# See if the user wants us to discover slaves.
discover = self.options.get("discover", None)
if not discover or not self.master:
return
# Get user and password (support login-path)
try:
user, password = parse_user_password(discover,
options=self.options)
except FormatError:
raise UtilError(USER_PASSWORD_FORMAT.format("--discover-slaves"))
# Find discovered slaves
new_slaves_found = False
self._report("# Discovering slaves for master at "
"{0}:{1}".format(self.master.host, self.master.port))
discovered_slaves = self.master.get_slaves(user, password)
# pylint: disable=R0101
for slave in discovered_slaves:
if "]" in slave:
host, port = slave.split("]:")
host = "{0}]".format(host)
else:
host, port = slave.split(":")
msg = "Discovering slave at {0}:{1}".format(host, port)
self._report(msg, logging.INFO, False)
if output_log:
print("# {0}".format(msg))
# Skip hosts that are not registered properly
if host == 'unknown host':
continue
# Check to see if the slave is already in the list
else:
found = False
# Eliminate if already a slave
for slave_dict in self.slaves:
if slave_dict['host'] == host and \
int(slave_dict['port']) == int(port):
found = True
break
if not found:
# Now we must attempt to connect to the slave.
conn_dict = {
'conn_info': {'user': user, 'passwd': password,
'host': host, 'port': port,
'socket': None,
'ssl_ca': self.master.ssl_ca,
'ssl_cert': self.master.ssl_cert,
'ssl_key': self.master.ssl_key,
'ssl': self.master.ssl},
'role': slave,
'verbose': self.options.get("verbosity", 0) > 0,
}
slave_conn = Slave(conn_dict)
try:
slave_conn.connect()
# Skip discovered slaves that are not connected
# to the master (i.e. IO thread is not running)
if slave_conn.is_connected():
self.slaves.append({'host': host, 'port': port,
'instance': slave_conn,
'discovered': True})
msg = "Found slave: {0}:{1}".format(host, port)
self._report(msg, logging.INFO, False)
if output_log:
print("# {0}".format(msg))
if self.logging:
log_server_version(slave_conn)
new_slaves_found = True
else:
msg = ("Slave skipped (IO not running): "
"{0}:{1}").format(host, port)
self._report(msg, logging.WARN, False)
if output_log:
print("# {0}".format(msg))
except UtilError, e:
msg = ("Cannot connect to slave {0}:{1} as user "
"'{2}'.").format(host, port, user)
if skip_conn_err:
msg = "{0} {1}".format(msg, e.errmsg)
self._report(msg, logging.WARN, False)
if output_log:
print("# {0}".format(msg))
else:
raise UtilRplError(msg)
return new_slaves_found
def _get_server_gtid_data(self, server, role):
"""Retrieve the GTID information from the server.
This method builds a tuple of three lists corresponding to the three
GTID lists (executed, purged, owned) retrievable via the global
variables. It generates lists suitable for format and printing.
role[in] role of the server (used for report generation)
Returns tuple - (executed list, purged list, owned list)
"""
executed = []
purged = []
owned = []
if server.supports_gtid() == "NO":
return (executed, purged, owned)
try:
gtids = server.get_gtid_status()
except UtilError, e:
self._report("# ERROR retrieving GTID information: %s" % e.errmsg,
logging.ERROR)
return None
for gtid in gtids[0]:
for row in gtid.split("\n"):
if len(row):
executed.append((server.host, server.port, role,
row.strip(",")))
for gtid in gtids[1]:
for row in gtid.split("\n"):
if len(row):
purged.append((server.host, server.port, role,
row.strip(",")))
for gtid in gtids[2]:
for row in gtid.split("\n"):
if len(row):
owned.append((server.host, server.port, role,
row.strip(",")))
return (executed, purged, owned)
def _check_switchover_prerequisites(self, candidate=None):
"""Check prerequisites for performing switchover
This method checks the prerequisites for performing a switch from a
master to a candidate slave.
candidate[in] if supplied, use this candidate instead of the
candidate supplied by the user. Must be instance of
Master class.
Returns bool - True if success, raises error if not
"""
if candidate is None:
candidate = self.options.get("candidate", None)
assert (candidate is not None), "A candidate server is required."
assert (isinstance(candidate, Master)), \
"A candidate server must be a Master class instance."
# If master has GTID=ON, ensure all servers have GTID=ON
gtid_enabled = self.master.supports_gtid() == "ON"
if gtid_enabled:
gtid_ok = True
for slave_dict in self.slaves:
slave = slave_dict['instance']
# skip dead or zombie slaves
if not slave or not slave.is_alive():
continue
if slave.supports_gtid() != "ON":
gtid_ok = False
if not gtid_ok:
msg = "GTIDs are enabled on the master but not " + \
"on all of the slaves."
self._report(msg, logging.CRITICAL)
raise UtilRplError(msg)
elif self.verbose:
self._report("# GTID_MODE=ON is set for all servers.")
# Need Slave class instance to check master and replication user
slave = self._change_role(candidate)
# Check eligibility
candidate_ok = self._check_candidate_eligibility(slave.host,
slave.port,
slave)
if not candidate_ok[0]:
# Create replication user if --force is specified.
if self.force and candidate_ok[1] == "RPL_USER":
user, passwd = slave.get_rpl_user()
res = candidate.create_rpl_user(slave.host, slave.port,
user, passwd, self.ssl)
if not res[0]:
print("# ERROR: {0}".format(res[1]))
self._report(res[1], logging.CRITICAL, False)
else:
msg = candidate_ok[2]
self._report(msg, logging.CRITICAL)
raise UtilRplError(msg)
return True
def _get_rpl_user(self, server):
"""Get the replication user
This method returns the user and password for the replication user
as read from the Slave class.
Returns tuple - user, password
"""
# Get replication user from server if rpl_user not specified
if self.rpl_user is None:
slave = self._change_role(server)
user, passwd = slave.get_rpl_user()
return (user, passwd)
# Get user and password (support login-path)
try:
user, passwd = parse_user_password(self.rpl_user,
options=self.options)
except FormatError:
raise UtilError(USER_PASSWORD_FORMAT.format("--rpl-user"))
return (user, passwd)
def run_script(self, script, quiet, options=None):
"""Run an external script
This method executes an external script. Result is checked for
success (res == 0). If the user specified a threshold and the
threshold is exceeded, an error is raised.
script[in] script to execute
quiet[in] if True, do not print messages
options[in] options for script
Default is none (no options)
Returns bool - True = success
"""
if options is None:
options = []
if script is None:
return
self._report("# Spawning external script.")
res = execute_script(script, None, options, self.verbose)
if self.script_threshold and res >= int(self.script_threshold):
raise UtilRplError("External script '{0}' failed. Result = {1}.\n"
"Specified threshold exceeded. Operation abort"
"ed.\nWARNING: The operation did not complete."
" Depending on when the external script was "
"called, you should check the topology "
"for inconsistencies.".format(script, res))
if res == 0:
self._report("# Script completed Ok.")
elif not quiet:
self._report("ERROR: %s Script failed. Result = %s" %
(script, res), logging.ERROR)
def _check_filters(self, master, slave):
"""Check filters to ensure they are compatible with the master.
This method compares the binlog_do_db with the replicate_do_db and
the binlog_ignore_db with the replicate_ignore_db on the master and
slave to ensure the candidate slave is not filtering out different
databases than the master.
master[in] the Master class instance of the master
slave[in] the Slave class instance of the slave
Returns bool - True = filters agree
"""
m_filter = master.get_binlog_exceptions()
s_filter = slave.get_binlog_exceptions()
failed = False
if len(m_filter) != len(s_filter):
failed = True
elif len(m_filter) == 0:
return True
elif m_filter[0][1] != s_filter[0][1] or \
m_filter[0][2] != s_filter[0][2]:
failed = True
if failed:
if self.verbose and not self.quiet:
fmt = self.options.get("format", "GRID")
rows = []
if len(m_filter) == 0:
rows.append(('MASTER', '', ''))
else:
rows.append(m_filter[0])
if len(s_filter) == 0:
rows.append(('SLAVE', '', ''))
else:
rows.append(s_filter[0])
cols = ["role", "*_do_db", "*_ignore_db"]
self._report("# Filter Check Failed.", logging.ERROR)
print_list(sys.stdout, fmt, cols, rows)
return False
return True
def _check_candidate_eligibility(self, host, port, slave,
check_master=True, quiet=False):
"""Perform sanity checks for slave promotion
This method checks the slave candidate to ensure it meets the
requirements as follows.
Check Name Description
----------- --------------------------------------------------
CONNECTED slave is connected to the master
GTID slave has GTID_MODE = ON if master has GTID = ON
(GTID only)
BEHIND slave is not behind master
(non-GTID only)
FILTER slave's filters match the master
RPL_USER slave has rpl user defined
BINLOG slave must have binary logging enabled
host[in] host name for the slave (used for errors)
port[in] port for the slave (used for errors)
slave[in] Slave class instance of candidate
check_master[in] if True, check that slave is connected to the master
quiet[in] if True, do not print messages even if verbosity > 0
Returns tuple (bool, check_name, string) -
(True, "", "") = candidate is viable,
(False, check_name, error_message) = candidate is not viable
"""
assert (slave is not None), "No Slave instance for eligibility check."
gtid_enabled = slave.supports_gtid() == "ON"
# Is slave connected to master?
if self.verbose and not quiet:
self._report("# Checking eligibility of slave %s:%s for "
"candidate." % (host, port))
if check_master:
msg = "# Slave connected to master ... %s"
if not slave.is_alive():
if self.verbose and not quiet:
self._report(msg % "FAIL", logging.WARN)
return (False, "CONNECTED",
"Connection to slave server lost.")
if not slave.is_configured_for_master(self.master):
if self.verbose and not quiet:
self._report(msg % "FAIL", logging.WARN)
return (False, "CONNECTED",
"Candidate is not connected to the correct master.")
if self.verbose and not quiet:
self._report(msg % "Ok")
# If GTID is active on master, ensure slave is on too.
if gtid_enabled:
msg = "# GTID_MODE=ON ... %s"
if slave.supports_gtid() != "ON":
if self.verbose and not quiet:
self._report(msg % "FAIL", logging.WARN)
return (False, "GTID",
"Slave does not have GTID support enabled.")
if self.verbose and not quiet:
self._report(msg % "Ok")
# Check for slave behind master
if not gtid_enabled and check_master:
msg = "# Slave not behind master ... %s"
rpl = Replication(self.master, slave, self.options)
errors = rpl.check_slave_delay()
if errors != []:
if self.verbose and not quiet:
self._report(msg % "FAIL", logging.WARN)
return (False, "BEHIND", " ".join(errors))
if self.verbose and not quiet:
self._report(msg % "Ok")
# Check filters unless force is on.
if not self.force and check_master:
msg = "# Logging filters agree ... %s"
if not self._check_filters(self.master, slave):
if self.verbose and not quiet:
self._report(msg % "FAIL", logging.WARN)
return (False, "FILTERS",
"Master and slave filters differ.")
elif self.verbose and not quiet:
self._report(msg % "Ok")
# If no GTIDs, we need binary logging enabled on candidate.
if not gtid_enabled:
msg = "# Binary logging turned on ... %s"
if not slave.binlog_enabled():
if self.verbose and not quiet:
self._report(msg % "FAIL", logging.WARN)
return (False, "BINLOG",
"Binary logging is not enabled on the candidate.")
if self.verbose and not quiet:
self._report(msg % "Ok")
# Check replication user - must exist with correct privileges
try:
user, _ = slave.get_rpl_user()
except UtilError:
if not self.rpl_user:
raise
# Get user and password (support login-path)
try:
user, _ = parse_user_password(self.rpl_user)
except FormatError:
raise UtilError(USER_PASSWORD_FORMAT.format("--rpl-user"))
# Make new master forget was a slave using slave methods
s_candidate = self._change_role(slave, slave=False)
res = s_candidate.get_rpl_users()
l = len(res)
user, host, _ = res[l - 1]
# raise
msg = "# Replication user exists ... %s"
if user is None or slave.check_rpl_user(user, slave.host) != []:
if not self.force:
if self.verbose and not quiet:
self._report(msg % "FAIL", logging.WARN)
return (False, "RPL_USER",
"Candidate slave is missing replication user.")
else:
self._report("Replication user not found but --force used.",
logging.WARN)
elif self.verbose and not quiet:
self._report(msg % "Ok")
return (True, "", "")
def read_all_retrieved_gtids(self, slave):
"""Ensure any GTIDS in relay log are read
This method iterates over all slaves ensuring any events read from
the master but not executed (read) from the relay log are read.
This step is necessary for failover to ensure all transactions are
applied to all slaves before the new master is selected.
slave[in] Server instance of the slave
"""
# skip dead or zombie slaves
if slave is None or not slave.is_alive():
return
gtids = slave.get_retrieved_gtid_set()
if gtids:
if self.verbose and not self.quiet:
self._report("# Reading events in relay log for slave "
"%s:%s" % (slave.host, slave.port))
try:
slave.exec_query(_GTID_WAIT % (gtids.strip(','), self.timeout))
except UtilRplError as err:
raise UtilRplError("Error executing %s: %s" %
((_GTID_WAIT % (gtids.strip(','),
self.timeout)), err.errmsg))
def _has_missing_transactions(self, candidate, slave):
"""Determine if there are transactions on the slave not on candidate
This method uses the function gtid_subset() to determine if there are
GTIDs (transactions) on the slave that are not on the candidate.
Return code fopr query should be 0 when there are missing
transactions, 1 if not, and -1 if there is a non-numeric result
code generated.
candidate[in] Server instance of candidate (new master)
slave[in] Server instance of slave to check
Returns boolean - True if there are transactions else False
"""
slave_exec_gtids = slave.get_executed_gtid_set()
slave_retrieved_gtids = slave.get_retrieved_gtid_set()
cand_slave = self._change_role(candidate)
candidate_exec_gtids = cand_slave.get_executed_gtid_set()
slave_gtids = ",".join([slave_exec_gtids.strip(","),
slave_retrieved_gtids.strip(",")])
res = slave.exec_query("SELECT gtid_subset('%s', '%s')" %
(slave_gtids, candidate_exec_gtids.strip(",")))
if res and res[0][0].isdigit():
result_code = int(res[0][0])
else:
result_code = -1
if self.verbose and not self.quiet:
if result_code != 1:
self._report("# Missing transactions found on %s:%s. "
"SELECT gtid_subset() = %s" %
(slave.host, slave.port, result_code))
else:
self._report("# No missing transactions found on %s:%s. "
"Skipping connection of candidate as slave." %
(slave.host, slave.port))
return result_code != 1
def _prepare_candidate_for_failover(self, candidate, user, passwd=""):
"""Prepare candidate slave for slave promotion (in failover)
This method uses the candidate slave specified and connects it to
each slave in the topology performing a GTID_SUBSET query to wait
for the candidate (acting as a slave) to catch up. This ensures
the candidate is now the 'best' or 'most up-to-date' slave in the
topology.
Method works only for GTID-enabled candidate servers.
candidate[in] Slave class instance of candidate
user[in] replication user
passwd[in] replication user password
Returns bool - True if successful,
raises exception if failure and forst is False
"""
assert (candidate is not None), "Candidate must be a Slave instance."
if candidate.supports_gtid() != "ON":
msg = "Candidate does not have GTID turned on or " + \
"does not support GTIDs."
self._report(msg, logging.CRITICAL)
raise UtilRplError(msg)
lock_options = {
'locking': 'flush',
'verbosity': 3 if self.verbose else self.verbosity,
'silent': self.quiet,
'rpl_mode': "master",
}
hostport = "%s:%s" % (candidate.host, candidate.port)
for slave_dict in self.slaves:
s_host = slave_dict['host']
s_port = slave_dict['port']
temp_master = slave_dict['instance']
# skip dead or zombie slaves
if temp_master is None or not temp_master.is_alive():
continue
# Gather retrieved_gtid_set to execute all events on slaves still
# in the slave's relay log
self.read_all_retrieved_gtids(temp_master)
# Sanity check: ensure candidate and slave are not the same.
if candidate.is_alias(s_host) and \
int(s_port) == int(candidate.port):
continue
# Check for missing transactions. No need to connect to slave if
# there are no transactions (GTIDs) to retrieve
if not self._has_missing_transactions(candidate, temp_master):
continue
try:
candidate.stop()
except UtilError as err:
if not self.quiet:
self._report("Candidate {0} failed to stop. "
"{1}".format(hostport, err.errmsg))
# Block writes to slave (temp_master)
lock_ftwrl = Lock(temp_master, [], lock_options)
temp_master.set_read_only(True)
if self.verbose and not self.quiet:
read_only = temp_master.show_server_variable("READ_ONLY")
self._report("# Read only is {0} for {1}:{2}."
"".format(read_only[0][1], temp_master.host,
temp_master.port))
# Connect candidate to slave as its temp_master
if self.verbose and not self.quiet:
self._report("# Connecting candidate to %s:%s as a temporary "
"slave to retrieve unprocessed GTIDs." %
(s_host, s_port))
if not candidate.switch_master(temp_master, user, passwd, False,
None, None,
self.verbose and not self.quiet):
msg = "Cannot switch candidate to slave for " + \
"slave promotion process."
self._report(msg, logging.CRITICAL)
raise UtilRplError(msg)
# Unblock writes to slave (temp_master).
temp_master.set_read_only(False)
if self.verbose and not self.quiet:
read_only = temp_master.show_server_variable("READ_ONLY")
self._report("# Read only is {0} for {1}:{2}."
"".format(read_only[0][1], temp_master.host,
temp_master.port))
lock_ftwrl.unlock()
try:
candidate.start()
candidate.exec_query("COMMIT")
except UtilError as err:
if not self.quiet:
self._report("Candidate {0} failed to start. "
"{1}".format(hostport, err.errmsg))
if self.verbose and not self.quiet:
self._report("# Waiting for candidate to catch up to slave "
"%s:%s." % (s_host, s_port))
temp_master_gtid = temp_master.exec_query(_GTID_EXECUTED)
candidate.wait_for_slave_gtid(temp_master_gtid, self.timeout,
self.verbose and not self.quiet)
# Disconnect candidate from slave (temp_master)
candidate.stop()
return True
def _check_slaves_status(self, stop_on_error=False):
"""Check all slaves for error before performing failover.
This method check the status of all slaves (before the new master catch
up with them), using SHOW SLAVE STATUS, reporting any error found and
warning the user if failover might result in an inconsistent
replication topology. By default the process will not stop, but if
the --pedantic option is used then failover will stop with an error.
stop_on_error[in] Define the default behavior of failover if errors
are found. By default: False (not stop on errors).
"""
for slave_dict in self.slaves:
s_host = slave_dict['host']
s_port = slave_dict['port']