/
oplog.go
392 lines (339 loc) · 10.1 KB
/
oplog.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
package oplog
import (
"encoding/json"
"fmt"
LOG "github.com/vinllen/log4go"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"reflect"
"strings"
)
const (
PrimaryKey = "_id"
)
type GenericOplog struct {
Raw []byte
Parsed *PartialLog
}
type ParsedLog struct {
Timestamp primitive.Timestamp `bson:"ts" json:"ts"`
Term *int64 `bson:"t" json:"t"`
Hash *int64 `bson:"h" json:"h"`
Version int `bson:"v" json:"v"`
Operation string `bson:"op" json:"op"`
Gid string `bson:"g,omitempty" json:"g,omitempty"`
Namespace string `bson:"ns" json:"ns"`
Object bson.D `bson:"o" json:"o"`
Query bson.D `bson:"o2" json:"o2"` // update condition
UniqueIndexes bson.M `bson:"uk,omitempty" json:"uk,omitempty"` //
LSID bson.Raw `bson:"lsid,omitempty" json:"lsid,omitempty"` // mark the session id, used in transaction
FromMigrate bool `bson:"fromMigrate,omitempty" json:"fromMigrate,omitempty"` // move chunk
TxnNumber *int64 `bson:"txnNumber,omitempty" json:"txnNumber,omitempty"` // transaction number in session
DocumentKey bson.D `bson:"documentKey,omitempty" json:"documentKey,omitempty"` // exists when source collection is sharded, only including shard key and _id
PrevOpTime bson.Raw `bson:"prevOpTime,omitempty"`
UI *primitive.Binary `bson:"ui,omitempty" json:"ui,omitempty"` // do not enable currently
}
type PartialLog struct {
ParsedLog
/*
* Every field subsequent declared is NEVER persistent or
* transfer on network connection. They only be parsed from
* respective logic
*/
UniqueIndexesUpdates bson.M // generate by CollisionMatrix
RawSize int // generate by Decorator
SourceId int // generate by Validator
}
func LogEntryEncode(logs []*GenericOplog) [][]byte {
encodedLogs := make([][]byte, 0, len(logs))
// log entry encode
for _, log := range logs {
if log.Raw == nil {
if out, err := bson.Marshal(log.Parsed); err != nil {
LOG.Crashf("LogEntryEncode marshal Oplog[%v] failed[%v]", log.Parsed, err)
} else {
encodedLogs = append(encodedLogs, out)
}
} else {
encodedLogs = append(encodedLogs, log.Raw)
}
}
return encodedLogs
}
func LogParsed(logs []*GenericOplog) []*PartialLog {
parsedLogs := make([]*PartialLog, len(logs), len(logs))
for i, log := range logs {
parsedLogs[i] = log.Parsed
}
return parsedLogs
}
func NewPartialLog(data bson.M) *PartialLog {
parsedLog := new(ParsedLog)
logType := reflect.TypeOf(*parsedLog)
for i := 0; i < logType.NumField(); i++ {
tagNameWithOption := logType.Field(i).Tag.Get("bson")
tagName := strings.Split(tagNameWithOption, ",")[0]
if v, ok := data[tagName]; ok {
reflect.ValueOf(parsedLog).Elem().Field(i).Set(reflect.ValueOf(v))
}
}
return &PartialLog{
ParsedLog: *parsedLog,
}
}
func (partialLog *PartialLog) String() string {
if ret, err := json.Marshal(partialLog.ParsedLog); err != nil {
return err.Error()
} else {
return string(ret)
}
}
// dump according to the given keys, "all" == true means ignore keys
func (partialLog *PartialLog) Dump(keys map[string]struct{}, all bool) bson.D {
var out bson.D
logType := reflect.TypeOf(partialLog.ParsedLog)
for i := 0; i < logType.NumField(); i++ {
if tagNameWithOption, ok := logType.Field(i).Tag.Lookup("bson"); ok {
// out[tagName] = reflect.ValueOf(partialLog).Elem().Field(i).Interface()
value := reflect.ValueOf(partialLog.ParsedLog).Field(i).Interface()
tagName := strings.Split(tagNameWithOption, ",")[0]
if !all {
if _, ok := keys[tagName]; !ok {
continue
}
}
out = append(out, primitive.E{tagName, value})
}
}
return out
}
func GetKey(log bson.D, wanted string) interface{} {
ret, _ := GetKeyWithIndex(log, wanted)
return ret
}
func GetKeyWithIndex(log bson.D, wanted string) (interface{}, int) {
if wanted == "" {
wanted = PrimaryKey
}
// "_id" is always the first field
for id, ele := range log {
if ele.Key == wanted {
return ele.Value, id
}
}
return nil, 0
}
func ConvertBsonD2MExcept(input bson.D, except map[string]struct{}) (bson.M, map[string]struct{}) {
m := bson.M{}
keys := make(map[string]struct{}, len(input))
for _, ele := range input {
switch ele.Value.(type) {
case bson.D:
if _, ok := except[ele.Key]; ok {
m[ele.Key] = ele.Value
} else {
son, _ := ConvertBsonD2M(ele.Value.(bson.D))
m[ele.Key] = son
}
default:
m[ele.Key] = ele.Value
}
keys[ele.Key] = struct{}{}
}
return m, keys
}
// convert bson.D to bson.M
func ConvertBsonD2M(input bson.D) (bson.M, map[string]struct{}) {
m := bson.M{}
keys := make(map[string]struct{}, len(input))
for _, ele := range input {
m[ele.Key] = ele.Value
switch ele.Value.(type) {
case bson.D:
son, _ := ConvertBsonD2M(ele.Value.(bson.D))
m[ele.Key] = son
default:
m[ele.Key] = ele.Value
}
keys[ele.Key] = struct{}{}
}
return m, keys
}
func ConvertBsonM2D(input bson.M) bson.D {
output := make(bson.D, 0, len(input))
for key, val := range input {
output = append(output, primitive.E{
Key: key,
Value: val,
})
}
return output
}
// pay attention: the input bson.D will be modified.
func RemoveFiled(input bson.D, key string) bson.D {
flag := -1
for id := range input {
if input[id].Key == key {
flag = id
break
}
}
if flag != -1 {
input = append(input[:flag], input[flag+1:]...)
}
return input
}
func FindFiledPrefix(input bson.D, prefix string) bool {
for id := range input {
if strings.HasPrefix(input[id].Key, prefix) {
return true
}
}
return false
}
func SetFiled(input bson.D, key string, value interface{}) {
for i, ele := range input {
if ele.Key == key {
input[i].Value = value
}
}
}
func GatherApplyOps(input []*PartialLog) (*GenericOplog, error) {
if len(input) == 0 {
return nil, fmt.Errorf("input list is empty")
}
newOplog := &PartialLog{
ParsedLog: ParsedLog{
Timestamp: input[0].Timestamp,
Operation: "c",
Gid: input[0].Gid,
Namespace: "admin.$cmd",
UniqueIndexes: input[0].UniqueIndexes,
LSID: input[0].LSID,
FromMigrate: input[0].FromMigrate,
},
}
applyOpsList := make([]bson.M, 0, len(input))
for _, ele := range input {
applyOpsList = append(applyOpsList, bson.M{
"op": ele.Operation,
"ns": ele.Namespace,
"o": ele.Object,
"o2": ele.Query,
})
}
newOplog.Object = bson.D{
primitive.E{
Key: "applyOps",
Value: applyOpsList,
},
}
if out, err := bson.Marshal(newOplog); err != nil {
return nil, fmt.Errorf("marshal new oplog[%v] failed[%v]", newOplog, err)
} else {
return &GenericOplog{
Raw: out,
Parsed: newOplog,
}, nil
}
}
// Oplog from mongod(5.0) in sharding&replica
// {"ts":{"T":1653449035,"I":3},"v":2,"op":"u","ns":"test.bar",
// "o":[{"Key":"diff","Value":[{"Key":"d","Value":[{"Key":"ok","Value":false}]},
// {"Key":"i","Value":[{"Key":"plus_field","Value":2}]}]}],
// "o2":[{"Key":"_id","Value":"628da11482387c117d4e9e45"}]}
// "o" : { "$v" : 2, "diff" : { "d" : { "count" : false }, "u" : { "name" : "orange" }, "i" : { "c" : 11 } } }
func DiffUpdateOplogToNormal(updateObj bson.D) (interface{}, error) {
diffObj := GetKey(updateObj, "diff")
if diffObj == nil {
return updateObj, fmt.Errorf("don't have diff field updateObj:[%v]", updateObj)
}
bsonDiffObj, ok := diffObj.(bson.D)
if !ok {
return updateObj, fmt.Errorf("diff field is not bson.D updateObj:[%v]", updateObj)
}
result, err := BuildUpdateDelteOplog("", bsonDiffObj)
if err != nil {
return updateObj, fmt.Errorf("parse diffOplog failed updateObj:[%v] err[%v]", updateObj, err)
}
return result, nil
}
func BuildUpdateDelteOplog(prefixField string, obj bson.D) (interface{}, error) {
var result bson.D
for _, ele := range obj {
if ele.Key == "d" {
result = append(result, primitive.E{
Key: "$unset",
Value: combinePrefixField(prefixField, ele.Value)})
} else if ele.Key == "i" || ele.Key == "u" {
result = append(result, primitive.E{
Key: "$set",
Value: combinePrefixField(prefixField, ele.Value)})
} else if len(ele.Key) > 1 && ele.Key[0] == 's' {
// s means subgroup field(array or nest)
tmpPrefixField := ""
if len(prefixField) == 0 {
tmpPrefixField = ele.Key[1:]
} else {
tmpPrefixField = prefixField + "." + ele.Key[1:]
}
nestObj, err := BuildUpdateDelteOplog(tmpPrefixField, ele.Value.(bson.D))
if err != nil {
return obj, fmt.Errorf("parse ele[%v] failed, updateObj:[%v]", ele, obj)
}
if _, ok := nestObj.(mongo.Pipeline); ok {
return nestObj, nil
} else if _, ok := nestObj.(bson.D); ok {
for _, nestObjEle := range nestObj.(bson.D) {
result = append(result, nestObjEle)
}
} else {
return obj, fmt.Errorf("unknown nest type ele[%v] updateObj:[%v] nestObj[%v]", ele, obj, nestObj)
}
} else if len(ele.Key) > 1 && ele.Key[0] == 'u' {
result = append(result, primitive.E{
Key: "$set",
Value: bson.D{
primitive.E{
Key: prefixField + "." + ele.Key[1:],
Value: ele.Value,
},
},
})
} else if ele.Key == "l" {
if len(result) != 0 {
return obj, fmt.Errorf("len should be 0, Key[%v] updateObj:[%v], result:[%v]",
ele, obj, result)
}
return mongo.Pipeline{
{{"$set", bson.D{
{prefixField, bson.D{
{"$slice", []interface{}{"$" + prefixField, ele.Value}},
}},
}}},
}, nil
} else if ele.Key == "a" && ele.Value == true {
continue
} else {
return obj, fmt.Errorf("unknow Key[%v] updateObj:[%v]", ele, obj)
}
}
return result, nil
}
func combinePrefixField(prefixField string, obj interface{}) interface{} {
if len(prefixField) == 0 {
return obj
}
tmpObj, ok := obj.(bson.D)
if !ok {
return obj
}
var result bson.D
for _, ele := range tmpObj {
result = append(result, primitive.E{
Key: prefixField + "." + ele.Key,
Value: ele.Value})
}
return result
}