-
Notifications
You must be signed in to change notification settings - Fork 9
/
oplog_streamer.go
323 lines (310 loc) · 8.34 KB
/
oplog_streamer.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
// Copyright Kuei-chun Chen, 2022-present. All rights reserved.
package hummingbird
import (
"bytes"
"context"
"fmt"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/simagix/gox"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
)
const (
// BSONSizeLimit set to 10,000
BSONSizeLimit = 16 * mb
// CacheDataSizeLimit set to 10,000
CacheDataSizeLimit = 4 * BSONSizeLimit
// GZippedBSONFileExt is .bson.gz
GZippedBSONFileExt = ".bson.gz"
// OplogBatchSize set to 10,000
OplogBatchSize = 10000
)
// OplogStreamer tails oplogs
type OplogStreamer struct {
SetName string
Spool string
URI string
cached string
isCache bool
mutex sync.Mutex
ts *primitive.Timestamp
}
// Oplog stores an oplog
type Oplog struct {
Hash *int64 `bson:"h"`
Namespace string `bson:"ns"`
Object bson.D `bson:"o"`
Operation string `bson:"op"`
Query bson.D `bson:"o2,omitempty"`
Term *int64 `bson:"t"`
Timestamp primitive.Timestamp `bson:"ts"`
Version int `bson:"v"`
}
// OplogStreamers copies oplogs from source to target
func OplogStreamers() error {
logger := gox.GetLogger("OplogStreamer")
inst := GetMigratorInstance()
ws := inst.Workspace()
status := "stream oplogs"
logger.Remark(status)
err := ws.Log(status)
if err != nil {
return fmt.Errorf("update status failed: %v", err)
}
for setName, replica := range inst.Replicas() {
logger.Infof("stream %v (%v)", setName, RedactedURI(replica))
streamer := OplogStreamer{SetName: setName, Spool: inst.Workspace().spool,
URI: replica, isCache: true}
streamer.ts = ws.GetOplogTimestamp(setName)
go func() {
err := streamer.CacheOplogs()
if err != nil {
log.Fatal(err)
}
}()
inst.AddOplogStreamer(&streamer)
}
return nil
}
// IsCache returns isCache
func (p *OplogStreamer) IsCache() bool {
p.mutex.Lock()
defer p.mutex.Unlock()
return p.isCache
}
// LiveStream begin applying oplogs to target
func (p *OplogStreamer) LiveStream() {
go func() {
for {
var err error
if p.cached, err = p.ApplyCachedOplogs(); err != nil {
log.Fatalf("ApplyCachedOplogs failed: %v", err)
}
if p.cached == "" {
break
}
}
p.mutex.Lock()
p.isCache = false
p.mutex.Unlock()
}()
}
// CacheOplogs store oplogs in files
func (p *OplogStreamer) CacheOplogs() error {
inst := GetMigratorInstance()
ws := inst.Workspace()
logger := gox.GetLogger()
status := fmt.Sprintf("%v cache oplog", p.SetName)
logger.Remark(status)
ws.Log(status)
os.Mkdir(p.Spool, 0755)
if p.ts == nil {
p.ts = &primitive.Timestamp{T: uint32(time.Now().Unix())}
ws.SaveOplogTimestamp(p.SetName, *p.ts)
}
client, err := GetMongoClient(p.URI)
if err != nil {
return fmt.Errorf("GetMongoClient failed: %v", err)
}
cursor, err := GetTailableCursor(client, p.ts)
if err != nil {
return fmt.Errorf("error finding oplog from %v since %v: %v", p.SetName,
time.Unix(int64(p.ts.T), 0).Format(time.RFC3339), err)
}
ctx := context.Background()
var raws bson.Raw
for p.IsCache() {
var oplog Oplog
if !cursor.TryNext(ctx) {
time.Sleep(1 * time.Millisecond)
continue
}
if err = cursor.Decode(&oplog); err != nil {
continue
}
if oplog.Namespace == "" || SkipOplog(oplog) {
continue
}
if len(raws)+len(cursor.Current) > CacheDataSizeLimit {
ofile := fmt.Sprintf(`%v/%v.%v.bson.gz`, p.Spool, p.SetName, GetDateTime())
if err = gox.OutputGzipped(raws, ofile); err != nil {
return fmt.Errorf("OutputGzipped %v failed: %v", ofile, err)
}
var last Oplog
bson.Unmarshal(cursor.Current, &last)
if err = ws.SaveOplogTimestamp(p.SetName, last.Timestamp); err != nil {
return fmt.Errorf("RecordOplogTimestamp failed: %v", err)
}
raws = nil
}
raws = append(raws, cursor.Current...)
}
if len(raws) > 0 {
logger.Infof("%v apply oplogs from memory", p.SetName)
reader := bytes.NewReader(raws)
breader := &BSONReader{Stream: io.NopCloser(reader)}
var oplogs []Oplog
var data []byte
var op *Oplog
processed := 0
for {
if data = breader.Next(); data == nil {
break
}
processed++
var oplog Oplog
err = bson.Unmarshal(data, &oplog)
op = &oplog
oplogs = append(oplogs, oplog)
if len(oplogs) >= MaxBatchSize {
if _, err := BulkWriteOplogs(oplogs); err != nil {
logger.Errorf("BulkWriteOplogs failed: %v", err)
}
oplogs = nil
}
}
if len(oplogs) > 0 {
if _, err := BulkWriteOplogs(oplogs); err != nil {
logger.Errorf("BulkWriteOplogs failed: %v", err)
}
}
lag := time.Since(time.Unix(int64(op.Timestamp.T), 0)).Truncate(time.Second)
logger.Infof("%v lag %v, %v processed", p.SetName, lag, processed)
p.ts = &op.Timestamp
if err = ws.SaveOplogTimestamp(p.SetName, op.Timestamp); err != nil {
return fmt.Errorf("RecordOplogTimestamp failed: %v", err)
}
}
if err = p.LiveStreamOplogs(p.ts); err != nil {
return fmt.Errorf("oplogs live streaming failed: %v", err)
}
return nil
}
// ApplyCachedOplogs applies cached oplogs to target
func (p *OplogStreamer) ApplyCachedOplogs() (string, error) {
inst := GetMigratorInstance()
logger := gox.GetLogger()
ws := inst.Workspace()
status := fmt.Sprintf("%v apply cached oplogs", p.SetName)
logger.Remark(status)
ws.Log(status)
filenames := []string{}
filepath.WalkDir(inst.Workspace().spool, func(s string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if strings.HasPrefix(d.Name(), p.SetName) && strings.HasSuffix(d.Name(), GZippedBSONFileExt) {
if s > p.cached {
filenames = append(filenames, s)
}
}
return nil
})
if len(filenames) == 0 {
return "", nil
}
logger.Infof("%v has %v file(s)", p.SetName, len(filenames))
sort.Slice(filenames, func(i int, j int) bool {
return filenames[i] < filenames[j]
})
for _, filename := range filenames {
logger.Infof("%v apply oplogs from %v", p.SetName, filename)
breader, err := NewBSONReader(filename)
if err != nil {
return filename, fmt.Errorf("read %v failed", err)
}
var oplogs []Oplog
var op *Oplog
processed := 0
for {
var data []byte
if data = breader.Next(); data == nil {
break
}
processed++
var oplog Oplog
err = bson.Unmarshal(data, &oplog)
op = &oplog
oplogs = append(oplogs, oplog)
if len(oplogs) >= MaxBatchSize {
if _, err := BulkWriteOplogs(oplogs); err != nil {
logger.Errorf("BulkWriteOplogs failed: %v", err)
}
oplogs = nil
}
}
if len(oplogs) > 0 {
if _, err := BulkWriteOplogs(oplogs); err != nil {
logger.Errorf("BulkWriteOplogs failed: %v", err)
}
}
lag := time.Since(time.Unix(int64(op.Timestamp.T), 0)).Truncate(time.Second)
logger.Infof("%v lag %v, %v processed", p.SetName, lag, processed)
p.ts = &oplogs[len(oplogs)-1].Timestamp
time.Sleep(50 * time.Millisecond) // yield
}
return filenames[len(filenames)-1], nil
}
// LiveStreamOplogs stream and apply oplogs
func (p *OplogStreamer) LiveStreamOplogs(ts *primitive.Timestamp) error {
ctx := context.Background()
inst := GetMigratorInstance()
ws := inst.Workspace()
logger := gox.GetLogger()
status := fmt.Sprintf("%v live stream oplogs", p.SetName)
logger.Remark(status)
ws.Log(status)
client, err := GetMongoClient(p.URI)
if err != nil {
return fmt.Errorf("GetMongoClient failed: %v", err)
}
cursor, err := GetTailableCursor(client, ts)
var oplogs []Oplog
last := time.Now()
for {
var oplog Oplog
if !cursor.TryNext(ctx) {
if len(oplogs) > 0 {
if _, err := BulkWriteOplogs(oplogs); err != nil {
logger.Errorf("BulkWriteOplogs failed: %v", err)
}
oplogs = nil
}
if time.Since(last) > 10*time.Second {
last = time.Now()
logger.Infof("%v lag 0s", p.SetName)
}
time.Sleep(1 * time.Millisecond)
continue
}
if err = cursor.Decode(&oplog); err != nil {
continue
}
if oplog.Namespace == "" || SkipOplog(oplog) {
continue
}
oplogs = append(oplogs, oplog)
if len(oplogs) >= MaxBatchSize || time.Since(last) > 10*time.Second {
last = time.Now()
if len(oplogs) == 0 {
logger.Infof("%v lag 0s", p.SetName)
continue
}
if _, err := BulkWriteOplogs(oplogs); err != nil {
logger.Errorf("BulkWriteOplogs failed: %v", err)
}
lag := time.Since(time.Unix(int64(oplogs[len(oplogs)-1].Timestamp.T), 0)).Truncate(time.Second)
logger.Infof("%v: lag %v", p.SetName, lag)
oplogs = nil
}
}
return nil
}