forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuiltinbackupengine.go
More file actions
1477 lines (1329 loc) · 57.7 KB
/
builtinbackupengine.go
File metadata and controls
1477 lines (1329 loc) · 57.7 KB
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 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.
*/
package mysqlctl
import (
"bufio"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash"
"hash/crc32"
"io"
"os"
"path"
"path/filepath"
"strconv"
"sync/atomic"
"time"
"github.com/spf13/pflag"
"golang.org/x/sync/errgroup"
"vitess.io/vitess/go/fileutil"
"vitess.io/vitess/go/ioutil"
"vitess.io/vitess/go/mysql"
"vitess.io/vitess/go/mysql/replication"
"vitess.io/vitess/go/netutil"
"vitess.io/vitess/go/os2"
"vitess.io/vitess/go/protoutil"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/logutil"
stats "vitess.io/vitess/go/vt/mysqlctl/backupstats"
"vitess.io/vitess/go/vt/mysqlctl/backupstorage"
"vitess.io/vitess/go/vt/servenv"
"vitess.io/vitess/go/vt/topo"
"vitess.io/vitess/go/vt/topo/topoproto"
"vitess.io/vitess/go/vt/utils"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vttablet/tmclient"
mysqlctlpb "vitess.io/vitess/go/vt/proto/mysqlctl"
tabletmanagerdatapb "vitess.io/vitess/go/vt/proto/tabletmanagerdata"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
)
const (
builtinBackupEngineName = "builtin"
AutoIncrementalFromPos = "auto"
dataDictionaryFile = "mysql.ibd"
// How many times we will retry file operations. Note that a file operation that
// returns a vtrpc.Code_FAILED_PRECONDITION error is considered fatal and we will
// not retry.
maxRetriesPerFile = 1
maxFileCloseRetries = 20 // At this point we should consider it permanent
)
var (
// BuiltinBackupMysqldTimeout is how long ExecuteBackup should wait for response from mysqld.Shutdown.
// It can later be extended for other calls to mysqld during backup functions.
// Exported for testing.
BuiltinBackupMysqldTimeout = 10 * time.Minute
builtinBackupProgress = 5 * time.Second
// Controls the size of the IO buffer used when reading files during backups.
builtinBackupFileReadBufferSize uint
// Controls the size of the IO buffer used when writing files during restores.
builtinBackupFileWriteBufferSize uint = 2 * 1024 * 1024 /* 2 MiB */
// Controls the size of the IO buffer used when writing to backupstorage
// engines during backups. The backupstorage may be a physical file,
// network, or something else.
builtinBackupStorageWriteBufferSize = 2 * 1024 * 1024 /* 2 MiB */
// The directory where incremental restore files, namely binlog files, are extracted to.
// In k8s environments, this should be set to a directory that is shared between the vttablet and mysqld pods.
// The path should exist.
// When empty, the default OS temp dir is assumed.
builtinIncrementalRestorePath = ""
)
// BuiltinBackupEngine encapsulates the logic of the builtin engine
// it implements the BackupEngine interface and contains all the logic
// required to implement a backup/restore by copying files from and to
// the correct location / storage bucket
type BuiltinBackupEngine struct{}
// builtinBackupManifest represents the backup. It lists all the files, the
// Position that the backup was taken at, the compression engine used, etc.
type builtinBackupManifest struct {
// BackupManifest is an anonymous embedding of the base manifest struct.
BackupManifest
// CompressionEngine stores which compression engine was originally provided
// to compress the files. Please note that if user has provided externalCompressorCmd
// then it will contain value 'external'. This field is used during restore routine to
// get a hint about what kind of compression was used.
CompressionEngine string `json:",omitempty"`
// FileEntries contains all the files in the backup
FileEntries []FileEntry
// SkipCompress is true if the backup files were NOT run through gzip.
// The field is expressed as a negative because it will come through as
// false for backups that were created before the field existed, and those
// backups all had compression enabled.
SkipCompress bool
// When CompressionEngine is "external", ExternalDecompressor may be
// consulted for the external decompressor command.
//
// When taking a backup with --compression-engine=external,
// ExternalDecompressor will be set to the value of
// --manifest-external-decompressor, if set, or else left as an empty
// string.
//
// When restoring from a backup with CompressionEngine "external",
// --external-decompressor will be consulted first and, if that is not set,
// ExternalDecompressor will be used. If neither are set, the restore will
// abort.
ExternalDecompressor string
}
// FileEntry is one file to backup
type FileEntry struct {
// Base is one of:
// - backupInnodbDataHomeDir for files that go into Mycnf.InnodbDataHomeDir
// - backupInnodbLogGroupHomeDir for files that go into Mycnf.InnodbLogGroupHomeDir
// - binLogDir for files that go in the binlog dir (base path of Mycnf.BinLogPath)
// - backupData for files that go into Mycnf.DataDir
Base string
// Name is the file name, relative to Base
Name string
// Hash is the hash of the final data (transformed and
// compressed if specified) stored in the BackupStorage.
Hash string
// ParentPath is an optional prefix to the Base path. If empty, it is ignored. Useful
// for writing files in a temporary directory
ParentPath string
// RetryCount specifies how many times we retried restoring/backing up this FileEntry.
// If we fail to restore/backup this FileEntry, we will retry up to maxRetriesPerFile times.
// Every time the builtin backup engine retries this file, we increment this field by 1.
// We don't care about adding this information to the MANIFEST and also to not cause any compatibility issue
// we are adding the - json tag to let Go know it can ignore the field.
RetryCount int `json:"-"`
}
func init() {
for _, cmd := range []string{"vtbackup", "vtcombo", "vttablet", "vttestserver", "vtctld", "vtctldclient"} {
servenv.OnParseFor(cmd, registerBuiltinBackupEngineFlags)
}
}
func registerBuiltinBackupEngineFlags(fs *pflag.FlagSet) {
utils.SetFlagDurationVar(fs, &BuiltinBackupMysqldTimeout, "builtinbackup-mysqld-timeout", BuiltinBackupMysqldTimeout, "how long to wait for mysqld to shutdown at the start of the backup.")
utils.SetFlagDurationVar(fs, &builtinBackupProgress, "builtinbackup-progress", builtinBackupProgress, "how often to send progress updates when backing up large files.")
fs.UintVar(&builtinBackupFileReadBufferSize, "builtinbackup-file-read-buffer-size", builtinBackupFileReadBufferSize, "read files using an IO buffer of this many bytes. Golang defaults are used when set to 0.")
fs.UintVar(&builtinBackupFileWriteBufferSize, "builtinbackup-file-write-buffer-size", builtinBackupFileWriteBufferSize, "write files using an IO buffer of this many bytes. Golang defaults are used when set to 0.")
fs.StringVar(&builtinIncrementalRestorePath, "builtinbackup-incremental-restore-path", builtinIncrementalRestorePath, "the directory where incremental restore files, namely binlog files, are extracted to. In k8s environments, this should be set to a directory that is shared between the vttablet and mysqld pods. The path should exist. When empty, the default OS temp dir is assumed.")
}
// fullPath returns the full path of the entry, based on its type.
// It validates that the resolved path does not escape the base directory
// via path traversal (e.g. "../../" sequences in fe.Name).
func (fe *FileEntry) fullPath(cnf *Mycnf) (string, error) {
// find the root to use
var root string
switch fe.Base {
case backupInnodbDataHomeDir:
root = cnf.InnodbDataHomeDir
case backupInnodbLogGroupHomeDir:
root = cnf.InnodbLogGroupHomeDir
case backupData:
root = cnf.DataDir
case backupBinlogDir:
root = filepath.Dir(cnf.BinLogPath)
default:
return "", vterrors.Errorf(vtrpcpb.Code_UNKNOWN, "unknown base: %v", fe.Base)
}
return fileutil.SafePathJoin(path.Join(fe.ParentPath, root), fe.Name)
}
// open attempts to open the file
func (fe *FileEntry) open(cnf *Mycnf, readOnly bool) (*os.File, error) {
name, err := fe.fullPath(cnf)
if err != nil {
return nil, vterrors.Wrapf(err, "cannot evaluate full name for %v", fe.Name)
}
var fd *os.File
if readOnly {
if fd, err = openForSequential(name); err != nil {
return nil, vterrors.Wrapf(err, "cannot open source file %v", name)
}
} else {
dir := path.Dir(name)
if err := os2.MkdirAll(dir); err != nil {
return nil, vterrors.Wrapf(err, "cannot create destination directory %v", dir)
}
if fd, err = os2.Create(name); err != nil {
return nil, vterrors.Wrapf(err, "cannot create destination file %v", name)
}
}
return fd, nil
}
// ExecuteBackup runs a backup based on given params. This could be a full or incremental backup.
// The function returns a BackupResult that indicates the usability of the backup, and an overall error.
func (be *BuiltinBackupEngine) ExecuteBackup(ctx context.Context, params BackupParams, bh backupstorage.BackupHandle) (BackupResult, error) {
params.Logger.Infof("Executing Backup at %v for keyspace/shard %v/%v on tablet %v, concurrency: %v, compress: %v, incrementalFromPos: %v",
params.BackupTime, params.Keyspace, params.Shard, params.TabletAlias, params.Concurrency, backupStorageCompress, params.IncrementalFromPos)
if isIncrementalBackup(params) {
return be.executeIncrementalBackup(ctx, params, bh)
}
return be.executeFullBackup(ctx, params, bh)
}
// getIncrementalFromPosGTIDSet turns the given string into a valid Mysql56GTIDSet
func getIncrementalFromPosGTIDSet(incrementalFromPos string) (replication.Mysql56GTIDSet, error) {
_, gtidSet, err := replication.DecodePositionMySQL56(incrementalFromPos)
if err != nil {
return nil, vterrors.Wrapf(err, "cannot decode position in incremental backup: %v", incrementalFromPos)
}
return gtidSet, nil
}
// executeIncrementalBackup runs an incremental backup, based on given 'incremental_from_pos', which can be:
// - A valid position
// - "auto", indicating the incremental backup should begin with last successful backup end position.
// The function returns a BackupResult that indicates the usability of the backup, and an overall error.
func (be *BuiltinBackupEngine) executeIncrementalBackup(ctx context.Context, params BackupParams, bh backupstorage.BackupHandle) (BackupResult, error) {
// Collect MySQL status:
// UUID
serverUUID, err := params.Mysqld.GetServerUUID(ctx)
if err != nil {
return BackupUnusable, vterrors.Wrap(err, "can't get server uuid")
}
mysqlVersion, err := params.Mysqld.GetVersionString(ctx)
if err != nil {
return BackupUnusable, vterrors.Wrap(err, "can't get MySQL version")
}
// We now need to figure out the GTIDSet from which we want to take the incremental backup. The user may have
// specified a position, or they may have specified "auto", or they may have specified a backup name, in which
// case we need to find the position of that backup.
var fromBackupName string
if params.IncrementalFromPos == AutoIncrementalFromPos {
// User has supplied "auto".
params.Logger.Infof("auto evaluating incremental_from_pos")
backupName, pos, err := findLatestSuccessfulBackupPosition(ctx, params, bh.Name())
if err != nil {
return BackupUnusable, err
}
fromBackupName = backupName
params.IncrementalFromPos = replication.EncodePosition(pos)
params.Logger.Infof("auto evaluated incremental_from_pos: %s", params.IncrementalFromPos)
}
if _, _, err := replication.DecodePositionMySQL56(params.IncrementalFromPos); err != nil {
// This does not seem to be a valid position. Maybe it's a backup name?
backupName := params.IncrementalFromPos
pos, err := findBackupPosition(ctx, params, backupName)
if err != nil {
return BackupUnusable, err
}
fromBackupName = backupName
params.IncrementalFromPos = replication.EncodePosition(pos)
params.Logger.Infof("evaluated incremental_from_pos using backup name %q: %s", backupName, params.IncrementalFromPos)
}
// params.IncrementalFromPos is a string. We want to turn that into a MySQL GTID
backupFromGTIDSet, err := getIncrementalFromPosGTIDSet(params.IncrementalFromPos)
if err != nil {
return BackupUnusable, err
}
// OK, we now have the formal MySQL GTID from which we want to take the incremental backup.
// binlogs may not contain information about purged GTIDs. e.g. some binlog.000003 may have
// previous GTIDs like 00021324-1111-1111-1111-111111111111:30-60, ie 1-29 range is missing. This can happen
// when a server is restored from backup and set with gtid_purged != "".
// This is fine!
// Shortly we will compare a binlog's "Previous GTIDs" with the backup's position. For the purpose of comparison, we
// ignore the purged GTIDs:
if err := params.Mysqld.FlushBinaryLogs(ctx); err != nil {
return BackupUnusable, vterrors.Wrapf(err, "cannot flush binary logs in incremental backup")
}
binaryLogs, err := params.Mysqld.GetBinaryLogs(ctx)
if err != nil {
return BackupUnusable, vterrors.Wrapf(err, "cannot get binary logs in incremental backup")
}
getPurgedGTIDSet := func() (replication.Position, replication.Mysql56GTIDSet, error) {
gtidPurged, err := params.Mysqld.GetGTIDPurged(ctx)
if err != nil {
return gtidPurged, nil, vterrors.Wrap(err, "can't get @@gtid_purged")
}
purgedGTIDSet, ok := gtidPurged.GTIDSet.(replication.Mysql56GTIDSet)
if !ok {
return gtidPurged, nil, vterrors.Errorf(vtrpcpb.Code_FAILED_PRECONDITION, "failed to parse a valid MySQL GTID set from value: %v", gtidPurged)
}
return gtidPurged, purgedGTIDSet, nil
}
// gtid_purged is important information. The restore flow uses this info to to complement binary logs' Previous-GTIDs.
// It is important to only get gtid_purged _after_ we've rotated into the new binary log, because the `FLUSH BINARY LOGS`
// command may also purge old logs, hence affecting the value of gtid_purged.
gtidPurged, purgedGTIDSet, err := getPurgedGTIDSet()
if err != nil {
return BackupUnusable, err
}
previousGTIDs := map[string]string{}
getBinlogPreviousGTIDs := func(ctx context.Context, binlog string) (gtids string, err error) {
gtids, ok := previousGTIDs[binlog]
if ok {
// Found a cached entry! No need to query again
return gtids, nil
}
gtids, err = params.Mysqld.GetPreviousGTIDs(ctx, binlog)
if err != nil {
return gtids, err
}
previousGTIDs[binlog] = gtids
return gtids, nil
}
binaryLogsToBackup, incrementalBackupFromGTID, incrementalBackupToGTID, err := ChooseBinlogsForIncrementalBackup(ctx, backupFromGTIDSet, purgedGTIDSet, binaryLogs, getBinlogPreviousGTIDs)
if err != nil {
return BackupUnusable, vterrors.Wrapf(err, "cannot get binary logs to backup in incremental backup")
}
if len(binaryLogsToBackup) == 0 {
// Empty backup.
return BackupEmpty, nil
}
incrementalBackupFromPosition, err := replication.ParsePosition(replication.Mysql56FlavorID, incrementalBackupFromGTID)
if err != nil {
return BackupUnusable, vterrors.Wrapf(err, "cannot parse position %v", incrementalBackupFromGTID)
}
incrementalBackupToPosition, err := replication.ParsePosition(replication.Mysql56FlavorID, incrementalBackupToGTID)
if err != nil {
return BackupUnusable, vterrors.Wrapf(err, "cannot parse position %v", incrementalBackupToGTID)
}
// The backup position is the GTISset of the last binary log (taken from Previous-GTIDs of the one-next binary log), and we
// also include gtid_purged ; this complies with the "standard" way MySQL "thinks" about GTIDs: there's gtid_executed, which includes
// everything that's ever been applied, and a subset of that is gtid_purged, which are the event no longer available in binary logs.
// When we consider Vitess incremental backups, what's important for us is "what's the GTIDSet that's true when this backup was taken,
// and which will be true when we restore this backup". The answer to this is the GTIDSet that includes the purged GTIDs.
// It's also nice for incremental backups that are taken on _other_ tablets, so that they don't need to understand what exactly was purged
// on _this_ tablet. They don't care, all they want to know is "what GTIDSet can we get from this".
incrementalBackupToPosition.GTIDSet = incrementalBackupToPosition.GTIDSet.Union(gtidPurged.GTIDSet)
req := &mysqlctlpb.ReadBinlogFilesTimestampsRequest{}
for _, binlogFile := range binaryLogsToBackup {
fe := FileEntry{Base: backupBinlogDir, Name: binlogFile}
fullPath, err := fe.fullPath(params.Cnf)
if err != nil {
return BackupUnusable, err
}
req.BinlogFileNames = append(req.BinlogFileNames, fullPath)
}
resp, err := params.Mysqld.ReadBinlogFilesTimestamps(ctx, req)
if err != nil {
return BackupUnusable, vterrors.Wrapf(err, "reading timestamps from binlog files %v", binaryLogsToBackup)
}
if resp.FirstTimestampBinlog == "" || resp.LastTimestampBinlog == "" {
return BackupUnusable, vterrors.Errorf(vtrpcpb.Code_ABORTED, "empty binlog name in response. Request=%v, Response=%v", req, resp)
}
log.Info(fmt.Sprintf("ReadBinlogFilesTimestampsResponse: %+v", resp))
incrDetails := &IncrementalBackupDetails{
FirstTimestamp: FormatRFC3339(protoutil.TimeFromProto(resp.FirstTimestamp).UTC()),
FirstTimestampBinlog: filepath.Base(resp.FirstTimestampBinlog),
LastTimestamp: FormatRFC3339(protoutil.TimeFromProto(resp.LastTimestamp).UTC()),
LastTimestampBinlog: filepath.Base(resp.LastTimestampBinlog),
}
// It's worthwhile we explain the difference between params.IncrementalFromPos and incrementalBackupFromPosition.
// params.IncrementalFromPos is supplied by the user. They want an incremental backup that covers that position.
// However, we implement incremental backups by copying complete binlog files. That position could potentially
// be somewhere in the middle of some binlog. So we look at the earliest binlog file that covers the user's position.
// The backup we take either starts exactly at the user's position or at some prior position, depending where in the
// binlog file the user's requested position is found.
// incrementalBackupFromGTID is the "previous GTIDs" of the first binlog file we back up.
// It is a fact that incrementalBackupFromGTID is earlier or equal to params.IncrementalFromPos.
// In the backup manifest file, we document incrementalBackupFromGTID, not the user's requested position.
if err := be.backupFiles(ctx, params, bh, incrementalBackupToPosition, gtidPurged, incrementalBackupFromPosition, fromBackupName, binaryLogsToBackup, serverUUID, mysqlVersion, incrDetails); err != nil {
return BackupUnusable, err
}
return BackupUsable, nil
}
// executeFullBackup returns a BackupResult that indicates the usability of the backup,
// and an overall error.
func (be *BuiltinBackupEngine) executeFullBackup(ctx context.Context, params BackupParams, bh backupstorage.BackupHandle) (BackupResult, error) {
if params.IncrementalFromPos != "" {
return be.executeIncrementalBackup(ctx, params, bh)
}
// Save initial state so we can restore.
replicaStartRequired := false
sourceIsPrimary := false
superReadOnly := true
var replicationPosition replication.Position
semiSyncSource, semiSyncReplica := params.Mysqld.SemiSyncEnabled(ctx)
// See if we need to restart replication after backup.
params.Logger.Infof("getting current replication status")
replicaStatus, err := params.Mysqld.ReplicationStatus(ctx)
switch err {
case nil:
replicaStartRequired = replicaStatus.Healthy() && !DisableActiveReparents
case mysql.ErrNotReplica:
// keep going if we're the primary, might be a degenerate case
sourceIsPrimary = true
default:
return BackupUnusable, vterrors.Wrap(err, "can't get replica status")
}
// get the read-only flag
readOnly, err := params.Mysqld.IsReadOnly(ctx)
if err != nil {
return BackupUnusable, vterrors.Wrap(err, "failed to get read_only status")
}
superReadOnly, err = params.Mysqld.IsSuperReadOnly(ctx)
if err != nil {
return BackupUnusable, vterrors.Wrap(err, "can't get super_read_only status")
}
log.Info(fmt.Sprintf("Flag values during full backup, read_only: %v, super_read_only:%t", readOnly, superReadOnly))
// get the replication position
if sourceIsPrimary {
// No need to set read_only because super_read_only will implicitly set read_only to true as well.
if !superReadOnly {
params.Logger.Infof("Enabling super_read_only on primary prior to backup")
if _, err = params.Mysqld.SetSuperReadOnly(ctx, true); err != nil {
return BackupUnusable, vterrors.Wrap(err, "failed to enable super_read_only")
}
defer func() {
// Resetting super_read_only back to its original value
params.Logger.Infof("resetting mysqld super_read_only to %v", superReadOnly)
if _, err := params.Mysqld.SetSuperReadOnly(ctx, false); err != nil {
log.Error("Failed to set super_read_only back to its original value")
}
}()
}
replicationPosition, err = params.Mysqld.PrimaryPosition(ctx)
if err != nil {
return BackupUnusable, vterrors.Wrap(err, "can't get position on primary")
}
} else {
// This is a replica
if err := params.Mysqld.StopReplication(ctx, params.HookExtraEnv); err != nil {
return BackupUnusable, vterrors.Wrapf(err, "can't stop replica")
}
replicaStatus, err := params.Mysqld.ReplicationStatus(ctx)
if err != nil {
return BackupUnusable, vterrors.Wrap(err, "can't get replica status")
}
replicationPosition = replicaStatus.Position
}
params.Logger.Infof("using replication position: %v", replicationPosition)
gtidPurgedPosition, err := params.Mysqld.GetGTIDPurged(ctx)
if err != nil {
return BackupUnusable, vterrors.Wrap(err, "can't get gtid_purged")
}
serverUUID, err := params.Mysqld.GetServerUUID(ctx)
if err != nil {
return BackupUnusable, vterrors.Wrap(err, "can't get server uuid")
}
mysqlVersion, err := params.Mysqld.GetVersionString(ctx)
if err != nil {
return BackupUnusable, vterrors.Wrap(err, "can't get MySQL version")
}
// check if we need to set innodb_fast_shutdown=0 for a backup safe for upgrades
if params.UpgradeSafe {
if _, err := params.Mysqld.FetchSuperQuery(ctx, "SET GLOBAL innodb_fast_shutdown=0"); err != nil {
return BackupUnusable, vterrors.Wrapf(err, "failed to disable fast shutdown")
}
}
// shutdown mysqld
shutdownCtx, cancel := context.WithTimeout(ctx, BuiltinBackupMysqldTimeout)
err = params.Mysqld.Shutdown(shutdownCtx, params.Cnf, true, params.MysqlShutdownTimeout)
defer cancel()
if err != nil {
return BackupUnusable, vterrors.Wrap(err, "can't shutdown mysqld")
}
// Backup everything, capture the error.
backupErr := be.backupFiles(ctx, params, bh, replicationPosition, gtidPurgedPosition, replication.Position{}, "", nil, serverUUID, mysqlVersion, nil)
backupResult := BackupUnusable
if backupErr == nil {
backupResult = BackupUsable
}
// Try to restart mysqld, use background context in case we timed out the original context
err = params.Mysqld.Start(context.Background(), params.Cnf)
if err != nil {
return backupResult, vterrors.Wrap(err, "can't restart mysqld")
}
// Resetting super_read_only back to its original value
params.Logger.Infof("resetting mysqld super_read_only to %v", superReadOnly)
if _, err := params.Mysqld.SetSuperReadOnly(ctx, superReadOnly); err != nil {
return backupResult, err
}
// Restore original mysqld state that we saved above.
if semiSyncSource || semiSyncReplica {
// Only do this if one of them was on, since both being off could mean
// the plugin isn't even loaded, and the server variables don't exist.
params.Logger.Infof("restoring semi-sync settings from before backup: primary=%v, replica=%v",
semiSyncSource, semiSyncReplica)
err := params.Mysqld.SetSemiSyncEnabled(ctx, semiSyncSource, semiSyncReplica)
if err != nil {
return backupResult, err
}
}
if replicaStartRequired {
params.Logger.Infof("restarting mysql replication")
if err := params.Mysqld.StartReplication(ctx, params.HookExtraEnv); err != nil {
return backupResult, vterrors.Wrap(err, "cannot restart replica")
}
// this should be quick, but we might as well just wait
if err := WaitForReplicationStart(ctx, params.Mysqld, replicationStartDeadline); err != nil {
return backupResult, vterrors.Wrap(err, "replica is not restarting")
}
// Wait for a reliable value for ReplicationLagSeconds from ReplicationStatus()
// We know that we stopped at replicationPosition.
// If PrimaryPosition is the same, that means no writes
// have happened to primary, so we are up-to-date.
// Otherwise, we wait for replica's Position to change from
// the saved replicationPosition before proceeding
tmc := tmclient.NewTabletManagerClient()
defer tmc.Close()
remoteCtx, remoteCancel := context.WithTimeout(ctx, topo.RemoteOperationTimeout)
defer remoteCancel()
pos, err := getPrimaryPosition(remoteCtx, tmc, params.TopoServer, params.Keyspace, params.Shard)
// If we are unable to get the primary's position, return error.
if err != nil {
return backupResult, err
}
if !replicationPosition.Equal(pos) {
for {
if err := ctx.Err(); err != nil {
return backupResult, err
}
status, err := params.Mysqld.ReplicationStatus(ctx)
if err != nil {
return backupResult, err
}
newPos := status.Position
if !newPos.Equal(replicationPosition) {
break
}
time.Sleep(1 * time.Second)
}
}
}
return backupResult, backupErr
}
// backupFiles finds the list of files to backup, and creates the backup.
func (be *BuiltinBackupEngine) backupFiles(
ctx context.Context,
params BackupParams,
bh backupstorage.BackupHandle,
backupPosition replication.Position,
purgedPosition replication.Position,
fromPosition replication.Position,
fromBackupName string,
binlogFiles []string,
serverUUID string,
mysqlVersion string,
incrDetails *IncrementalBackupDetails,
) (finalErr error) {
// backupFiles always wait for AddFiles to finish its work before returning, unless there has been a
// non-recoverable error in the process, in both cases we can cancel the context safely.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
// Get the files to backup.
// We don't care about totalSize because we add each file separately.
var fes []FileEntry
var err error
if isIncrementalBackup(params) {
fes, _, err = binlogFilesToBackup(params.Cnf, binlogFiles)
} else {
fes, _, err = findFilesToBackup(params.Cnf)
}
if err != nil {
return vterrors.Wrap(err, "can't find files to backup")
}
params.Logger.Infof("found %v files to backup", len(fes))
// The error here can be ignored safely. Failed FileEntry's are handled in the next 'if' statement.
_ = be.backupFileEntries(ctx, fes, bh, params)
// BackupHandle supports the BackupErrorRecorder interface for tracking errors
// across any goroutines that fan out to take the backup. This means that we
// don't need a local error recorder and can put everything through the bh.
//
// This handles the scenario where bh.AddFile() encounters an error asynchronously,
// which ordinarily would be lost in the context of `be.backupFile`, i.e. if an
// error were encountered
// [here](https://github.com/vitessio/vitess/blob/d26b6c7975b12a87364e471e2e2dfa4e253c2a5b/go/vt/mysqlctl/s3backupstorage/s3.go#L139-L142).
//
// All the errors are grouped per file, if one or more files failed, we back them up
// once more concurrently, if any of the retry fail, we fail-fast by canceling the context
// and return an error. There is no reason to continue processing the other retries, if
// one of them failed.
if files := bh.GetFailedFiles(); len(files) > 0 {
newFEs := make([]FileEntry, len(fes))
for _, file := range files {
fileNb, err := strconv.Atoi(file)
if err != nil {
return vterrors.Wrapf(err, "failed to retry file '%s'", file)
}
oldFes := fes[fileNb]
newFEs[fileNb] = FileEntry{
Base: oldFes.Base,
Name: oldFes.Name,
ParentPath: oldFes.ParentPath,
RetryCount: 1,
}
bh.ResetErrorForFile(file)
}
err = be.backupFileEntries(ctx, newFEs, bh, params)
if err != nil {
return err
}
// Propagate retry results back to the original entries so the
// manifest records correct hashes and metadata.
for i, fe := range newFEs {
if fe.Name != "" {
fes[i] = fe
}
}
}
// Backup the MANIFEST file and apply retry logic.
var manifestErr error
for currentRetry := 0; currentRetry <= maxRetriesPerFile; currentRetry++ {
manifestErr = be.backupManifest(ctx, params, bh, backupPosition, purgedPosition, fromPosition, fromBackupName, serverUUID, mysqlVersion, incrDetails, fes, currentRetry)
if manifestErr == nil || vterrors.Code(manifestErr) == vtrpcpb.Code_FAILED_PRECONDITION {
break
}
bh.ResetErrorForFile(backupManifestFileName)
}
if manifestErr != nil {
return manifestErr
}
return nil
}
// backupFileEntries iterates over a slice of FileEntry, backing them up concurrently up to the defined concurrency limit.
// This function will ignore empty FileEntry, allowing the retry mechanism to send a partially empty slice, to not
// mess up the index of retriable FileEntry.
// This function does not leave any background operation behind itself, all calls to bh.AddFile will be finished or canceled.
func (be *BuiltinBackupEngine) backupFileEntries(ctx context.Context, fes []FileEntry, bh backupstorage.BackupHandle, params BackupParams) error {
ctxCancel, cancel := context.WithCancel(ctx)
defer func() {
// If we reached this defer in all cases we can cancel the context.
// The only ways to get here are: a panic, an error when ending the backup, a successful backup.
// For all three options, it is safe to cancel the context, there should be no pending operations
// that 1) haven't completed, 2) we care about anymore.
cancel()
}()
g := errgroup.Group{}
g.SetLimit(params.Concurrency)
for i := range fes {
if fes[i].Name == "" {
continue
}
g.Go(func() error {
fe := &fes[i]
name := strconv.Itoa(i)
// Check for context cancellation explicitly because, the way semaphore code is written, theoretically we might
// end up not throwing an error even after cancellation. Please see https://cs.opensource.google/go/x/sync/+/refs/tags/v0.1.0:semaphore/semaphore.go;l=66,
// which suggests that if the context is already done, `Acquire()` may still succeed without blocking. This introduces
// unpredictability in my test cases, so in order to avoid that, I am adding this cancellation check.
select {
case <-ctxCancel.Done():
log.Error(fmt.Sprintf("Context canceled or timed out during %q backup", fe.Name))
bh.RecordError(name, vterrors.Errorf(vtrpcpb.Code_CANCELED, "context canceled"))
return nil
default:
}
// Backup the individual file.
var errBackupFile error
if errBackupFile = be.backupFile(ctxCancel, params, bh, fe, name); errBackupFile != nil {
bh.RecordError(name, vterrors.Wrapf(errBackupFile, "failed to backup file '%s'", name))
if fe.RetryCount >= maxRetriesPerFile || vterrors.Code(errBackupFile) == vtrpcpb.Code_FAILED_PRECONDITION {
// this is the last attempt, and we have an error, we can cancel everything and fail fast.
cancel()
}
}
return nil
})
}
_ = g.Wait()
err := bh.EndBackup(ctx)
if err != nil {
return err
}
return bh.Error()
}
type backupPipe struct {
filename string
maxSize int64
r io.Reader
w *bufio.Writer
crc32 hash.Hash32
nn int64
done chan struct{}
failed chan struct{}
closed int32
}
func newBackupWriter(filename string, writerBufferSize int, maxSize int64, w io.Writer) *backupPipe {
return &backupPipe{
crc32: crc32.NewIEEE(),
w: bufio.NewWriterSize(w, writerBufferSize),
filename: filename,
maxSize: maxSize,
done: make(chan struct{}),
failed: make(chan struct{}),
}
}
func newBackupReader(filename string, maxSize int64, r io.Reader) *backupPipe {
return &backupPipe{
crc32: crc32.NewIEEE(),
r: r,
filename: filename,
done: make(chan struct{}),
failed: make(chan struct{}),
maxSize: maxSize,
}
}
func retryToString(retry int) string {
// We convert the retry number to an attempt number, increasing retry by one, so it looks more human friendly
return fmt.Sprintf("(attempt %d/%d)", retry+1, maxRetriesPerFile+1)
}
func (bp *backupPipe) Read(p []byte) (int, error) {
nn, err := bp.r.Read(p)
_, _ = bp.crc32.Write(p[:nn])
atomic.AddInt64(&bp.nn, int64(nn))
return nn, err
}
func (bp *backupPipe) Write(p []byte) (int, error) {
nn, err := bp.w.Write(p)
_, _ = bp.crc32.Write(p[:nn])
atomic.AddInt64(&bp.nn, int64(nn))
return nn, err
}
func (bp *backupPipe) Close(isDone bool) (err error) {
if atomic.CompareAndSwapInt32(&bp.closed, 0, 1) {
// If we fail to Flush the writer we must report this backup as a failure.
defer func() {
if isDone && err == nil {
close(bp.done)
return
}
close(bp.failed)
}()
if bp.w != nil {
if err := bp.w.Flush(); err != nil {
return err
}
}
}
return nil
}
func (bp *backupPipe) HashString() string {
return hex.EncodeToString(bp.crc32.Sum(nil))
}
func (bp *backupPipe) ReportProgress(ctx context.Context, period time.Duration, logger logutil.Logger, restore bool, retryStr string) {
messageStr := "restoring"
if !restore {
messageStr = "backing up"
}
tick := time.NewTicker(period)
defer tick.Stop()
for {
select {
case <-ctx.Done():
logger.Infof("Canceled %s of %q file %s", messageStr, bp.filename, retryStr)
return
case <-bp.done:
logger.Infof("Completed %s %q %s", messageStr, bp.filename, retryStr)
return
case <-bp.failed:
logger.Infof("Failed %s %q %s", messageStr, bp.filename, retryStr)
return
case <-tick.C:
written := float64(atomic.LoadInt64(&bp.nn))
if bp.maxSize == 0 {
logger.Infof("%s %q %s: %.02fkb", messageStr, bp.filename, retryStr, written/1024.0)
} else {
maxSize := float64(bp.maxSize)
logger.Infof("%s %q %s: %.02f%% (%.02f/%.02fkb)", messageStr, bp.filename, retryStr, 100.0*written/maxSize, written/1024.0, maxSize/1024.0)
}
}
}
}
// backupFile backs up an individual file.
func (be *BuiltinBackupEngine) backupFile(ctx context.Context, params BackupParams, bh backupstorage.BackupHandle, fe *FileEntry, name string) (finalErr error) {
// We need another context that does not live outside of this function.
// Reporting progress, compressing and writing are operations that will be
// over by the time we exit this function, they can use this cancelable context.
// However, AddFile is something that may continue in the background even after
// this function exits. In this case, we give it the parent context so the caller
// has more control over when to cancel AddFile.
cancelableCtx, cancel := context.WithCancel(ctx)
defer cancel()
// Open the source file for reading.
openSourceAt := time.Now()
source, err := fe.open(params.Cnf, true)
if err != nil {
return err
}
params.Stats.Scope(stats.Operation("Source:Open")).TimedIncrement(time.Since(openSourceAt))
defer func() {
closeSourceAt := time.Now()
if err := closeWithRetry(ctx, params.Logger, source, fe.Name); err != nil {
params.Logger.Infof("Failed to close %s source file during backup: %v", fe.Name, err)
return
}
params.Stats.Scope(stats.Operation("Source:Close")).TimedIncrement(time.Since(closeSourceAt))
}()
readStats := params.Stats.Scope(stats.Operation("Source:Read"))
timedSource := ioutil.NewMeteredReadCloser(source, readStats.TimedIncrementBytes)
fi, err := source.Stat()
if err != nil {
return err
}
retryStr := retryToString(fe.RetryCount)
br := newBackupReader(fe.Name, fi.Size(), timedSource)
go br.ReportProgress(cancelableCtx, builtinBackupProgress, params.Logger, false /*restore*/, retryStr)
// Open the destination file for writing, and a buffer.
params.Logger.Infof("Backing up file: %v %s", fe.Name, retryStr)
openDestAt := time.Now()
dest, err := bh.AddFile(ctx, name, fi.Size())
if err != nil {
return vterrors.Wrapf(err, "cannot add file: %v,%v", name, fe.Name)
}
params.Stats.Scope(stats.Operation("Destination:Open")).TimedIncrement(time.Since(openDestAt))
defer func(name, fileName string) {
closeDestAt := time.Now()
if rerr := closeWithRetry(ctx, params.Logger, dest, fe.Name); rerr != nil {
rerr = vterrors.Wrapf(rerr, "failed to close destination file (%v) %v", name, fe.Name)
params.Logger.Error(rerr)
finalErr = errors.Join(finalErr, rerr)
return
}
params.Stats.Scope(stats.Operation("Destination:Close")).TimedIncrement(time.Since(closeDestAt))
}(name, fe.Name)
destStats := params.Stats.Scope(stats.Operation("Destination:Write"))
timedDest := ioutil.NewMeteredWriteCloser(dest, destStats.TimedIncrementBytes)
bw := newBackupWriter(fe.Name, builtinBackupStorageWriteBufferSize, fi.Size(), timedDest)
// We create the following inner function because:
// - we must `defer` the compressor's Close() function
// - but it must take place before we close the pipe reader&writer
createAndCopy := func() (createAndCopyErr error) {
var reader io.Reader = br
var writer io.Writer = bw
defer func() {
// Close the backupPipe to finish writing on destination.
if err := bw.Close(createAndCopyErr == nil); err != nil {
createAndCopyErr = errors.Join(createAndCopyErr, vterrors.Wrapf(err, "cannot flush destination: %v", name))
}
if err := br.Close(createAndCopyErr == nil); err != nil {
createAndCopyErr = errors.Join(createAndCopyErr, vterrors.Wrap(err, "failed to close the source reader"))
}
}()
// Create the gzip compression pipe, if necessary.
if backupStorageCompress {
var compressor io.WriteCloser
if ExternalCompressorCmd != "" {
compressor, err = newExternalCompressor(cancelableCtx, ExternalCompressorCmd, writer, params.Logger)
} else {
compressor, err = newBuiltinCompressor(CompressionEngineName, writer, params.Logger)
}
if err != nil {
return vterrors.Wrap(err, "can't create compressor")
}
compressStats := params.Stats.Scope(stats.Operation("Compressor:Write"))
writer = ioutil.NewMeteredWriter(compressor, compressStats.TimedIncrementBytes)
closer := ioutil.NewTimeoutCloser(cancelableCtx, compressor, closeTimeout)
defer func() {
// Close gzip to flush it, after that all data is sent to writer.
params.Logger.Infof("Closing compressor for file: %s %s", fe.Name, retryStr)
closeCompressorAt := time.Now()
if cerr := closeWithRetry(ctx, params.Logger, closer, "compressor"); cerr != nil {
cerr = vterrors.Wrapf(cerr, "failed to close compressor %v", fe.Name)
params.Logger.Error(cerr)
createAndCopyErr = errors.Join(createAndCopyErr, cerr)
return
}
params.Stats.Scope(stats.Operation("Compressor:Close")).TimedIncrement(time.Since(closeCompressorAt))
}()
}
if builtinBackupFileReadBufferSize > 0 {
reader = bufio.NewReaderSize(br, int(builtinBackupFileReadBufferSize))
}
// Copy from the source file to writer (optional gzip,
// optional pipe, tee, output file and hasher).
_, err = io.Copy(writer, reader)
if err != nil {
return vterrors.Wrap(err, "cannot copy data")
}
return nil
}
if err := createAndCopy(); err != nil {
return errors.Join(finalErr, err)
}
// Save the hash.
fe.Hash = bw.HashString()
return nil
}
func (be *BuiltinBackupEngine) backupManifest(
ctx context.Context,
params BackupParams,
bh backupstorage.BackupHandle,
backupPosition replication.Position,
purgedPosition replication.Position,
fromPosition replication.Position,
fromBackupName string,
serverUUID string,
mysqlVersion string,
incrDetails *IncrementalBackupDetails,
fes []FileEntry,
currentAttempt int,
) (finalErr error) {
retryStr := retryToString(currentAttempt)
params.Logger.Infof("Backing up file %s %s", backupManifestFileName, retryStr)
defer func() {
state := "Completed"