-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
replication.go
821 lines (725 loc) · 25.4 KB
/
replication.go
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
/*
Copyright 2019 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Handle creating replicas and setting up the replication streams.
*/
package mysqlctl
import (
"context"
"errors"
"fmt"
"net"
"strconv"
"strings"
"time"
"vitess.io/vitess/go/mysql"
"vitess.io/vitess/go/mysql/replication"
"vitess.io/vitess/go/netutil"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/vt/hook"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/proto/replicationdata"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/vterrors"
)
const (
// Queries used for RPCs
getGlobalStatusQuery = "SELECT variable_name, variable_value FROM performance_schema.global_status"
)
type ResetSuperReadOnlyFunc func() error
// WaitForReplicationStart waits until the deadline for replication to start.
// This validates the current primary is correct and can be connected to.
func WaitForReplicationStart(ctx context.Context, mysqld MysqlDaemon, replicaStartDeadline int) (err error) {
var replicaStatus replication.ReplicationStatus
for replicaWait := 0; replicaWait < replicaStartDeadline; replicaWait++ {
replicaStatus, err = mysqld.ReplicationStatus(ctx)
if err != nil {
return err
}
if replicaStatus.Running() {
return nil
}
time.Sleep(time.Second)
}
errs := make([]string, 0, 2)
if replicaStatus.LastSQLError != "" {
errs = append(errs, "Last_SQL_Error: "+replicaStatus.LastSQLError)
}
if replicaStatus.LastIOError != "" {
errs = append(errs, "Last_IO_Error: "+replicaStatus.LastIOError)
}
if len(errs) != 0 {
return errors.New(strings.Join(errs, ", "))
}
return nil
}
// StartReplication starts replication.
func (mysqld *Mysqld) StartReplication(ctx context.Context, hookExtraEnv map[string]string) error {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return err
}
defer conn.Recycle()
if err := mysqld.executeSuperQueryListConn(ctx, conn, []string{conn.Conn.StartReplicationCommand()}); err != nil {
return err
}
h := hook.NewSimpleHook("postflight_start_slave")
h.ExtraEnv = hookExtraEnv
return h.ExecuteOptional()
}
// StartReplicationUntilAfter starts replication until replication has come to `targetPos`, then it stops replication
func (mysqld *Mysqld) StartReplicationUntilAfter(ctx context.Context, targetPos replication.Position) error {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return err
}
defer conn.Recycle()
queries := []string{conn.Conn.StartReplicationUntilAfterCommand(targetPos)}
return mysqld.executeSuperQueryListConn(ctx, conn, queries)
}
// StartSQLThreadUntilAfter starts replication's SQL thread(s) until replication has come to `targetPos`, then it stops it
func (mysqld *Mysqld) StartSQLThreadUntilAfter(ctx context.Context, targetPos replication.Position) error {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return err
}
defer conn.Recycle()
queries := []string{conn.Conn.StartSQLThreadUntilAfterCommand(targetPos)}
return mysqld.executeSuperQueryListConn(ctx, conn, queries)
}
// StopReplication stops replication.
func (mysqld *Mysqld) StopReplication(ctx context.Context, hookExtraEnv map[string]string) error {
h := hook.NewSimpleHook("preflight_stop_slave")
h.ExtraEnv = hookExtraEnv
if err := h.ExecuteOptional(); err != nil {
return err
}
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return err
}
defer conn.Recycle()
return mysqld.executeSuperQueryListConn(ctx, conn, []string{conn.Conn.StopReplicationCommand()})
}
// StopIOThread stops a replica's IO thread only.
func (mysqld *Mysqld) StopIOThread(ctx context.Context) error {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return err
}
defer conn.Recycle()
return mysqld.executeSuperQueryListConn(ctx, conn, []string{conn.Conn.StopIOThreadCommand()})
}
// StopSQLThread stops a replica's SQL thread(s) only.
func (mysqld *Mysqld) StopSQLThread(ctx context.Context) error {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return err
}
defer conn.Recycle()
return mysqld.executeSuperQueryListConn(ctx, conn, []string{conn.Conn.StopSQLThreadCommand()})
}
// RestartReplication stops, resets and starts replication.
func (mysqld *Mysqld) RestartReplication(ctx context.Context, hookExtraEnv map[string]string) error {
h := hook.NewSimpleHook("preflight_stop_slave")
h.ExtraEnv = hookExtraEnv
if err := h.ExecuteOptional(); err != nil {
return err
}
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return err
}
defer conn.Recycle()
if err := mysqld.executeSuperQueryListConn(ctx, conn, conn.Conn.RestartReplicationCommands()); err != nil {
return err
}
h = hook.NewSimpleHook("postflight_start_slave")
h.ExtraEnv = hookExtraEnv
return h.ExecuteOptional()
}
// GetMysqlPort returns mysql port
func (mysqld *Mysqld) GetMysqlPort(ctx context.Context) (int32, error) {
// We can not use the connection pool here. This check runs very early
// during MySQL startup when we still might be loading things like grants.
// This means we need to use an isolated connection to avoid poisoning the
// DBA connection pool for further queries.
params, err := mysqld.dbcfgs.DbaConnector().MysqlParams()
if err != nil {
return 0, err
}
conn, err := mysql.Connect(ctx, params)
if err != nil {
return 0, err
}
defer conn.Close()
qr, err := conn.ExecuteFetch("SHOW VARIABLES LIKE 'port'", 1, false)
if err != nil {
return 0, err
}
if len(qr.Rows) != 1 {
return 0, errors.New("no port variable in mysql")
}
utemp, err := qr.Rows[0][1].ToCastUint64()
if err != nil {
return 0, err
}
return int32(utemp), nil
}
// GetServerID returns mysql server id
func (mysqld *Mysqld) GetServerID(ctx context.Context) (uint32, error) {
qr, err := mysqld.FetchSuperQuery(ctx, "select @@global.server_id")
if err != nil {
return 0, err
}
if len(qr.Rows) != 1 {
return 0, errors.New("no server_id in mysql")
}
utemp, err := qr.Rows[0][0].ToCastUint64()
if err != nil {
return 0, err
}
return uint32(utemp), nil
}
// GetServerUUID returns mysql server uuid
func (mysqld *Mysqld) GetServerUUID(ctx context.Context) (string, error) {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return "", err
}
defer conn.Recycle()
return conn.Conn.GetServerUUID()
}
// GetGlobalStatusVars returns the server's global status variables asked for.
// An empty/nil variable name parameter slice means you want all of them.
func (mysqld *Mysqld) GetGlobalStatusVars(ctx context.Context, variables []string) (map[string]string, error) {
query := getGlobalStatusQuery
if len(variables) != 0 {
// The format specifier is for any optional predicates.
statusBv, err := sqltypes.BuildBindVariable(variables)
if err != nil {
return nil, err
}
query, err = sqlparser.ParseAndBind(getGlobalStatusQuery+" WHERE variable_name IN %a",
statusBv,
)
if err != nil {
return nil, err
}
}
qr, err := mysqld.FetchSuperQuery(ctx, query)
if err != nil {
return nil, err
}
finalRes := make(map[string]string, len(qr.Rows))
for _, row := range qr.Rows {
if len(row) != 2 {
return nil, vterrors.New(vtrpcpb.Code_INTERNAL, "incorrect number of fields in the row")
}
finalRes[row[0].ToString()] = row[1].ToString()
}
return finalRes, nil
}
// IsReadOnly return true if the instance is read only
func (mysqld *Mysqld) IsReadOnly(ctx context.Context) (bool, error) {
qr, err := mysqld.FetchSuperQuery(ctx, "SHOW VARIABLES LIKE 'read_only'")
if err != nil {
return true, err
}
if len(qr.Rows) != 1 {
return true, errors.New("no read_only variable in mysql")
}
if qr.Rows[0][1].ToString() == "ON" {
return true, nil
}
return false, nil
}
// IsSuperReadOnly return true if the instance is super read only
func (mysqld *Mysqld) IsSuperReadOnly(ctx context.Context) (bool, error) {
qr, err := mysqld.FetchSuperQuery(ctx, "SELECT @@global.super_read_only")
if err != nil {
return false, err
}
if len(qr.Rows) == 1 {
sro := qr.Rows[0][0].ToString()
if sro == "1" || sro == "ON" {
return true, nil
}
}
return false, nil
}
// SetReadOnly set/unset the read_only flag
func (mysqld *Mysqld) SetReadOnly(ctx context.Context, on bool) error {
query := "SET GLOBAL read_only = "
if on {
query += "ON"
} else {
query += "OFF"
}
return mysqld.ExecuteSuperQuery(ctx, query)
}
// SetSuperReadOnly set/unset the super_read_only flag.
// Returns a function which is called to set super_read_only back to its original value.
func (mysqld *Mysqld) SetSuperReadOnly(ctx context.Context, on bool) (ResetSuperReadOnlyFunc, error) {
// return function for switching `OFF` super_read_only
var resetFunc ResetSuperReadOnlyFunc
var disableFunc = func() error {
query := "SET GLOBAL super_read_only = 'OFF'"
err := mysqld.ExecuteSuperQuery(context.Background(), query)
return err
}
// return function for switching `ON` super_read_only.
var enableFunc = func() error {
query := "SET GLOBAL super_read_only = 'ON'"
err := mysqld.ExecuteSuperQuery(context.Background(), query)
return err
}
superReadOnlyEnabled, err := mysqld.IsSuperReadOnly(ctx)
if err != nil {
return nil, err
}
// If non-idempotent then set the right call-back.
// We are asked to turn on super_read_only but original value is false,
// therefore return disableFunc, that can be used as defer by caller.
if on && !superReadOnlyEnabled {
resetFunc = disableFunc
}
// We are asked to turn off super_read_only but original value is true,
// therefore return enableFunc, that can be used as defer by caller.
if !on && superReadOnlyEnabled {
resetFunc = enableFunc
}
query := "SET GLOBAL super_read_only = "
if on {
query += "'ON'"
} else {
query += "'OFF'"
}
if err := mysqld.ExecuteSuperQuery(context.Background(), query); err != nil {
return nil, err
}
return resetFunc, nil
}
// WaitSourcePos lets replicas wait for the given replication position to
// be reached.
func (mysqld *Mysqld) WaitSourcePos(ctx context.Context, targetPos replication.Position) error {
// Get a connection.
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return err
}
defer conn.Recycle()
// First check if filePos flavored Position was passed in. If so, we
// can't defer to the flavor in the connection, unless that flavor is
// also filePos.
if targetPos.MatchesFlavor(replication.FilePosFlavorID) {
// If we are the primary, WaitUntilFilePosition will fail. But
// position is most likely reached. So, check the position first.
mpos, err := conn.Conn.PrimaryFilePosition()
if err != nil {
return vterrors.Wrapf(err, "WaitSourcePos: PrimaryFilePosition failed")
}
if mpos.AtLeast(targetPos) {
return nil
}
} else {
// If we are the primary, WaitUntilPosition will fail. But
// position is most likely reached. So, check the position first.
mpos, err := conn.Conn.PrimaryPosition()
if err != nil {
return vterrors.Wrapf(err, "WaitSourcePos: PrimaryPosition failed")
}
if mpos.AtLeast(targetPos) {
return nil
}
}
if err := conn.Conn.WaitUntilPosition(ctx, targetPos); err != nil {
return vterrors.Wrapf(err, "WaitSourcePos failed")
}
return nil
}
func (mysqld *Mysqld) CatchupToGTID(ctx context.Context, targetPos replication.Position) error {
params, err := mysqld.dbcfgs.ReplConnector().MysqlParams()
if err != nil {
return err
}
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return err
}
defer conn.Recycle()
cmds := conn.Conn.CatchupToGTIDCommands(params, targetPos)
return mysqld.executeSuperQueryListConn(ctx, conn, cmds)
}
// ReplicationStatus returns the server replication status
func (mysqld *Mysqld) ReplicationStatus(ctx context.Context) (replication.ReplicationStatus, error) {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return replication.ReplicationStatus{}, err
}
defer conn.Recycle()
return conn.Conn.ShowReplicationStatus()
}
// PrimaryStatus returns the primary replication statuses
func (mysqld *Mysqld) PrimaryStatus(ctx context.Context) (replication.PrimaryStatus, error) {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return replication.PrimaryStatus{}, err
}
defer conn.Recycle()
primaryStatus, err := conn.Conn.ShowPrimaryStatus()
if err != nil {
return replication.PrimaryStatus{}, err
}
primaryStatus.ServerUUID, err = conn.Conn.GetServerUUID()
if err != nil {
return replication.PrimaryStatus{}, err
}
return primaryStatus, nil
}
func (mysqld *Mysqld) ReplicationConfiguration(ctx context.Context) (*replicationdata.Configuration, error) {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return nil, err
}
defer conn.Recycle()
return conn.Conn.ReplicationConfiguration()
}
// GetGTIDPurged returns the gtid purged statuses
func (mysqld *Mysqld) GetGTIDPurged(ctx context.Context) (replication.Position, error) {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return replication.Position{}, err
}
defer conn.Recycle()
return conn.Conn.GetGTIDPurged()
}
// PrimaryPosition returns the primary replication position.
func (mysqld *Mysqld) PrimaryPosition(ctx context.Context) (replication.Position, error) {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return replication.Position{}, err
}
defer conn.Recycle()
return conn.Conn.PrimaryPosition()
}
// SetReplicationPosition sets the replication position at which the replica will resume
// when its replication is started.
func (mysqld *Mysqld) SetReplicationPosition(ctx context.Context, pos replication.Position) error {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return err
}
defer conn.Recycle()
cmds := conn.Conn.SetReplicationPositionCommands(pos)
log.Infof("Executing commands to set replication position: %v", cmds)
return mysqld.executeSuperQueryListConn(ctx, conn, cmds)
}
// SetReplicationSource makes the provided host / port the primary. It optionally
// stops replication before, and starts it after.
func (mysqld *Mysqld) SetReplicationSource(ctx context.Context, host string, port int32, heartbeatInterval float64, stopReplicationBefore bool, startReplicationAfter bool) error {
params, err := mysqld.dbcfgs.ReplConnector().MysqlParams()
if err != nil {
return err
}
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return err
}
defer conn.Recycle()
var cmds []string
if stopReplicationBefore {
cmds = append(cmds, conn.Conn.StopReplicationCommand())
}
smc := conn.Conn.SetReplicationSourceCommand(params, host, port, heartbeatInterval, int(replicationConnectRetry.Seconds()))
cmds = append(cmds, smc)
if startReplicationAfter {
cmds = append(cmds, conn.Conn.StartReplicationCommand())
}
return mysqld.executeSuperQueryListConn(ctx, conn, cmds)
}
// ResetReplication resets all replication for this host.
func (mysqld *Mysqld) ResetReplication(ctx context.Context) error {
conn, connErr := getPoolReconnect(ctx, mysqld.dbaPool)
if connErr != nil {
return connErr
}
defer conn.Recycle()
cmds := conn.Conn.ResetReplicationCommands()
return mysqld.executeSuperQueryListConn(ctx, conn, cmds)
}
// ResetReplicationParameters resets the replica replication parameters for this host.
func (mysqld *Mysqld) ResetReplicationParameters(ctx context.Context) error {
conn, connErr := getPoolReconnect(ctx, mysqld.dbaPool)
if connErr != nil {
return connErr
}
defer conn.Recycle()
cmds := conn.Conn.ResetReplicationParametersCommands()
return mysqld.executeSuperQueryListConn(ctx, conn, cmds)
}
// +------+---------+---------------------+------+-------------+------+------------------------------------------------------------------+------------------+
// | Id | User | Host | db | Command | Time | State | Info |
// +------+---------+---------------------+------+-------------+------+------------------------------------------------------------------+------------------+
// | 9792 | vt_repl | host:port | NULL | Binlog Dump | 54 | Has sent all binlog to replica; waiting for binlog to be updated | NULL |
// | 9797 | vt_dba | localhost | NULL | Query | 0 | NULL | show processlist |
// +------+---------+---------------------+------+-------------+------+------------------------------------------------------------------+------------------+
//
// Array indices for the results of SHOW PROCESSLIST.
const (
colConnectionID = iota //nolint
colUsername //nolint
colClientAddr
colDbName //nolint
colCommand
)
const (
// this is the command used by mysql replicas
binlogDumpCommand = "Binlog Dump"
)
// FindReplicas gets IP addresses for all currently connected replicas.
func FindReplicas(ctx context.Context, mysqld MysqlDaemon) ([]string, error) {
qr, err := mysqld.FetchSuperQuery(ctx, "SHOW PROCESSLIST")
if err != nil {
return nil, err
}
addrs := make([]string, 0, 32)
for _, row := range qr.Rows {
// Check for prefix, since it could be "Binlog Dump GTID".
if strings.HasPrefix(row[colCommand].ToString(), binlogDumpCommand) {
host := row[colClientAddr].ToString()
if host == "localhost" {
// If we have a local binlog streamer, it will
// show up as being connected
// from 'localhost' through the local
// socket. Ignore it.
continue
}
host, _, err = netutil.SplitHostPort(host)
if err != nil {
return nil, fmt.Errorf("FindReplicas: malformed addr %v", err)
}
var ips []string
ips, err = net.LookupHost(host)
if err != nil {
return nil, fmt.Errorf("FindReplicas: LookupHost failed %v", err)
}
addrs = append(addrs, ips...)
}
}
return addrs, nil
}
// GetBinlogInformation gets the binlog format, whether binlog is enabled and if updates on replica logging is enabled.
func (mysqld *Mysqld) GetBinlogInformation(ctx context.Context) (string, bool, bool, string, error) {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return "", false, false, "", err
}
defer conn.Recycle()
return conn.Conn.BinlogInformation()
}
// GetGTIDMode gets the GTID mode for the server
func (mysqld *Mysqld) GetGTIDMode(ctx context.Context) (string, error) {
conn, err := getPoolReconnect(ctx, mysqld.dbaPool)
if err != nil {
return "", err
}
defer conn.Recycle()
return conn.Conn.GetGTIDMode()
}
// FlushBinaryLogs is part of the MysqlDaemon interface.
func (mysqld *Mysqld) FlushBinaryLogs(ctx context.Context) (err error) {
_, err = mysqld.FetchSuperQuery(ctx, "FLUSH BINARY LOGS")
return err
}
// GetBinaryLogs is part of the MysqlDaemon interface.
func (mysqld *Mysqld) GetBinaryLogs(ctx context.Context) (binaryLogs []string, err error) {
qr, err := mysqld.FetchSuperQuery(ctx, "SHOW BINARY LOGS")
if err != nil {
return binaryLogs, err
}
for _, row := range qr.Rows {
binaryLogs = append(binaryLogs, row[0].ToString())
}
return binaryLogs, err
}
// GetPreviousGTIDs is part of the MysqlDaemon interface.
func (mysqld *Mysqld) GetPreviousGTIDs(ctx context.Context, binlog string) (previousGtids string, err error) {
query := fmt.Sprintf("SHOW BINLOG EVENTS IN '%s' LIMIT 2", binlog)
qr, err := mysqld.FetchSuperQuery(ctx, query)
if err != nil {
return previousGtids, err
}
previousGtidsFound := false
for _, row := range qr.Named().Rows {
if row.AsString("Event_type", "") == "Previous_gtids" {
previousGtids = row.AsString("Info", "")
previousGtidsFound = true
}
}
if !previousGtidsFound {
return previousGtids, fmt.Errorf("GetPreviousGTIDs: previous GTIDs not found")
}
return previousGtids, nil
}
var ErrNoSemiSync = errors.New("semi-sync plugin not loaded")
func (mysqld *Mysqld) SemiSyncType(ctx context.Context) mysql.SemiSyncType {
if mysqld.semiSyncType == mysql.SemiSyncTypeUnknown {
mysqld.semiSyncType, _ = mysqld.SemiSyncExtensionLoaded(ctx)
}
return mysqld.semiSyncType
}
func (mysqld *Mysqld) enableSemiSyncQuery(ctx context.Context) (string, error) {
switch mysqld.SemiSyncType(ctx) {
case mysql.SemiSyncTypeSource:
return "SET GLOBAL rpl_semi_sync_source_enabled = %v, GLOBAL rpl_semi_sync_replica_enabled = %v", nil
case mysql.SemiSyncTypeMaster:
return "SET GLOBAL rpl_semi_sync_master_enabled = %v, GLOBAL rpl_semi_sync_slave_enabled = %v", nil
}
return "", ErrNoSemiSync
}
func (mysqld *Mysqld) semiSyncClientsQuery(ctx context.Context) (string, error) {
switch mysqld.SemiSyncType(ctx) {
case mysql.SemiSyncTypeSource:
return "SHOW STATUS LIKE 'Rpl_semi_sync_source_clients'", nil
case mysql.SemiSyncTypeMaster:
return "SHOW STATUS LIKE 'Rpl_semi_sync_master_clients'", nil
}
return "", ErrNoSemiSync
}
func (mysqld *Mysqld) semiSyncReplicationStatusQuery(ctx context.Context) (string, error) {
switch mysqld.SemiSyncType(ctx) {
case mysql.SemiSyncTypeSource:
return "SHOW STATUS LIKE 'rpl_semi_sync_replica_status'", nil
case mysql.SemiSyncTypeMaster:
return "SHOW STATUS LIKE 'rpl_semi_sync_slave_status'", nil
}
return "", ErrNoSemiSync
}
// SetSemiSyncEnabled enables or disables semi-sync replication for
// primary and/or replica mode.
func (mysqld *Mysqld) SetSemiSyncEnabled(ctx context.Context, primary, replica bool) error {
log.Infof("Setting semi-sync mode: primary=%v, replica=%v", primary, replica)
// Convert bool to int.
var p, s int
if primary {
p = 1
}
if replica {
s = 1
}
query, err := mysqld.enableSemiSyncQuery(ctx)
if err != nil {
return err
}
err = mysqld.ExecuteSuperQuery(ctx, fmt.Sprintf(query, p, s))
if err != nil {
return fmt.Errorf("can't set semi-sync mode: %v; make sure plugins are loaded in my.cnf", err)
}
return nil
}
// SemiSyncEnabled returns whether semi-sync is enabled for primary or replica.
// If the semi-sync plugin is not loaded, we assume semi-sync is disabled.
func (mysqld *Mysqld) SemiSyncEnabled(ctx context.Context) (primary, replica bool) {
vars, err := mysqld.fetchVariables(ctx, "rpl_semi_sync_%_enabled")
if err != nil {
return false, false
}
switch mysqld.SemiSyncType(ctx) {
case mysql.SemiSyncTypeSource:
primary = vars["rpl_semi_sync_source_enabled"] == "ON"
replica = vars["rpl_semi_sync_replica_enabled"] == "ON"
case mysql.SemiSyncTypeMaster:
primary = vars["rpl_semi_sync_master_enabled"] == "ON"
replica = vars["rpl_semi_sync_slave_enabled"] == "ON"
}
return primary, replica
}
// SemiSyncStatus returns the current status of semi-sync for primary and replica.
func (mysqld *Mysqld) SemiSyncStatus(ctx context.Context) (primary, replica bool) {
vars, err := mysqld.fetchStatuses(ctx, "Rpl_semi_sync_%_status")
if err != nil {
return false, false
}
switch mysqld.SemiSyncType(ctx) {
case mysql.SemiSyncTypeSource:
primary = vars["Rpl_semi_sync_source_status"] == "ON"
replica = vars["Rpl_semi_sync_replica_status"] == "ON"
case mysql.SemiSyncTypeMaster:
primary = vars["Rpl_semi_sync_master_status"] == "ON"
replica = vars["Rpl_semi_sync_slave_status"] == "ON"
}
return primary, replica
}
// SemiSyncClients returns the number of semi-sync clients for the primary.
func (mysqld *Mysqld) SemiSyncClients(ctx context.Context) uint32 {
query, err := mysqld.semiSyncClientsQuery(ctx)
if err != nil {
return 0
}
qr, err := mysqld.FetchSuperQuery(ctx, query)
if err != nil {
return 0
}
if len(qr.Rows) != 1 {
return 0
}
countStr := qr.Rows[0][1].ToString()
count, _ := strconv.ParseUint(countStr, 10, 32)
return uint32(count)
}
// SemiSyncSettings returns the settings of semi-sync which includes the timeout and the number of replicas to wait for.
func (mysqld *Mysqld) SemiSyncSettings(ctx context.Context) (timeout uint64, numReplicas uint32) {
vars, err := mysqld.fetchVariables(ctx, "rpl_semi_sync_%")
if err != nil {
return 0, 0
}
var numReplicasUint uint64
switch mysqld.SemiSyncType(ctx) {
case mysql.SemiSyncTypeSource:
timeout, _ = strconv.ParseUint(vars["rpl_semi_sync_source_timeout"], 10, 64)
numReplicasUint, _ = strconv.ParseUint(vars["rpl_semi_sync_source_wait_for_replica_count"], 10, 32)
case mysql.SemiSyncTypeMaster:
timeout, _ = strconv.ParseUint(vars["rpl_semi_sync_master_timeout"], 10, 64)
numReplicasUint, _ = strconv.ParseUint(vars["rpl_semi_sync_master_wait_for_slave_count"], 10, 32)
}
return timeout, uint32(numReplicasUint)
}
// SemiSyncReplicationStatus returns whether semi-sync is currently used by replication.
func (mysqld *Mysqld) SemiSyncReplicationStatus(ctx context.Context) (bool, error) {
query, err := mysqld.semiSyncReplicationStatusQuery(ctx)
if err != nil {
return false, err
}
qr, err := mysqld.FetchSuperQuery(ctx, query)
if err != nil {
return false, err
}
if len(qr.Rows) != 1 {
return false, errors.New("no rpl_semi_sync_replica_status variable in mysql")
}
if qr.Rows[0][1].ToString() == "ON" {
return true, nil
}
return false, nil
}
// SemiSyncExtensionLoaded returns whether semi-sync plugins are loaded.
func (mysqld *Mysqld) SemiSyncExtensionLoaded(ctx context.Context) (mysql.SemiSyncType, error) {
conn, connErr := getPoolReconnect(ctx, mysqld.dbaPool)
if connErr != nil {
return mysql.SemiSyncTypeUnknown, connErr
}
defer conn.Recycle()
return conn.Conn.SemiSyncExtensionLoaded()
}