forked from go-mysql-org/go-mysql
-
Notifications
You must be signed in to change notification settings - Fork 1
/
backup.go
96 lines (75 loc) · 1.91 KB
/
backup.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
package replication
import (
"context"
"io"
"os"
"path"
"time"
"github.com/pingcap/errors"
. "github.com/hanchuanchuan/go-mysql/mysql"
)
// StartBackup: Like mysqlbinlog remote raw backup
// Backup remote binlog from position (filename, offset) and write in backupDir
func (b *BinlogSyncer) StartBackup(backupDir string, p Position, timeout time.Duration) error {
if timeout == 0 {
// a very long timeout here
timeout = 30 * 3600 * 24 * time.Second
}
// Force use raw mode
b.parser.SetRawMode(true)
os.MkdirAll(backupDir, 0755)
s, err := b.StartSync(p)
if err != nil {
return errors.Trace(err)
}
var filename string
var offset uint32
var f *os.File
defer func() {
if f != nil {
f.Close()
}
}()
for {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
e, err := s.GetEvent(ctx)
cancel()
if err == context.DeadlineExceeded {
return nil
}
if err != nil {
return errors.Trace(err)
}
offset = e.Header.LogPos
if e.Header.EventType == ROTATE_EVENT {
rotateEvent := e.Event.(*RotateEvent)
filename = string(rotateEvent.NextLogName)
if e.Header.Timestamp == 0 || offset == 0 {
// fake rotate event
continue
}
} else if e.Header.EventType == FORMAT_DESCRIPTION_EVENT {
// FormateDescriptionEvent is the first event in binlog, we will close old one and create a new
if f != nil {
f.Close()
}
if len(filename) == 0 {
return errors.Errorf("empty binlog filename for FormateDescriptionEvent")
}
f, err = os.OpenFile(path.Join(backupDir, filename), os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return errors.Trace(err)
}
// write binlog header fe'bin'
if _, err = f.Write(BinLogFileHeader); err != nil {
return errors.Trace(err)
}
}
if n, err := f.Write(e.RawData); err != nil {
return errors.Trace(err)
} else if n != len(e.RawData) {
return errors.Trace(io.ErrShortWrite)
}
}
return nil
}