/
instance_topology.go
2776 lines (2472 loc) · 105 KB
/
instance_topology.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
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 2014 Outbrain Inc.
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.
*/
package inst
import (
"fmt"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/github/orchestrator/go/config"
"github.com/openark/golib/log"
"github.com/openark/golib/math"
"github.com/openark/golib/util"
)
type StopReplicationMethod string
const (
NoStopReplication StopReplicationMethod = "NoStopReplication"
StopReplicationNormal = "StopReplicationNormal"
StopReplicationNicely = "StopReplicationNicely"
)
var ReplicationNotRunningError = fmt.Errorf("Replication not running")
var asciiFillerCharacter = " "
var tabulatorScharacter = "|"
var countRetries = 5
// getASCIITopologyEntry will get an ascii topology tree rooted at given instance. Ir recursively
// draws the tree
func getASCIITopologyEntry(depth int, instance *Instance, replicationMap map[*Instance]([]*Instance), extendedOutput bool, fillerCharacter string, tabulated bool) []string {
if instance == nil {
return []string{}
}
if instance.IsCoMaster && depth > 1 {
return []string{}
}
prefix := ""
if depth > 0 {
prefix = strings.Repeat(fillerCharacter, (depth-1)*2)
if instance.ReplicaRunning() && instance.IsLastCheckValid && instance.IsRecentlyChecked {
prefix += "+" + fillerCharacter
} else {
prefix += "-" + fillerCharacter
}
}
entry := fmt.Sprintf("%s%s", prefix, instance.Key.DisplayString())
if extendedOutput {
if tabulated {
entry = fmt.Sprintf("%s%s%s", entry, tabulatorScharacter, instance.TabulatedDescription(tabulatorScharacter))
} else {
entry = fmt.Sprintf("%s%s%s", entry, fillerCharacter, instance.HumanReadableDescription())
}
}
result := []string{entry}
for _, replica := range replicationMap[instance] {
replicasResult := getASCIITopologyEntry(depth+1, replica, replicationMap, extendedOutput, fillerCharacter, tabulated)
result = append(result, replicasResult...)
}
return result
}
// ASCIITopology returns a string representation of the topology of given cluster.
func ASCIITopology(clusterName string, historyTimestampPattern string, tabulated bool) (result string, err error) {
fillerCharacter := asciiFillerCharacter
var instances [](*Instance)
if historyTimestampPattern == "" {
instances, err = ReadClusterInstances(clusterName)
} else {
instances, err = ReadHistoryClusterInstances(clusterName, historyTimestampPattern)
}
if err != nil {
return "", err
}
instancesMap := make(map[InstanceKey](*Instance))
for _, instance := range instances {
log.Debugf("instanceKey: %+v", instance.Key)
instancesMap[instance.Key] = instance
}
replicationMap := make(map[*Instance]([]*Instance))
var masterInstance *Instance
// Investigate replicas:
for _, instance := range instances {
master, ok := instancesMap[instance.MasterKey]
if ok {
if _, ok := replicationMap[master]; !ok {
replicationMap[master] = [](*Instance){}
}
replicationMap[master] = append(replicationMap[master], instance)
} else {
masterInstance = instance
}
}
// Get entries:
var entries []string
if masterInstance != nil {
// Single master
entries = getASCIITopologyEntry(0, masterInstance, replicationMap, historyTimestampPattern == "", fillerCharacter, tabulated)
} else {
// Co-masters? For visualization we put each in its own branch while ignoring its other co-masters.
for _, instance := range instances {
if instance.IsCoMaster {
entries = append(entries, getASCIITopologyEntry(1, instance, replicationMap, historyTimestampPattern == "", fillerCharacter, tabulated)...)
}
}
}
// Beautify: make sure the "[...]" part is nicely aligned for all instances.
if tabulated {
entries = util.Tabulate(entries, "|", "|", util.TabulateLeft, util.TabulateRight)
} else {
indentationCharacter := "["
maxIndent := 0
for _, entry := range entries {
maxIndent = math.MaxInt(maxIndent, strings.Index(entry, indentationCharacter))
}
for i, entry := range entries {
entryIndent := strings.Index(entry, indentationCharacter)
if maxIndent > entryIndent {
tokens := strings.SplitN(entry, indentationCharacter, 2)
newEntry := fmt.Sprintf("%s%s%s%s", tokens[0], strings.Repeat(fillerCharacter, maxIndent-entryIndent), indentationCharacter, tokens[1])
entries[i] = newEntry
}
}
}
// Turn into string
result = strings.Join(entries, "\n")
return result, nil
}
func shouldPostponeRelocatingReplica(replica *Instance, postponedFunctionsContainer *PostponedFunctionsContainer) bool {
if postponedFunctionsContainer == nil {
return false
}
if config.Config.PostponeReplicaRecoveryOnLagMinutes > 0 &&
replica.SQLDelay > config.Config.PostponeReplicaRecoveryOnLagMinutes*60 {
// This replica is lagging very much, AND
// we're configured to postpone operation on this replica so as not to delay everyone else.
return true
}
if replica.LastDiscoveryLatency > ReasonableDiscoveryLatency {
return true
}
return false
}
// GetInstanceMaster synchronously reaches into the replication topology
// and retrieves master's data
func GetInstanceMaster(instance *Instance) (*Instance, error) {
master, err := ReadTopologyInstance(&instance.MasterKey)
return master, err
}
// InstancesAreSiblings checks whether both instances are replicating from same master
func InstancesAreSiblings(instance0, instance1 *Instance) bool {
if !instance0.IsReplica() {
return false
}
if !instance1.IsReplica() {
return false
}
if instance0.Key.Equals(&instance1.Key) {
// same instance...
return false
}
return instance0.MasterKey.Equals(&instance1.MasterKey)
}
// InstanceIsMasterOf checks whether an instance is the master of another
func InstanceIsMasterOf(allegedMaster, allegedReplica *Instance) bool {
if !allegedReplica.IsReplica() {
return false
}
if allegedMaster.Key.Equals(&allegedReplica.Key) {
// same instance...
return false
}
return allegedMaster.Key.Equals(&allegedReplica.MasterKey)
}
// MoveEquivalent will attempt moving instance indicated by instanceKey below another instance,
// based on known master coordinates equivalence
func MoveEquivalent(instanceKey, otherKey *InstanceKey) (*Instance, error) {
instance, found, err := ReadInstance(instanceKey)
if err != nil || !found {
return instance, err
}
if instance.Key.Equals(otherKey) {
return instance, fmt.Errorf("MoveEquivalent: attempt to move an instance below itself %+v", instance.Key)
}
// Are there equivalent coordinates to this instance?
instanceCoordinates := &InstanceBinlogCoordinates{Key: instance.MasterKey, Coordinates: instance.ExecBinlogCoordinates}
binlogCoordinates, err := GetEquivalentBinlogCoordinatesFor(instanceCoordinates, otherKey)
if err != nil {
return instance, err
}
if binlogCoordinates == nil {
return instance, fmt.Errorf("No equivalent coordinates found for %+v replicating from %+v at %+v", instance.Key, instance.MasterKey, instance.ExecBinlogCoordinates)
}
// For performance reasons, we did all the above before even checking the replica is stopped or stopping it at all.
// This allows us to quickly skip the entire operation should there NOT be coordinates.
// To elaborate: if the replica is actually running AND making progress, it is unlikely/impossible for it to have
// equivalent coordinates, as the current coordinates are like to have never been seen.
// This excludes the case, for example, that the master is itself not replicating.
// Now if we DO get to happen on equivalent coordinates, we need to double check. For CHANGE MASTER to happen we must
// stop the replica anyhow. But then let's verify the position hasn't changed.
knownExecBinlogCoordinates := instance.ExecBinlogCoordinates
instance, err = StopSlave(instanceKey)
if err != nil {
goto Cleanup
}
if !instance.ExecBinlogCoordinates.Equals(&knownExecBinlogCoordinates) {
// Seems like things were still running... We don't have an equivalence point
err = fmt.Errorf("MoveEquivalent(): ExecBinlogCoordinates changed after stopping replication on %+v; aborting", instance.Key)
goto Cleanup
}
instance, err = ChangeMasterTo(instanceKey, otherKey, binlogCoordinates, false, GTIDHintNeutral)
Cleanup:
instance, _ = StartSlave(instanceKey)
if err == nil {
message := fmt.Sprintf("moved %+v via equivalence coordinates below %+v", *instanceKey, *otherKey)
log.Debugf(message)
AuditOperation("move-equivalent", instanceKey, message)
}
return instance, err
}
// MoveUp will attempt moving instance indicated by instanceKey up the topology hierarchy.
// It will perform all safety and sanity checks and will tamper with this instance's replication
// as well as its master.
func MoveUp(instanceKey *InstanceKey) (*Instance, error) {
instance, err := ReadTopologyInstance(instanceKey)
if err != nil {
return instance, err
}
if !instance.IsReplica() {
return instance, fmt.Errorf("instance is not a replica: %+v", instanceKey)
}
rinstance, _, _ := ReadInstance(&instance.Key)
if canMove, merr := rinstance.CanMove(); !canMove {
return instance, merr
}
master, err := GetInstanceMaster(instance)
if err != nil {
return instance, log.Errorf("Cannot GetInstanceMaster() for %+v. error=%+v", instance.Key, err)
}
if !master.IsReplica() {
return instance, fmt.Errorf("master is not a replica itself: %+v", master.Key)
}
if canReplicate, err := instance.CanReplicateFrom(master); canReplicate == false {
return instance, err
}
if master.IsBinlogServer() {
// Quick solution via binlog servers
return Repoint(instanceKey, &master.MasterKey, GTIDHintDeny)
}
log.Infof("Will move %+v up the topology", *instanceKey)
if maintenanceToken, merr := BeginMaintenance(instanceKey, GetMaintenanceOwner(), "move up"); merr != nil {
err = fmt.Errorf("Cannot begin maintenance on %+v", *instanceKey)
goto Cleanup
} else {
defer EndMaintenance(maintenanceToken)
}
if maintenanceToken, merr := BeginMaintenance(&master.Key, GetMaintenanceOwner(), fmt.Sprintf("child %+v moves up", *instanceKey)); merr != nil {
err = fmt.Errorf("Cannot begin maintenance on %+v", master.Key)
goto Cleanup
} else {
defer EndMaintenance(maintenanceToken)
}
if !instance.UsingMariaDBGTID {
master, err = StopSlave(&master.Key)
if err != nil {
goto Cleanup
}
}
instance, err = StopSlave(instanceKey)
if err != nil {
goto Cleanup
}
if !instance.UsingMariaDBGTID {
instance, err = StartSlaveUntilMasterCoordinates(instanceKey, &master.SelfBinlogCoordinates)
if err != nil {
goto Cleanup
}
}
// We can skip hostname unresolve; we just copy+paste whatever our master thinks of its master.
instance, err = ChangeMasterTo(instanceKey, &master.MasterKey, &master.ExecBinlogCoordinates, true, GTIDHintDeny)
if err != nil {
goto Cleanup
}
Cleanup:
instance, _ = StartSlave(instanceKey)
if !instance.UsingMariaDBGTID {
master, _ = StartSlave(&master.Key)
}
if err != nil {
return instance, log.Errore(err)
}
// and we're done (pending deferred functions)
AuditOperation("move-up", instanceKey, fmt.Sprintf("moved up %+v. Previous master: %+v", *instanceKey, master.Key))
return instance, err
}
// MoveUpReplicas will attempt moving up all replicas of a given instance, at the same time.
// Clock-time, this is fater than moving one at a time. However this means all replicas of the given instance, and the instance itself,
// will all stop replicating together.
func MoveUpReplicas(instanceKey *InstanceKey, pattern string) ([](*Instance), *Instance, error, []error) {
res := [](*Instance){}
errs := []error{}
replicaMutex := make(chan bool, 1)
var barrier chan *InstanceKey
instance, err := ReadTopologyInstance(instanceKey)
if err != nil {
return res, nil, err, errs
}
if !instance.IsReplica() {
return res, instance, fmt.Errorf("instance is not a replica: %+v", instanceKey), errs
}
_, err = GetInstanceMaster(instance)
if err != nil {
return res, instance, log.Errorf("Cannot GetInstanceMaster() for %+v. error=%+v", instance.Key, err), errs
}
if instance.IsBinlogServer() {
replicas, err, errors := RepointReplicasTo(instanceKey, pattern, &instance.MasterKey)
// Bail out!
return replicas, instance, err, errors
}
replicas, err := ReadReplicaInstances(instanceKey)
if err != nil {
return res, instance, err, errs
}
replicas = filterInstancesByPattern(replicas, pattern)
if len(replicas) == 0 {
return res, instance, nil, errs
}
log.Infof("Will move replicas of %+v up the topology", *instanceKey)
if maintenanceToken, merr := BeginMaintenance(instanceKey, GetMaintenanceOwner(), "move up replicas"); merr != nil {
err = fmt.Errorf("Cannot begin maintenance on %+v", *instanceKey)
goto Cleanup
} else {
defer EndMaintenance(maintenanceToken)
}
for _, replica := range replicas {
if maintenanceToken, merr := BeginMaintenance(&replica.Key, GetMaintenanceOwner(), fmt.Sprintf("%+v moves up", replica.Key)); merr != nil {
err = fmt.Errorf("Cannot begin maintenance on %+v", replica.Key)
goto Cleanup
} else {
defer EndMaintenance(maintenanceToken)
}
}
instance, err = StopSlave(instanceKey)
if err != nil {
goto Cleanup
}
barrier = make(chan *InstanceKey)
for _, replica := range replicas {
replica := replica
go func() {
defer func() {
defer func() { barrier <- &replica.Key }()
StartSlave(&replica.Key)
}()
var replicaErr error
ExecuteOnTopology(func() {
if canReplicate, err := replica.CanReplicateFrom(instance); canReplicate == false || err != nil {
replicaErr = err
return
}
if instance.IsBinlogServer() {
// Special case. Just repoint
replica, err = Repoint(&replica.Key, instanceKey, GTIDHintDeny)
if err != nil {
replicaErr = err
return
}
} else {
// Normal case. Do the math.
replica, err = StopSlave(&replica.Key)
if err != nil {
replicaErr = err
return
}
replica, err = StartSlaveUntilMasterCoordinates(&replica.Key, &instance.SelfBinlogCoordinates)
if err != nil {
replicaErr = err
return
}
replica, err = ChangeMasterTo(&replica.Key, &instance.MasterKey, &instance.ExecBinlogCoordinates, false, GTIDHintDeny)
if err != nil {
replicaErr = err
return
}
}
})
func() {
replicaMutex <- true
defer func() { <-replicaMutex }()
if replicaErr == nil {
res = append(res, replica)
} else {
errs = append(errs, replicaErr)
}
}()
}()
}
for range replicas {
<-barrier
}
Cleanup:
instance, _ = StartSlave(instanceKey)
if err != nil {
return res, instance, log.Errore(err), errs
}
if len(errs) == len(replicas) {
// All returned with error
return res, instance, log.Error("Error on all operations"), errs
}
AuditOperation("move-up-replicas", instanceKey, fmt.Sprintf("moved up %d/%d replicas of %+v. New master: %+v", len(res), len(replicas), *instanceKey, instance.MasterKey))
return res, instance, err, errs
}
// MoveBelow will attempt moving instance indicated by instanceKey below its supposed sibling indicated by sinblingKey.
// It will perform all safety and sanity checks and will tamper with this instance's replication
// as well as its sibling.
func MoveBelow(instanceKey, siblingKey *InstanceKey) (*Instance, error) {
instance, err := ReadTopologyInstance(instanceKey)
if err != nil {
return instance, err
}
sibling, err := ReadTopologyInstance(siblingKey)
if err != nil {
return instance, err
}
if sibling.IsBinlogServer() {
// Binlog server has same coordinates as master
// Easy solution!
return Repoint(instanceKey, &sibling.Key, GTIDHintDeny)
}
rinstance, _, _ := ReadInstance(&instance.Key)
if canMove, merr := rinstance.CanMove(); !canMove {
return instance, merr
}
rinstance, _, _ = ReadInstance(&sibling.Key)
if canMove, merr := rinstance.CanMove(); !canMove {
return instance, merr
}
if !InstancesAreSiblings(instance, sibling) {
return instance, fmt.Errorf("instances are not siblings: %+v, %+v", *instanceKey, *siblingKey)
}
if canReplicate, err := instance.CanReplicateFrom(sibling); !canReplicate {
return instance, err
}
log.Infof("Will move %+v below %+v", instanceKey, siblingKey)
if maintenanceToken, merr := BeginMaintenance(instanceKey, GetMaintenanceOwner(), fmt.Sprintf("move below %+v", *siblingKey)); merr != nil {
err = fmt.Errorf("Cannot begin maintenance on %+v", *instanceKey)
goto Cleanup
} else {
defer EndMaintenance(maintenanceToken)
}
if maintenanceToken, merr := BeginMaintenance(siblingKey, GetMaintenanceOwner(), fmt.Sprintf("%+v moves below this", *instanceKey)); merr != nil {
err = fmt.Errorf("Cannot begin maintenance on %+v", *siblingKey)
goto Cleanup
} else {
defer EndMaintenance(maintenanceToken)
}
instance, err = StopSlave(instanceKey)
if err != nil {
goto Cleanup
}
sibling, err = StopSlave(siblingKey)
if err != nil {
goto Cleanup
}
if instance.ExecBinlogCoordinates.SmallerThan(&sibling.ExecBinlogCoordinates) {
instance, err = StartSlaveUntilMasterCoordinates(instanceKey, &sibling.ExecBinlogCoordinates)
if err != nil {
goto Cleanup
}
} else if sibling.ExecBinlogCoordinates.SmallerThan(&instance.ExecBinlogCoordinates) {
sibling, err = StartSlaveUntilMasterCoordinates(siblingKey, &instance.ExecBinlogCoordinates)
if err != nil {
goto Cleanup
}
}
// At this point both siblings have executed exact same statements and are identical
instance, err = ChangeMasterTo(instanceKey, &sibling.Key, &sibling.SelfBinlogCoordinates, false, GTIDHintDeny)
if err != nil {
goto Cleanup
}
Cleanup:
instance, _ = StartSlave(instanceKey)
sibling, _ = StartSlave(siblingKey)
if err != nil {
return instance, log.Errore(err)
}
// and we're done (pending deferred functions)
AuditOperation("move-below", instanceKey, fmt.Sprintf("moved %+v below %+v", *instanceKey, *siblingKey))
return instance, err
}
func canReplicateAssumingOracleGTID(instance, masterInstance *Instance) (canReplicate bool, err error) {
subtract, err := GTIDSubtract(&instance.Key, masterInstance.GtidPurged, instance.ExecutedGtidSet)
if err != nil {
return false, err
}
subtractGtidSet, err := NewOracleGtidSet(subtract)
if err != nil {
return false, err
}
return subtractGtidSet.IsEmpty(), nil
}
func instancesAreGTIDAndCompatible(instance, otherInstance *Instance) (isOracleGTID bool, isMariaDBGTID, compatible bool) {
isOracleGTID = (instance.UsingOracleGTID && otherInstance.SupportsOracleGTID)
isMariaDBGTID = (instance.UsingMariaDBGTID && otherInstance.IsMariaDB())
compatible = isOracleGTID || isMariaDBGTID
return isOracleGTID, isMariaDBGTID, compatible
}
func CheckMoveViaGTID(instance, otherInstance *Instance) (err error) {
isOracleGTID, _, moveCompatible := instancesAreGTIDAndCompatible(instance, otherInstance)
if !moveCompatible {
return fmt.Errorf("Instances %+v, %+v not GTID compatible or not using GTID", instance.Key, otherInstance.Key)
}
if isOracleGTID {
canReplicate, err := canReplicateAssumingOracleGTID(instance, otherInstance)
if err != nil {
return err
}
if !canReplicate {
return fmt.Errorf("Instance %+v has purged GTID entries not found on %+v", otherInstance.Key, instance.Key)
}
}
return nil
}
// moveInstanceBelowViaGTID will attempt moving given instance below another instance using either Oracle GTID or MariaDB GTID.
func moveInstanceBelowViaGTID(instance, otherInstance *Instance) (*Instance, error) {
rinstance, _, _ := ReadInstance(&instance.Key)
if canMove, merr := rinstance.CanMoveViaMatch(); !canMove {
return instance, merr
}
if canReplicate, err := instance.CanReplicateFrom(otherInstance); !canReplicate {
return instance, err
}
if err := CheckMoveViaGTID(instance, otherInstance); err != nil {
return instance, err
}
log.Infof("Will move %+v below %+v via GTID", instance.Key, otherInstance.Key)
instanceKey := &instance.Key
otherInstanceKey := &otherInstance.Key
var err error
if maintenanceToken, merr := BeginMaintenance(instanceKey, GetMaintenanceOwner(), fmt.Sprintf("move below %+v", *otherInstanceKey)); merr != nil {
err = fmt.Errorf("Cannot begin maintenance on %+v", *instanceKey)
goto Cleanup
} else {
defer EndMaintenance(maintenanceToken)
}
instance, err = StopSlave(instanceKey)
if err != nil {
goto Cleanup
}
instance, err = ChangeMasterTo(instanceKey, &otherInstance.Key, &otherInstance.SelfBinlogCoordinates, false, GTIDHintForce)
if err != nil {
goto Cleanup
}
Cleanup:
instance, _ = StartSlave(instanceKey)
if err != nil {
return instance, log.Errore(err)
}
// and we're done (pending deferred functions)
AuditOperation("move-below-gtid", instanceKey, fmt.Sprintf("moved %+v below %+v", *instanceKey, *otherInstanceKey))
return instance, err
}
// MoveBelowGTID will attempt moving instance indicated by instanceKey below another instance using either Oracle GTID or MariaDB GTID.
func MoveBelowGTID(instanceKey, otherKey *InstanceKey) (*Instance, error) {
instance, err := ReadTopologyInstance(instanceKey)
if err != nil {
return instance, err
}
other, err := ReadTopologyInstance(otherKey)
if err != nil {
return instance, err
}
return moveInstanceBelowViaGTID(instance, other)
}
// moveReplicasViaGTID moves a list of replicas under another instance via GTID, returning those replicas
// that could not be moved (do not use GTID or had GTID errors)
func moveReplicasViaGTID(replicas [](*Instance), other *Instance, postponedFunctionsContainer *PostponedFunctionsContainer) (movedReplicas [](*Instance), unmovedReplicas [](*Instance), err error, errs []error) {
replicas = RemoveNilInstances(replicas)
replicas = RemoveInstance(replicas, &other.Key)
if len(replicas) == 0 {
// Nothing to do
return movedReplicas, unmovedReplicas, nil, errs
}
log.Infof("moveReplicasViaGTID: Will move %+v replicas below %+v via GTID", len(replicas), other.Key)
var waitGroup sync.WaitGroup
var replicaMutex sync.Mutex
for _, replica := range replicas {
replica := replica
waitGroup.Add(1)
// Parallelize repoints
go func() {
defer waitGroup.Done()
moveFunc := func() error {
movedReplica, replicaErr := moveInstanceBelowViaGTID(replica, other)
if replicaErr != nil && movedReplica != nil {
replica = movedReplica
}
// After having moved replicas, update local shared variables:
replicaMutex.Lock()
defer replicaMutex.Unlock()
if replicaErr == nil {
movedReplicas = append(movedReplicas, replica)
} else {
unmovedReplicas = append(unmovedReplicas, replica)
errs = append(errs, replicaErr)
}
return replicaErr
}
if shouldPostponeRelocatingReplica(replica, postponedFunctionsContainer) {
postponedFunctionsContainer.AddPostponedFunction(moveFunc, fmt.Sprintf("move-replicas-gtid %+v", replica.Key))
// We bail out and trust our invoker to later call upon this postponed function
} else {
ExecuteOnTopology(func() { moveFunc() })
}
}()
}
waitGroup.Wait()
if len(errs) == len(replicas) {
// All returned with error
return movedReplicas, unmovedReplicas, fmt.Errorf("moveReplicasViaGTID: Error on all %+v operations", len(errs)), errs
}
AuditOperation("move-replicas-gtid", &other.Key, fmt.Sprintf("moved %d/%d replicas below %+v via GTID", len(movedReplicas), len(replicas), other.Key))
return movedReplicas, unmovedReplicas, err, errs
}
// MoveReplicasGTID will (attempt to) move all replicas of given master below given instance.
func MoveReplicasGTID(masterKey *InstanceKey, belowKey *InstanceKey, pattern string) (movedReplicas [](*Instance), unmovedReplicas [](*Instance), err error, errs []error) {
belowInstance, err := ReadTopologyInstance(belowKey)
if err != nil {
// Can't access "below" ==> can't move replicas beneath it
return movedReplicas, unmovedReplicas, err, errs
}
// replicas involved
replicas, err := ReadReplicaInstancesIncludingBinlogServerSubReplicas(masterKey)
if err != nil {
return movedReplicas, unmovedReplicas, err, errs
}
replicas = filterInstancesByPattern(replicas, pattern)
movedReplicas, unmovedReplicas, err, errs = moveReplicasViaGTID(replicas, belowInstance, nil)
if err != nil {
log.Errore(err)
}
if len(unmovedReplicas) > 0 {
err = fmt.Errorf("MoveReplicasGTID: only moved %d out of %d replicas of %+v; error is: %+v", len(movedReplicas), len(replicas), *masterKey, err)
}
return movedReplicas, unmovedReplicas, err, errs
}
// Repoint connects a replica to a master using its exact same executing coordinates.
// The given masterKey can be null, in which case the existing master is used.
// Two use cases:
// - masterKey is nil: use case is corrupted relay logs on replica
// - masterKey is not nil: using Binlog servers (coordinates remain the same)
func Repoint(instanceKey *InstanceKey, masterKey *InstanceKey, gtidHint OperationGTIDHint) (*Instance, error) {
instance, err := ReadTopologyInstance(instanceKey)
if err != nil {
return instance, err
}
if !instance.IsReplica() {
return instance, fmt.Errorf("instance is not a replica: %+v", *instanceKey)
}
if masterKey == nil {
masterKey = &instance.MasterKey
}
// With repoint we *prefer* the master to be alive, but we don't strictly require it.
// The use case for the master being alive is with hostname-resolve or hostname-unresolve: asking the replica
// to reconnect to its same master while changing the MASTER_HOST in CHANGE MASTER TO due to DNS changes etc.
master, err := ReadTopologyInstance(masterKey)
masterIsAccessible := (err == nil)
if !masterIsAccessible {
master, _, err = ReadInstance(masterKey)
if err != nil {
return instance, err
}
}
if canReplicate, err := instance.CanReplicateFrom(master); !canReplicate {
return instance, err
}
// if a binlog server check it is sufficiently up to date
if master.IsBinlogServer() {
// "Repoint" operation trusts the user. But only so much. Repoiting to a binlog server which is not yet there is strictly wrong.
if !instance.ExecBinlogCoordinates.SmallerThanOrEquals(&master.SelfBinlogCoordinates) {
return instance, fmt.Errorf("repoint: binlog server %+v is not sufficiently up to date to repoint %+v below it", *masterKey, *instanceKey)
}
}
log.Infof("Will repoint %+v to master %+v", *instanceKey, *masterKey)
if maintenanceToken, merr := BeginMaintenance(instanceKey, GetMaintenanceOwner(), "repoint"); merr != nil {
err = fmt.Errorf("Cannot begin maintenance on %+v", *instanceKey)
goto Cleanup
} else {
defer EndMaintenance(maintenanceToken)
}
instance, err = StopSlave(instanceKey)
if err != nil {
goto Cleanup
}
// See above, we are relaxed about the master being accessible/inaccessible.
// If accessible, we wish to do hostname-unresolve. If inaccessible, we can skip the test and not fail the
// ChangeMasterTo operation. This is why we pass "!masterIsAccessible" below.
if instance.ExecBinlogCoordinates.IsEmpty() {
instance.ExecBinlogCoordinates.LogFile = "orchestrator-unknown-log-file"
}
instance, err = ChangeMasterTo(instanceKey, masterKey, &instance.ExecBinlogCoordinates, !masterIsAccessible, gtidHint)
if err != nil {
goto Cleanup
}
Cleanup:
instance, _ = StartSlave(instanceKey)
if err != nil {
return instance, log.Errore(err)
}
// and we're done (pending deferred functions)
AuditOperation("repoint", instanceKey, fmt.Sprintf("replica %+v repointed to master: %+v", *instanceKey, *masterKey))
return instance, err
}
// RepointTo repoints list of replicas onto another master.
// Binlog Server is the major use case
func RepointTo(replicas [](*Instance), belowKey *InstanceKey) ([](*Instance), error, []error) {
res := [](*Instance){}
errs := []error{}
replicas = RemoveInstance(replicas, belowKey)
if len(replicas) == 0 {
// Nothing to do
return res, nil, errs
}
if belowKey == nil {
return res, log.Errorf("RepointTo received nil belowKey"), errs
}
log.Infof("Will repoint %+v replicas below %+v", len(replicas), *belowKey)
barrier := make(chan *InstanceKey)
replicaMutex := make(chan bool, 1)
for _, replica := range replicas {
replica := replica
// Parallelize repoints
go func() {
defer func() { barrier <- &replica.Key }()
ExecuteOnTopology(func() {
replica, replicaErr := Repoint(&replica.Key, belowKey, GTIDHintNeutral)
func() {
// Instantaneous mutex.
replicaMutex <- true
defer func() { <-replicaMutex }()
if replicaErr == nil {
res = append(res, replica)
} else {
errs = append(errs, replicaErr)
}
}()
})
}()
}
for range replicas {
<-barrier
}
if len(errs) == len(replicas) {
// All returned with error
return res, log.Error("Error on all operations"), errs
}
AuditOperation("repoint-to", belowKey, fmt.Sprintf("repointed %d/%d replicas to %+v", len(res), len(replicas), *belowKey))
return res, nil, errs
}
// RepointReplicasTo repoints replicas of a given instance (possibly filtered) onto another master.
// Binlog Server is the major use case
func RepointReplicasTo(instanceKey *InstanceKey, pattern string, belowKey *InstanceKey) ([](*Instance), error, []error) {
res := [](*Instance){}
errs := []error{}
replicas, err := ReadReplicaInstances(instanceKey)
if err != nil {
return res, err, errs
}
replicas = RemoveInstance(replicas, belowKey)
replicas = filterInstancesByPattern(replicas, pattern)
if len(replicas) == 0 {
// Nothing to do
return res, nil, errs
}
if belowKey == nil {
// Default to existing master. All replicas are of the same master, hence just pick one.
belowKey = &replicas[0].MasterKey
}
log.Infof("Will repoint replicas of %+v to %+v", *instanceKey, *belowKey)
return RepointTo(replicas, belowKey)
}
// RepointReplicas repoints all replicas of a given instance onto its existing master.
func RepointReplicas(instanceKey *InstanceKey, pattern string) ([](*Instance), error, []error) {
return RepointReplicasTo(instanceKey, pattern, nil)
}
// MakeCoMaster will attempt to make an instance co-master with its master, by making its master a replica of its own.
// This only works out if the master is not replicating; the master does not have a known master (it may have an unknown master).
func MakeCoMaster(instanceKey *InstanceKey) (*Instance, error) {
instance, err := ReadTopologyInstance(instanceKey)
if err != nil {
return instance, err
}
if canMove, merr := instance.CanMove(); !canMove {
return instance, merr
}
master, err := GetInstanceMaster(instance)
if err != nil {
return instance, err
}
log.Debugf("Will check whether %+v's master (%+v) can become its co-master", instance.Key, master.Key)
if canMove, merr := master.CanMoveAsCoMaster(); !canMove {
return instance, merr
}
if instanceKey.Equals(&master.MasterKey) {
return instance, fmt.Errorf("instance %+v is already co master of %+v", instance.Key, master.Key)
}
if !instance.ReadOnly {
return instance, fmt.Errorf("instance %+v is not read-only; first make it read-only before making it co-master", instance.Key)
}
if master.IsCoMaster {
// We allow breaking of an existing co-master replication. Here's the breakdown:
// Ideally, this would not eb allowed, and we would first require the user to RESET SLAVE on 'master'
// prior to making it participate as co-master with our 'instance'.
// However there's the problem that upon RESET SLAVE we lose the replication's user/password info.
// Thus, we come up with the following rule:
// If S replicates from M1, and M1<->M2 are co masters, we allow S to become co-master of M1 (S<->M1) if:
// - M1 is writeable
// - M2 is read-only or is unreachable/invalid
// - S is read-only
// And so we will be replacing one read-only co-master with another.
otherCoMaster, found, _ := ReadInstance(&master.MasterKey)
if found && otherCoMaster.IsLastCheckValid && !otherCoMaster.ReadOnly {
return instance, fmt.Errorf("master %+v is already co-master with %+v, and %+v is alive, and not read-only; cowardly refusing to demote it. Please set it as read-only beforehand", master.Key, otherCoMaster.Key, otherCoMaster.Key)
}
// OK, good to go.
} else if _, found, _ := ReadInstance(&master.MasterKey); found {
return instance, fmt.Errorf("%+v is not a real master; it replicates from: %+v", master.Key, master.MasterKey)
}
if canReplicate, err := master.CanReplicateFrom(instance); !canReplicate {
return instance, err
}
log.Infof("Will make %+v co-master of %+v", instanceKey, master.Key)
var gitHint OperationGTIDHint = GTIDHintNeutral
if maintenanceToken, merr := BeginMaintenance(instanceKey, GetMaintenanceOwner(), fmt.Sprintf("make co-master of %+v", master.Key)); merr != nil {
err = fmt.Errorf("Cannot begin maintenance on %+v", *instanceKey)
goto Cleanup
} else {
defer EndMaintenance(maintenanceToken)
}
if maintenanceToken, merr := BeginMaintenance(&master.Key, GetMaintenanceOwner(), fmt.Sprintf("%+v turns into co-master of this", *instanceKey)); merr != nil {
err = fmt.Errorf("Cannot begin maintenance on %+v", master.Key)
goto Cleanup
} else {
defer EndMaintenance(maintenanceToken)
}
// the coMaster used to be merely a replica. Just point master into *some* position
// within coMaster...
if master.IsReplica() {
// this is the case of a co-master. For masters, the StopSlave operation throws an error, and
// there's really no point in doing it.
master, err = StopSlave(&master.Key)
if err != nil {
goto Cleanup
}
}
if !master.HasReplicationCredentials {
// Let's try , if possible, to get credentials from replica. Best effort.
if replicationUser, replicationPassword, credentialsErr := ReadReplicationCredentials(&instance.Key); credentialsErr == nil {
log.Debugf("Got credentials from a replica. will now apply")
_, err = ChangeMasterCredentials(&master.Key, replicationUser, replicationPassword)
if err != nil {
goto Cleanup
}
}
}
if instance.AllowTLS {
log.Debugf("Enabling SSL replication")
_, err = EnableMasterSSL(&master.Key)
if err != nil {
goto Cleanup
}
}
if instance.UsingOracleGTID {
gitHint = GTIDHintForce
}
master, err = ChangeMasterTo(&master.Key, instanceKey, &instance.SelfBinlogCoordinates, false, gitHint)
if err != nil {
goto Cleanup
}
Cleanup:
master, _ = StartSlave(&master.Key)
if err != nil {
return instance, log.Errore(err)
}
// and we're done (pending deferred functions)
AuditOperation("make-co-master", instanceKey, fmt.Sprintf("%+v made co-master of %+v", *instanceKey, master.Key))