-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathrpl_rli.cc
3553 lines (3095 loc) · 126 KB
/
rpl_rli.cc
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) 2006, 2024, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
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, version 2.0, 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 */
#include "sql/rpl_rli.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <algorithm>
#include <regex>
#include "mutex_lock.h" // Mutex_lock
#include "my_bitmap.h"
#include "my_dbug.h"
#include "my_dir.h" // MY_STAT
#include "my_sqlcommand.h"
#include "my_systime.h"
#include "my_thread.h"
#include "mysql/binlog/event/binlog_event.h"
#include "mysql/components/services/bits/psi_bits.h"
#include "mysql/components/services/bits/psi_stage_bits.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/plugin.h"
#include "mysql/psi/mysql_cond.h"
#include "mysql/psi/mysql_file.h"
#include "mysql/service_mysql_alloc.h"
#include "mysql/service_thd_wait.h"
#include "mysql/strings/int2str.h"
#include "mysql/strings/m_ctype.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "nulls.h"
#include "sql/auth/auth_acls.h" // SUPER_ACL
#include "sql/auth/roles.h" // Roles::Role_activation
#include "sql/auth/sql_auth_cache.h"
#include "sql/debug_sync.h"
#include "sql/derror.h"
#include "sql/log_event.h" // Log_event
#include "sql/mdl.h"
#include "sql/mysqld.h" // sync_relaylog_period ...
#include "sql/protocol.h"
#include "sql/rpl_info_factory.h" // Rpl_info_factory
#include "sql/rpl_info_handler.h"
#include "sql/rpl_mi.h" // Master_info
#include "sql/rpl_msr.h" // channel_map
#include "sql/rpl_relay_log_sanitizer.h"
#include "sql/rpl_replica.h"
#include "sql/rpl_reporting.h"
#include "sql/rpl_rli_pdb.h" // Slave_worker
#include "sql/rpl_trx_boundary_parser.h"
#include "sql/sql_base.h" // close_thread_tables
#include "sql/sql_error.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_plugin.h"
#include "sql/strfunc.h" // strconvert
#include "sql/transaction.h" // trans_commit_stmt
#include "sql/transaction_info.h"
#include "sql/xa.h"
#include "sql_string.h"
#include "string_with_len.h"
#include "strmake.h"
#include "thr_mutex.h"
class Item;
using std::max;
using std::min;
/*
Please every time you add a new field to the relay log info, update
what follows. For now, this is just used to get the number of
fields.
*/
const char *info_rli_fields[] = {
"number_of_lines",
"group_relay_log_name",
"group_relay_log_pos",
"group_source_log_name",
"group_source_log_pos",
"sql_delay",
"number_of_workers",
"id",
"channel_name",
"privilege_checks_user",
"privilege_checks_hostname",
"require_row_format",
"require_table_primary_key_check",
"assign_gtids_to_anonymous_transactions_type",
"assign_gtids_to_anonymous_transactions_value"};
Relay_log_info::Relay_log_info(bool is_slave_recovery,
#ifdef HAVE_PSI_INTERFACE
PSI_mutex_key *param_key_info_run_lock,
PSI_mutex_key *param_key_info_data_lock,
PSI_mutex_key *param_key_info_sleep_lock,
PSI_mutex_key *param_key_info_thd_lock,
PSI_mutex_key *param_key_info_data_cond,
PSI_mutex_key *param_key_info_start_cond,
PSI_mutex_key *param_key_info_stop_cond,
PSI_mutex_key *param_key_info_sleep_cond,
#endif
uint param_id, const char *param_channel,
bool is_rli_fake)
: Rpl_info("SQL",
#ifdef HAVE_PSI_INTERFACE
param_key_info_run_lock, param_key_info_data_lock,
param_key_info_sleep_lock, param_key_info_thd_lock,
param_key_info_data_cond, param_key_info_start_cond,
param_key_info_stop_cond, param_key_info_sleep_cond,
#endif
param_id, param_channel),
replicate_same_server_id(::replicate_same_server_id),
relay_log(&sync_relaylog_period, true),
is_relay_log_recovery(is_slave_recovery),
save_temporary_tables(nullptr),
mi(nullptr),
error_on_rli_init_info(false),
transaction_parser(mysql::binlog::event::Transaction_boundary_parser::
TRX_BOUNDARY_PARSER_APPLIER),
group_relay_log_pos(0),
event_relay_log_pos(0),
group_source_log_seen_start_pos(false),
group_source_log_start_pos(0),
group_source_log_end_pos(0),
event_start_pos(0),
group_master_log_pos(0),
gtid_set(nullptr),
rli_fake(is_rli_fake),
gtid_retrieved_initialized(false),
m_privilege_checks_username{""},
m_privilege_checks_hostname{""},
m_privilege_checks_user_corrupted{false},
m_require_row_format(false),
m_require_table_primary_key_check(PK_CHECK_STREAM),
m_is_applier_source_position_info_invalid(false),
is_group_master_log_pos_invalid(false),
log_space_total(0),
last_master_timestamp(0),
slave_skip_counter(0),
abort_pos_wait(0),
until_condition(UNTIL_NONE),
trans_retries(0),
retried_trans(0),
tables_to_lock(nullptr),
tables_to_lock_count(0),
rows_query_ev(nullptr),
last_event_start_time(0),
deferred_events(nullptr),
workers(PSI_NOT_INSTRUMENTED),
workers_array_initialized(false),
curr_group_assigned_parts(PSI_NOT_INSTRUMENTED),
curr_group_da(PSI_NOT_INSTRUMENTED),
curr_group_seen_begin(false),
mts_end_group_sets_max_dbs(false),
replica_parallel_workers(0),
exit_counter(0),
max_updated_index(0),
recovery_parallel_workers(0),
rli_checkpoint_seqno(0),
checkpoint_group(opt_mta_checkpoint_group),
recovery_groups_inited(false),
mts_recovery_group_cnt(0),
mts_recovery_index(0),
mts_recovery_group_seen_begin(false),
mts_group_status(MTS_NOT_IN_GROUP),
current_mts_submode(nullptr),
reported_unsafe_warning(false),
rli_description_event(nullptr),
commit_order_mngr(nullptr),
sql_delay(0),
sql_delay_end(0),
m_flags(0),
row_stmt_start_timestamp(0),
long_find_row_note_printed(false),
thd_tx_priority(0),
m_ignore_write_set_memory_limit(false),
m_allow_drop_write_set(false),
m_is_engine_ha_data_detached(false),
current_event(nullptr),
ddl_not_atomic(false) {
DBUG_TRACE;
#ifdef HAVE_PSI_INTERFACE
relay_log.set_psi_keys(
key_RELAYLOG_LOCK_index, key_RELAYLOG_LOCK_commit, PSI_NOT_INSTRUMENTED,
PSI_NOT_INSTRUMENTED, PSI_NOT_INSTRUMENTED, PSI_NOT_INSTRUMENTED,
PSI_NOT_INSTRUMENTED, key_RELAYLOG_LOCK_log,
key_RELAYLOG_LOCK_log_end_pos, key_RELAYLOG_LOCK_sync,
PSI_NOT_INSTRUMENTED, key_RELAYLOG_LOCK_xids, PSI_NOT_INSTRUMENTED,
PSI_NOT_INSTRUMENTED, PSI_NOT_INSTRUMENTED, PSI_NOT_INSTRUMENTED,
key_RELAYLOG_update_cond, PSI_NOT_INSTRUMENTED, PSI_NOT_INSTRUMENTED,
key_file_relaylog, key_file_relaylog_index, key_file_relaylog_cache,
key_file_relaylog_index_cache);
#endif
group_relay_log_name[0] = event_relay_log_name[0] = group_master_log_name[0] =
0;
ign_master_log_name_end[0] = 0;
set_timespec_nsec(&last_clock, 0);
cached_charset_invalidate();
inited_hash_workers = false;
commit_timestamps_status = COMMIT_TS_UNKNOWN;
if (!rli_fake) {
mysql_mutex_init(key_relay_log_info_log_space_lock, &log_space_lock,
MY_MUTEX_INIT_FAST);
mysql_cond_init(key_relay_log_info_log_space_cond, &log_space_cond);
mysql_mutex_init(key_mutex_slave_parallel_pend_jobs, &pending_jobs_lock,
MY_MUTEX_INIT_FAST);
mysql_cond_init(key_cond_slave_parallel_pend_jobs, &pending_jobs_cond);
mysql_mutex_init(key_mutex_slave_parallel_worker_count, &exit_count_lock,
MY_MUTEX_INIT_FAST);
mysql_mutex_init(key_mta_temp_table_LOCK, &mts_temp_table_LOCK,
MY_MUTEX_INIT_FAST);
mysql_mutex_init(key_mta_gaq_LOCK, &mts_gaq_LOCK, MY_MUTEX_INIT_FAST);
mysql_cond_init(key_cond_mta_gaq, &logical_clock_cond);
relay_log.init_pthread_objects();
force_flush_postponed_due_to_split_trans = false;
Checkable_rwlock *tsid_lock = new Checkable_rwlock(
#if defined(HAVE_PSI_INTERFACE)
key_rwlock_receiver_tsid_lock
#endif
);
Tsid_map *tsid_map = new Tsid_map(tsid_lock);
gtid_set = new Gtid_set(tsid_map, tsid_lock);
/*
Group replication applier channel shall not use checksum on its relay
log files.
*/
if (channel_map.is_group_replication_applier_channel_name(param_channel)) {
relay_log.relay_log_checksum_alg =
mysql::binlog::event::BINLOG_CHECKSUM_ALG_OFF;
}
}
gtid_monitoring_info = new Gtid_monitoring_info();
do_server_version_split(::server_version, slave_version_split);
until_option = nullptr;
rpl_filter = nullptr;
}
/**
The method to invoke at slave threads start
*/
void Relay_log_info::init_workers(ulong n_workers) {
/*
Parallel slave parameters initialization is done regardless
whether the feature is or going to be active or not.
*/
mta_coordinator_has_waited_stat = 0;
mts_groups_assigned = 0;
pending_jobs = 0;
mts_wq_excess_cnt = 0;
worker_queue_mem_exceeded_count = 0;
workers.reserve(n_workers);
workers_array_initialized = true; // set after init
}
/**
The method to invoke at slave threads stop
*/
void Relay_log_info::deinit_workers() { workers.clear(); }
Relay_log_info::~Relay_log_info() {
DBUG_TRACE;
if (!rli_fake) {
if (recovery_groups_inited) bitmap_free(&recovery_groups);
delete current_mts_submode;
if (rpl_filter != nullptr) {
/* Remove the channel's replication filter from rpl_channel_filters. */
rpl_channel_filters.delete_filter(rpl_filter);
rpl_filter = nullptr;
}
if (workers_copy_pfs.size()) {
for (int i = static_cast<int>(workers_copy_pfs.size()) - 1; i >= 0; i--)
delete workers_copy_pfs[i];
workers_copy_pfs.clear();
}
mysql_mutex_destroy(&log_space_lock);
mysql_cond_destroy(&log_space_cond);
mysql_mutex_destroy(&pending_jobs_lock);
mysql_cond_destroy(&pending_jobs_cond);
mysql_mutex_destroy(&exit_count_lock);
mysql_mutex_destroy(&mts_temp_table_LOCK);
mysql_mutex_destroy(&mts_gaq_LOCK);
mysql_cond_destroy(&logical_clock_cond);
relay_log.cleanup();
Tsid_map *tsid_map = gtid_set->get_tsid_map();
Checkable_rwlock *tsid_lock = tsid_map->get_tsid_lock();
tsid_lock->wrlock();
gtid_set->clear();
tsid_map->clear();
delete gtid_set;
delete tsid_map;
tsid_lock->unlock();
delete tsid_lock;
}
if (set_rli_description_event(nullptr)) {
#ifndef NDEBUG
bool set_rli_description_event_failed{false};
#endif
assert(set_rli_description_event_failed);
}
delete until_option;
delete gtid_monitoring_info;
}
/**
Method is called when MTS coordinator senses the relay-log name
has been changed.
It marks each Worker member with this fact to make an action
at time it will distribute a terminal event of a group to the Worker.
Worker receives the new name at the group committing phase
@c Slave_worker::slave_worker_ends_group().
*/
void Relay_log_info::reset_notified_relay_log_change() {
if (!is_parallel_exec()) return;
for (Slave_worker **it = workers.begin(); it != workers.end(); ++it) {
Slave_worker *w = *it;
w->relay_log_change_notified = false;
}
}
/**
This method is called in mta_checkpoint_routine() to mark that each
worker is required to adapt to a new checkpoint data whose coordinates
are passed to it through GAQ index.
Worker notices the new checkpoint value at the group commit to reset
the current bitmap and starts using the clean bitmap indexed from zero
of being reset rli_checkpoint_seqno.
New seconds_behind_source timestamp is installed.
@param shift number of bits to shift by Worker due to the
current checkpoint change.
@param new_ts new seconds_behind_source timestamp value
unless zero. Zero could be due to FD event
or fake rotate event.
@param update_timestamp if true, this function will update the
rli->last_master_timestamp.
*/
void Relay_log_info::reset_notified_checkpoint(ulong shift, time_t new_ts,
bool update_timestamp) {
/*
If this is not a parallel execution we return immediately.
*/
if (!is_parallel_exec()) return;
for (Slave_worker **it = workers.begin(); it != workers.end(); ++it) {
Slave_worker *w = *it;
/*
Resetting the notification information in order to force workers to
assign jobs with the new updated information.
Notice that the bitmap_shifted is accumulated to indicate how many
consecutive jobs were successfully processed.
The worker when assigning a new job will set the value back to
zero.
*/
w->checkpoint_notified = false;
w->bitmap_shifted = w->bitmap_shifted + shift;
/*
Zero shift indicates the caller rotates the master binlog.
The new name will be passed to W through the group descriptor
during the first post-rotation time scheduling.
*/
if (shift == 0) w->master_log_change_notified = false;
DBUG_PRINT("mta", ("reset_notified_checkpoint shift --> %lu, "
"worker->bitmap_shifted --> %lu, worker --> %u.",
shift, w->bitmap_shifted,
static_cast<unsigned>(it - workers.begin())));
}
/*
There should not be a call where (shift == 0 && rli_checkpoint_seqno != 0).
Then the new checkpoint sequence is updated by subtracting the number
of consecutive jobs that were successfully processed.
*/
assert(current_mts_submode->get_type() != MTS_PARALLEL_TYPE_DB_NAME ||
!(shift == 0 && rli_checkpoint_seqno != 0));
rli_checkpoint_seqno = rli_checkpoint_seqno - shift;
DBUG_PRINT("mta", ("reset_notified_checkpoint shift --> %lu, "
"rli_checkpoint_seqno --> %u.",
shift, rli_checkpoint_seqno));
if (update_timestamp) {
mysql_mutex_lock(&data_lock);
last_master_timestamp = new_ts;
mysql_mutex_unlock(&data_lock);
}
}
/**
Reset recovery info from Worker info table and
mark MTS recovery is completed.
@return false on success true when @c reset_notified_checkpoint failed.
*/
bool Relay_log_info::mts_finalize_recovery() {
bool ret = false;
uint i;
uint repo_type = get_rpl_info_handler()->get_rpl_info_type();
DBUG_TRACE;
for (Slave_worker **it = workers.begin(); !ret && it != workers.end(); ++it) {
Slave_worker *w = *it;
ret = w->reset_recovery_info();
DBUG_EXECUTE_IF("mta_debug_recovery_reset_fails", ret = true;);
}
/*
The loop is traversed in the worker index descending order due
to specifics of the Worker table repository that does not like
even temporary holes. Therefore stale records are deleted
from the tail.
*/
DBUG_EXECUTE_IF("enable_mta_wokrer_failure_in_recovery_finalize",
{ DBUG_SET("+d,mta_worker_thread_init_fails"); });
for (i = recovery_parallel_workers; i > workers.size() && !ret; i--) {
Slave_worker *w = Rpl_info_factory::create_worker(repo_type, i - 1, this,
!mi->is_gtid_only_mode());
/*
If an error occurs during the above create_worker call, the newly created
worker object gets deleted within the above function call itself and only
NULL is returned. Hence the following check has been added to verify
that a valid worker object exists.
*/
if (w) {
ret = w->remove_info();
delete w;
} else {
ret = true;
goto err;
}
}
recovery_parallel_workers = replica_parallel_workers;
err:
return ret;
}
static inline int add_relay_log(Relay_log_info *rli, Log_info *linfo) {
MY_STAT s;
DBUG_TRACE;
mysql_mutex_assert_owner(&rli->log_space_lock);
if (!mysql_file_stat(key_file_relaylog, linfo->log_file_name, &s, MYF(0))) {
LogErr(ERROR_LEVEL, ER_RPL_FAILED_TO_STAT_LOG_IN_INDEX,
linfo->log_file_name);
return 1;
}
rli->log_space_total += s.st_size;
#ifndef NDEBUG
char buf[22];
DBUG_PRINT("info", ("log_space_total: %s", llstr(rli->log_space_total, buf)));
#endif
return 0;
}
int Relay_log_info::count_relay_log_space() {
Log_info flinfo;
DBUG_TRACE;
MUTEX_LOCK(lock, &log_space_lock);
log_space_total = 0;
if (relay_log.find_log_pos(&flinfo, NullS, true)) {
LogErr(ERROR_LEVEL, ER_RPL_LOG_NOT_FOUND_WHILE_COUNTING_RELAY_LOG_SPACE);
return 1;
}
do {
if (add_relay_log(this, &flinfo)) return 1;
} while (!relay_log.find_next_log(&flinfo, true));
/*
As we have counted everything, including what may have written in a
preceding write, we must reset bytes_written, or we may count some space
twice.
*/
relay_log.reset_bytes_written();
return 0;
}
bool Relay_log_info::reset_group_relay_log_pos(const char **errmsg) {
Log_info linfo;
mysql_mutex_assert_owner(&data_lock);
if (relay_log.find_log_pos(&linfo, NullS, true)) {
*errmsg = "Could not find first log during relay log initialization";
return true;
}
set_group_relay_log_name(linfo.log_file_name);
group_relay_log_pos = BIN_LOG_HEADER_SIZE;
return false;
}
bool Relay_log_info::is_group_relay_log_name_invalid(const char **errmsg) {
DBUG_TRACE;
const char *errmsg_fmt = nullptr;
static char errmsg_buff[MYSQL_ERRMSG_SIZE + FN_REFLEN];
Log_info linfo;
*errmsg = nullptr;
if (relay_log.find_log_pos(&linfo, group_relay_log_name, true)) {
errmsg_fmt =
"Could not find target log file mentioned in "
"applier metadata in the index file '%s' during "
"relay log initialization";
sprintf(errmsg_buff, errmsg_fmt, relay_log.get_index_fname());
*errmsg = errmsg_buff;
return true;
}
return false;
}
/**
Update the error number, message and timestamp fields. This function is
different from va_report() as va_report() also logs the error message in the
log apart from updating the error fields.
SYNOPSIS
@param[in] level specifies the level- error, warning or information,
@param[in] err_code error number,
@param[in] buff_coord error message to be used.
*/
void Relay_log_info::fill_coord_err_buf(loglevel level, int err_code,
const char *buff_coord) const {
mysql_mutex_lock(&err_lock);
if (level == ERROR_LEVEL) {
m_last_error.number = err_code;
snprintf(m_last_error.message, sizeof(m_last_error.message), "%.*s",
MAX_SLAVE_ERRMSG - 1, buff_coord);
m_last_error.update_timestamp();
}
mysql_mutex_unlock(&err_lock);
}
/**
Waits until the SQL thread reaches (has executed up to) the
log/position or timed out.
SYNOPSIS
@param[in] thd client thread that sent @c SELECT @c
SOURCE_POS_WAIT,
@param[in] log_name log name to wait for,
@param[in] log_pos position to wait for,
@param[in] timeout @c timeout in seconds before giving up waiting.
@c timeout is double whereas it should be ulong;
but this is to catch if the user submitted a negative timeout.
@retval -2 improper arguments (log_pos<0)
or slave not running, or master info changed
during the function's execution,
or client thread killed. -2 is translated to NULL by caller,
@retval -1 timed out
@retval >=0 number of log events the function had to wait
before reaching the desired log/position
*/
int Relay_log_info::wait_for_pos(THD *thd, String *log_name, longlong log_pos,
double timeout) {
int event_count = 0;
ulong init_abort_pos_wait;
int error = 0;
struct timespec abstime; // for timeout checking
PSI_stage_info old_stage;
DBUG_TRACE;
if (!inited) return -2;
DBUG_PRINT("enter", ("log_name: '%s' log_pos: %lu timeout: %lu",
log_name->c_ptr_safe(), (ulong)log_pos, (ulong)timeout));
DEBUG_SYNC(thd, "begin_source_pos_wait");
set_timespec_nsec(&abstime, static_cast<ulonglong>(timeout * 1000000000ULL));
mysql_mutex_lock(&data_lock);
thd->ENTER_COND(&data_cond, &data_lock,
&stage_waiting_for_the_replica_thread_to_advance_position,
&old_stage);
/*
This function will abort when it notices that some CHANGE REPLICATION
SOURCE or RESET BINARY LOGS AND GTIDS has changed the master info. To catch
this, these commands modify abort_pos_wait ; We just monitor abort_pos_wait
and see if it has changed. Why do we have this mechanism instead of simply
monitoring slave_running in the loop (we do this too), as CHANGE
MASTER/RESET REPLICA require that the SQL thread be stopped? This is
because if someones does: STOP REPLICA;CHANGE REPLICATION SOURCE/RESET
REPLICA; START REPLICA; the change may happen very quickly and we may not
notice that slave_running briefly switches between 1/0/1.
*/
init_abort_pos_wait = abort_pos_wait;
/*
We'll need to
handle all possible log names comparisons (e.g. 999 vs 1000).
We use ulong for string->number conversion ; this is no
stronger limitation than in find_uniq_filename in sql/log.cc
*/
ulong log_name_extension;
char log_name_tmp[FN_REFLEN]; // make a char[] from String
strmake(log_name_tmp, log_name->ptr(),
min<uint32>(log_name->length(), FN_REFLEN - 1));
const char *p = fn_ext(log_name_tmp);
char *p_end;
if (!*p || log_pos < 0) {
error = -2; // means improper arguments
goto err;
}
// Convert 0-3 to 4
log_pos = max(log_pos, static_cast<longlong>(BIN_LOG_HEADER_SIZE));
/* p points to '.' */
log_name_extension = strtoul(++p, &p_end, 10);
/*
p_end points to the first invalid character.
If it equals to p, no digits were found, error.
If it contains '\0' it means conversion went ok.
*/
if (p_end == p || *p_end) {
error = -2;
goto err;
}
/* The "compare and wait" main loop */
while (!thd->killed && init_abort_pos_wait == abort_pos_wait &&
slave_running) {
bool pos_reached;
int cmp_result = 0;
DBUG_PRINT("info", ("init_abort_pos_wait: %ld abort_pos_wait: %ld",
init_abort_pos_wait, abort_pos_wait.load()));
DBUG_PRINT("info", ("group_source_log_name: '%s' pos: %lu",
group_master_log_name, (ulong)group_master_log_pos));
/*
group_master_log_name can be "", if we are just after a fresh
replication start or after a CHANGE REPLICATION SOURCE TO SOURCE_HOST/PORT
(before we have executed one Rotate event from the master) or
(rare) if the user is doing a weird slave setup (see next
paragraph). If group_master_log_name is "", we assume we don't
have enough info to do the comparison yet, so we just wait until
more data. In this case master_log_pos is always 0 except if
somebody (wrongly) sets this slave to be a slave of itself
without using --replicate-same-server-id (an unsupported
configuration which does nothing), then group_master_log_pos
will grow and group_master_log_name will stay "".
Also in case the group master log position is invalid (e.g. after
CHANGE REPLICATION SOURCE TO RELAY_LOG_POS ), we will wait till the first
event is read and the log position is valid again.
*/
if (*group_master_log_name && !is_group_master_log_pos_invalid &&
!is_applier_source_position_info_invalid()) {
char *basename =
(group_master_log_name + dirname_length(group_master_log_name));
/*
First compare the parts before the extension.
Find the dot in the master's log basename,
and protect against user's input error :
if the names do not match up to '.' included, return error
*/
const char *q = fn_ext(basename) + 1;
if (strncmp(basename, log_name_tmp, (int)(q - basename))) {
error = -2;
break;
}
// Now compare extensions.
char *q_end;
ulong group_master_log_name_extension = strtoul(q, &q_end, 10);
if (group_master_log_name_extension < log_name_extension)
cmp_result = -1;
else
cmp_result =
(group_master_log_name_extension > log_name_extension) ? 1 : 0;
pos_reached =
((!cmp_result && group_master_log_pos >= (ulonglong)log_pos) ||
cmp_result > 0);
if (pos_reached || thd->killed) break;
}
// wait for master update, with optional timeout.
DBUG_PRINT("info", ("Waiting for source update"));
/*
We are going to mysql_cond_(timed)wait(); if the SQL thread stops it
will wake us up.
*/
thd_wait_begin(thd, THD_WAIT_BINLOG);
if (timeout > 0) {
/*
Note that mysql_cond_timedwait checks for the timeout
before for the condition ; i.e. it returns ETIMEDOUT
if the system time equals or exceeds the time specified by abstime
before the condition variable is signaled or broadcast, _or_ if
the absolute time specified by abstime has already passed at the time
of the call.
For that reason, mysql_cond_timedwait will do the "timeoutting" job
even if its condition is always immediately signaled (case of a loaded
master).
*/
error = mysql_cond_timedwait(&data_cond, &data_lock, &abstime);
} else
mysql_cond_wait(&data_cond, &data_lock);
thd_wait_end(thd);
DBUG_PRINT("info", ("Got signal of source update or timed out"));
if (is_timeout(error)) {
#ifndef NDEBUG
/*
Doing this to generate a stack trace and make debugging
easier.
*/
if (DBUG_EVALUATE_IF("debug_crash_replica_time_out", 1, 0)) assert(0);
#endif
error = -1;
break;
}
error = 0;
event_count++;
DBUG_PRINT("info", ("Testing if killed or SQL thread not running"));
}
err:
mysql_mutex_unlock(&data_lock);
thd->EXIT_COND(&old_stage);
DBUG_PRINT("exit",
("killed: %d abort: %d replica_running: %d "
"improper_arguments: %d timed_out: %d",
thd->killed.load(), (int)(init_abort_pos_wait != abort_pos_wait),
(int)slave_running, (int)(error == -2), (int)(error == -1)));
if (thd->killed || init_abort_pos_wait != abort_pos_wait || !slave_running) {
error = -2;
}
return error ? error : event_count;
}
int Relay_log_info::wait_for_gtid_set(THD *thd, const char *gtid,
double timeout, bool update_THD_status) {
DBUG_TRACE;
DBUG_PRINT("info", ("Waiting for %s timeout %lf", gtid, timeout));
Gtid_set wait_gtid_set(global_tsid_map);
global_tsid_lock->rdlock();
enum_return_status ret = wait_gtid_set.add_gtid_text(gtid);
global_tsid_lock->unlock();
if (ret != RETURN_STATUS_OK) {
DBUG_PRINT("exit", ("improper gtid argument"));
return -2;
}
return wait_for_gtid_set(thd, &wait_gtid_set, timeout, update_THD_status);
}
int Relay_log_info::wait_for_gtid_set(THD *thd, String *gtid, double timeout,
bool update_THD_status) {
DBUG_TRACE;
return wait_for_gtid_set(thd, gtid->c_ptr_safe(), timeout, update_THD_status);
}
/*
TODO: This is a duplicated code that needs to be simplified.
This will be done while developing all possible sync options.
See WL#3584's specification.
/Alfranio
*/
int Relay_log_info::wait_for_gtid_set(THD *thd, const Gtid_set *wait_gtid_set,
double timeout, bool update_THD_status) {
int event_count = 0;
ulong init_abort_pos_wait;
int error = 0;
struct timespec abstime; // for timeout checking
PSI_stage_info old_stage;
DBUG_TRACE;
if (!inited) return -2;
DEBUG_SYNC(thd, "begin_wait_for_gtid_set");
set_timespec_nsec(&abstime, static_cast<ulonglong>(timeout * 1000000000ULL));
mysql_mutex_lock(&data_lock);
if (update_THD_status)
thd->ENTER_COND(&data_cond, &data_lock,
&stage_waiting_for_the_replica_thread_to_advance_position,
&old_stage);
/*
This function will abort when it notices that some CHANGE REPLICATION
SOURCE or RESET BINARY LOGS AND GTIDS has changed the master info. To catch
this, these commands modify abort_pos_wait ; We just monitor abort_pos_wait
and see if it has changed. Why do we have this mechanism instead of simply
monitoring slave_running in the loop (we do this too), as CHANGE
REPLICATION SOURCE/RESET REPLICA require that the SQL thread be stopped?
This is because if someones does:
STOP REPLICA;CHANGE REPLICATION SOURCE/RESET REPLICA; START REPLICA;
the change may happen very quickly and we may not notice that
slave_running briefly switches between 1/0/1.
*/
init_abort_pos_wait = abort_pos_wait;
/* The "compare and wait" main loop */
while (!thd->killed && init_abort_pos_wait == abort_pos_wait &&
slave_running) {
DBUG_PRINT("info", ("init_abort_pos_wait: %ld abort_pos_wait: %ld",
init_abort_pos_wait, abort_pos_wait.load()));
// wait for master update, with optional timeout.
assert(wait_gtid_set->get_tsid_map() == nullptr ||
wait_gtid_set->get_tsid_map() == global_tsid_map);
global_tsid_lock->wrlock();
const Gtid_set *executed_gtids = gtid_state->get_executed_gtids();
const Owned_gtids *owned_gtids = gtid_state->get_owned_gtids();
#ifndef NDEBUG
char *wait_gtid_set_buf;
wait_gtid_set->to_string(&wait_gtid_set_buf);
DBUG_PRINT("info",
("Waiting for '%s'. is_subset: %d and "
"!is_intersection_nonempty: %d",
wait_gtid_set_buf, wait_gtid_set->is_subset(executed_gtids),
!owned_gtids->is_intersection_nonempty(wait_gtid_set)));
my_free(wait_gtid_set_buf);
executed_gtids->dbug_print("gtid_executed:");
owned_gtids->dbug_print("owned_gtids:");
#endif
/*
Since commit is performed after log to binary log, we must also
check if any GTID of wait_gtid_set is not yet committed.
*/
if (wait_gtid_set->is_subset(executed_gtids) &&
!owned_gtids->is_intersection_nonempty(wait_gtid_set)) {
global_tsid_lock->unlock();
break;
}
global_tsid_lock->unlock();
DBUG_PRINT("info", ("Waiting for source update"));
/*
We are going to mysql_cond_(timed)wait(); if the SQL thread stops it
will wake us up.
*/
thd_wait_begin(thd, THD_WAIT_BINLOG);
if (timeout > 0) {
/*
Note that mysql_cond_timedwait checks for the timeout
before for the condition ; i.e. it returns ETIMEDOUT
if the system time equals or exceeds the time specified by abstime
before the condition variable is signaled or broadcast, _or_ if
the absolute time specified by abstime has already passed at the time
of the call.
For that reason, mysql_cond_timedwait will do the "timeoutting" job
even if its condition is always immediately signaled (case of a loaded
master).
*/
error = mysql_cond_timedwait(&data_cond, &data_lock, &abstime);
} else
mysql_cond_wait(&data_cond, &data_lock);
thd_wait_end(thd);
DBUG_PRINT("info", ("Got signal of source update or timed out"));
if (is_timeout(error)) {
#ifndef NDEBUG
/*
Doing this to generate a stack trace and make debugging
easier.
*/
if (DBUG_EVALUATE_IF("debug_crash_replica_time_out", 1, 0)) assert(0);
#endif
error = -1;
break;
}
error = 0;
event_count++;
DBUG_PRINT("info", ("Testing if killed or SQL thread not running"));
}
mysql_mutex_unlock(&data_lock);
if (update_THD_status) thd->EXIT_COND(&old_stage);
DBUG_PRINT("exit",
("killed: %d abort: %d replica_running: %d "
"improper_arguments: %d timed_out: %d",
thd->killed.load(), (int)(init_abort_pos_wait != abort_pos_wait),
(int)slave_running, (int)(error == -2), (int)(error == -1)));
if (thd->killed || init_abort_pos_wait != abort_pos_wait || !slave_running) {
error = -2;
}
return error ? error : event_count;
}
int Relay_log_info::inc_group_relay_log_pos(ulonglong log_pos,
bool need_data_lock, bool force) {
int error = 0;
DBUG_TRACE;
if (need_data_lock)
mysql_mutex_lock(&data_lock);
else
mysql_mutex_assert_owner(&data_lock);
inc_event_relay_log_pos();
group_relay_log_pos = event_relay_log_pos;
strmake(group_relay_log_name, event_relay_log_name,
sizeof(group_relay_log_name) - 1);
/*
In 4.x we used the event's len to compute the positions here. This is
wrong if the event was 3.23/4.0 and has been converted to 5.0, because
then the event's len is not what is was in the master's binlog, so this
will make a wrong group_master_log_pos (yes it's a bug in 3.23->4.0
replication: Exec_master_log_pos is wrong). Only way to solve this is to
have the original offset of the end of the event the relay log. This is
what we do in 5.0: log_pos has become "end_log_pos" (because the real use
of log_pos in 4.0 was to compute the end_log_pos; so better to store
end_log_pos instead of begin_log_pos.
If we had not done this fix here, the problem would also have appeared
when the slave and master are 5.0 but with different event length (for
example the slave is more recent than the master and features the event
UID). It would give false SOURCE_POS_WAIT, false Exec_master_log_pos in
SHOW REPLICA STATUS, and so the user would do some CHANGE REPLICATION SOURCE
using this value which would lead to badly broken replication. Even the
relay_log_pos will be corrupted in this case, because the len is the relay
log is not "val". With the end_log_pos solution, we avoid computations
involving lengths.
*/
DBUG_PRINT("info", ("log_pos: %lu group_source_log_pos: %lu", (long)log_pos,
(long)group_master_log_pos));
if (log_pos > 0) // 3.23 binlogs don't have log_posx
group_master_log_pos = log_pos;
/*
If the master log position was invalidiated by say, "CHANGE REPLICATION
SOURCE TO RELAY_LOG_POS=N", it is now valid,
*/
if (is_group_master_log_pos_invalid) is_group_master_log_pos_invalid = false;
/*
In MTS mode FD or Rotate event commit their solitary group to
Coordinator's info table. Callers make sure that Workers have been
executed all assignments.
Broadcast to source_pos_wait() waiters should be done after
the table is updated.
*/
assert(!is_parallel_exec() ||
mts_group_status != Relay_log_info::MTS_IN_GROUP);
/*
We do not force synchronization at this point, except for Rotate event
(see Rotate_log_event::do_update_pos), note @c force is false by default,
because a non-transactional change is being committed.
For that reason, the synchronization here is subjected to
the option sync_relay_log_info.
See sql/rpl_rli.h for further information on this behavior.
*/
error = flush_info(force ? RLI_FLUSH_IGNORE_SYNC_OPT : RLI_FLUSH_NO_OPTION);
mysql_cond_broadcast(&data_cond);
if (need_data_lock) mysql_mutex_unlock(&data_lock);
return error;