/
client.go
410 lines (353 loc) · 10.9 KB
/
client.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
package client
import (
"context"
"fmt"
"io"
"time"
"github.com/apecloud/dataprotection-wal-g/internal/databases/mongo/models"
"github.com/apecloud/dataprotection-wal-g/utility"
"github.com/mongodb/mongo-tools-common/db"
"github.com/wal-g/tracelog"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
_ = []MongoDriver{&MongoClient{}}
_ = []OplogCursor{&MongoOplogCursor{}}
_ = []OplogCursor{&MongoOplogCursor{}, &BsonCursor{}}
)
const (
driverAppName = "wal-g-mongo"
oplogDatabaseName = "local"
oplogCollectionName = "oplog.rs"
)
type OplogAppMode string
const (
OplogAppModeInitSync OplogAppMode = "InitialSync"
OplogAppModeRecovering OplogAppMode = "Recovering"
OplogAppModeSecondary OplogAppMode = "Secondary"
)
var (
OplogAppModes = map[OplogAppMode]struct{}{
OplogAppModeInitSync: {},
OplogAppModeRecovering: {},
OplogAppModeSecondary: {},
}
)
// CmdResponse is used to unmarshal mongodb cmd responses
type CmdResponse struct {
Ok int `bson:"ok"`
ErrMsg string `bson:"errmsg, omitempty"`
}
// Optime ...
type OpTime struct {
TS primitive.Timestamp `bson:"ts" json:"ts"`
Term int64 `bson:"t" json:"t"`
}
// IsMasterLastWrite ...
type IsMasterLastWrite struct {
OpTime OpTime `bson:"opTime"`
MajorityOpTime OpTime `bson:"majorityOpTime"`
}
// IsMaster is used to unmarshal results of IsMaster command
type IsMaster struct {
IsMaster bool `bson:"ismaster"`
LastWrite IsMasterLastWrite `bson:"lastWrite"`
}
// MongoDriver defines methods to work with mongodb.
type MongoDriver interface {
CreateIndexes(ctx context.Context, dbName, collName string, indexes []IndexDocument) error
EnsureIsMaster(ctx context.Context) error
IsMaster(ctx context.Context) (models.IsMaster, error)
LastWriteTS(ctx context.Context) (lastTS, lastMajTS models.Timestamp, err error)
TailOplogFrom(ctx context.Context, from models.Timestamp) (OplogCursor, error)
ApplyOp(ctx context.Context, op db.Oplog) error
Close(ctx context.Context) error
}
// OplogCursor defines methods to work with mongodb cursor.
type OplogCursor interface {
Close(ctx context.Context) error
Data() []byte
Err() error
Next(context.Context) bool
Push([]byte) error
}
// MongoOplogCursor implements OplogCursor.
type MongoOplogCursor struct {
*mongo.Cursor
pushed []byte
}
// NewMongoOplogCursor builds MongoOplogCursor.
func NewMongoOplogCursor(c *mongo.Cursor) *MongoOplogCursor {
return &MongoOplogCursor{c, nil}
}
// Data returns current cursor document
func (m *MongoOplogCursor) Data() []byte {
return m.Current
}
// Push returns document back to cursor
func (m *MongoOplogCursor) Push(data []byte) error {
if m.pushed != nil {
return fmt.Errorf("cursor already has one unread pushed document")
}
m.pushed = data
return nil
}
// Next fills Current by next document, returns true if there were no errors and the cursor has not been exhausted.
func (m *MongoOplogCursor) Next(ctx context.Context) bool {
if m.pushed != nil {
m.Current = m.pushed
m.pushed = nil
return true
}
return m.Cursor.Next(ctx)
}
// ApplyOplog is used to replay oplog entry.
type ApplyOplog struct {
Operation string `bson:"op"`
Namespace string `bson:"ns"`
Object bson.D `bson:"o"`
Query bson.D `bson:"o2,omitempty"`
UI *primitive.Binary `bson:"ui,omitempty"`
LSID bson.Raw `bson:"lsid,omitempty"`
TxnNumber *int64 `bson:"txnNumber,omitempty"`
PrevOpTime bson.Raw `bson:"prevOpTime,omitempty"`
}
// MongoClient implements MongoDriver
type MongoClient struct {
c *mongo.Client
applyOpsCmd bson.D
}
// Options defines mongo client options
type Options struct {
OplogApplicationMode *OplogAppMode
OplogAlwaysUpsert *bool
}
type Option func(*Options)
// OplogAlwaysUpsert sets applyOps argument oplogApplicationMode
func OplogApplicationMode(mode OplogAppMode) Option {
return func(args *Options) {
args.OplogApplicationMode = &mode
}
}
// OplogAlwaysUpsert sets applyOps argument alwaysUpsert
func OplogAlwaysUpsert(alwaysUpsert bool) Option {
return func(args *Options) {
args.OplogAlwaysUpsert = &alwaysUpsert
}
}
// NewMongoClient builds MongoClient
func NewMongoClient(ctx context.Context, uri string, setters ...Option) (*MongoClient, error) {
// Default Options
args := &Options{}
for _, setter := range setters {
setter(args)
}
applyOpsCmd := bson.D{
{Key: "applyOps"},
}
if args.OplogApplicationMode != nil {
oplogApplicationMode := *args.OplogApplicationMode
if _, ok := OplogAppModes[oplogApplicationMode]; !ok {
return nil, fmt.Errorf("unsupported oplogApplicationMode: %s", oplogApplicationMode)
}
applyOpsCmd = append(applyOpsCmd, bson.E{Key: "oplogApplicationMode", Value: oplogApplicationMode})
}
if args.OplogAlwaysUpsert != nil {
applyOpsCmd = append(applyOpsCmd, bson.E{Key: "alwaysUpsert", Value: *args.OplogAlwaysUpsert})
}
client, err := mongo.Connect(ctx,
options.Client().ApplyURI(uri).
SetAppName(driverAppName).
SetDirect(true).
SetRetryReads(false))
if err != nil {
return nil, err
}
return &MongoClient{
c: client,
applyOpsCmd: applyOpsCmd,
}, client.Ping(ctx, nil)
}
// IndexDocument holds information about a collection's index.
type IndexDocument struct {
Options bson.M `bson:",inline"`
Key bson.D `bson:"key"`
PartialFilterExpression bson.D `bson:"partialFilterExpression,omitempty"`
}
func (mc *MongoClient) CreateIndexes(ctx context.Context, dbName, collName string, indexes []IndexDocument) error {
rawCommand := bson.D{
{Key: "createIndexes", Value: collName},
{Key: "indexes", Value: indexes},
}
if err := mc.c.Database(dbName).RunCommand(ctx, rawCommand).Err(); err != nil {
return fmt.Errorf("createIndexes command %q failed: %w", rawCommand, err)
}
return nil
}
func (mc *MongoClient) EnsureIsMaster(ctx context.Context) error {
im, err := mc.IsMaster(ctx)
if err != nil {
return err
}
if !im.IsMaster {
return fmt.Errorf("current node is not a primary")
}
return nil
}
func (mc *MongoClient) IsMaster(ctx context.Context) (models.IsMaster, error) {
im := IsMaster{}
err := mc.c.Database("test").RunCommand(ctx, bson.D{{Key: "isMaster", Value: 1}}).Decode(&im)
if err != nil {
return models.IsMaster{}, fmt.Errorf("isMaster command failed: %w", err)
}
return models.IsMaster{
IsMaster: im.IsMaster,
LastWrite: models.IsMasterLastWrite{
OpTime: models.OpTime{
TS: models.TimestampFromBson(im.LastWrite.OpTime.TS),
},
MajorityOpTime: models.OpTime{
TS: models.TimestampFromBson(im.LastWrite.MajorityOpTime.TS),
},
},
}, nil
}
// LastWriteTS fetches timestamps with last write
// TODO: support non-replset setups
func (mc *MongoClient) LastWriteTS(ctx context.Context) (lastTS, lastMajTS models.Timestamp, err error) {
im, err := mc.IsMaster(ctx)
if err != nil {
return models.Timestamp{}, models.Timestamp{}, fmt.Errorf("isMaster command failed: %+v", err)
}
return im.LastWrite.OpTime.TS, im.LastWrite.MajorityOpTime.TS, nil
}
// Close disconnects from mongodb
func (mc *MongoClient) Close(ctx context.Context) error {
return mc.c.Disconnect(ctx)
}
// TailOplogFrom gives OplogCursor to tail oplog from
func (mc *MongoClient) TailOplogFrom(ctx context.Context, from models.Timestamp) (OplogCursor, error) {
coll, err := mc.getOplogCollection(ctx)
if err != nil {
return nil, err
}
bsonTS := models.BsonTimestampFromOplogTS(from)
filter := bson.M{"ts": bson.M{"$gte": bsonTS}}
cur, err := coll.Find(ctx, filter, options.Find().SetCursorType(options.TailableAwait))
if err == nil && cur.ID() == 0 {
err = fmt.Errorf("dead cursor from oplog find")
}
if err != nil {
return nil, fmt.Errorf("oplog lookup failed: %w", err)
}
return NewMongoOplogCursor(cur), nil
}
func (mc *MongoClient) getOplogCollection(ctx context.Context) (*mongo.Collection, error) {
odb := mc.c.Database(oplogDatabaseName)
colls, err := odb.ListCollectionNames(ctx, bson.M{"name": oplogCollectionName})
if err != nil {
return nil, fmt.Errorf("can not list collections in 'local' database: %w", err)
}
if len(colls) != 1 {
return nil, fmt.Errorf("collection '%s' was not found in database '%s'",
oplogCollectionName, oplogDatabaseName)
}
return odb.Collection(oplogCollectionName), nil
}
func (mc *MongoClient) getApplyOpsCmd() bson.D {
return mc.applyOpsCmd
}
// ApplyOp calls applyOps and check response
func (mc *MongoClient) ApplyOp(ctx context.Context, dbop db.Oplog) error {
// mongod complains if 'ts' or 'history' are passed to applyOps
op := ApplyOplog{
Operation: dbop.Operation,
Namespace: dbop.Namespace,
Object: dbop.Object,
Query: dbop.Query,
UI: dbop.UI,
LSID: dbop.LSID,
TxnNumber: dbop.TxnNumber,
PrevOpTime: dbop.PrevOpTime,
}
// TODO: fix ugly interface after switch to passing pointers
cmd := mc.getApplyOpsCmd()
cmd[0] = bson.E{Key: "applyOps", Value: []interface{}{op}}
apply := mc.c.Database("admin").RunCommand(ctx, cmd)
if err := apply.Err(); err != nil {
return err
}
resp := CmdResponse{}
if err := apply.Decode(&resp); err != nil {
return fmt.Errorf("can not unmarshall command execution response: %+v\ncommand was:%+v", err, cmd)
}
if resp.Ok != 1 {
return fmt.Errorf("command execution failed with: %s\ncommand was: %+v", resp.ErrMsg, cmd)
}
return nil
}
// BsonCursor implements OplogCursor with source io.reader
type BsonCursor struct {
r io.Reader
raw []byte
pushed []byte
err error
}
// NewMongoOplogCursor builds MongoOplogCursor.
func NewBsonCursor(r io.Reader) *BsonCursor {
return &BsonCursor{r: r}
}
// Close closes this cursor.
func (b *BsonCursor) Close(ctx context.Context) error {
b.raw = nil
return nil
}
// Data returns current cursor document.
func (b *BsonCursor) Data() []byte {
return b.raw
}
// Err returns the last error.
func (b *BsonCursor) Err() error {
return b.err
}
// Next gets the next document for this cursor, returns true if there were no errors.
func (b *BsonCursor) Next(ctx context.Context) bool {
if b.err != nil {
return false
}
if b.pushed != nil {
b.raw = b.pushed
b.pushed = nil
return true
}
b.raw, b.err = bson.NewFromIOReader(b.r)
return b.err == nil
}
// Push returns document back to cursor
func (b *BsonCursor) Push(data []byte) error {
if b.pushed != nil {
return fmt.Errorf("cursor already has one unread pushed document")
}
b.pushed = data
return nil
}
// WaitForBecomePrimary waits until mongo client connection node becomes primary
func WaitForBecomePrimary(ctx context.Context, mc *MongoClient, checkTimeout time.Duration) error {
reconnect := time.NewTimer(checkTimeout)
for {
select {
case <-reconnect.C:
err := mc.EnsureIsMaster(ctx)
if err == nil {
return nil
}
tracelog.InfoLogger.Printf("Waiting: %v", err)
utility.ResetTimer(reconnect, checkTimeout)
case <-ctx.Done():
return ctx.Err()
}
}
}