/
diff.go
382 lines (337 loc) · 8.59 KB
/
diff.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
package cmd
import (
"fmt"
"reflect"
"regexp"
"sync"
"sync/atomic"
"github.com/go-redis/redis"
"github.com/spf13/cobra"
pb "gopkg.in/cheggaaa/pb.v1"
)
const compareCount = 4000
type differ struct {
allKeys1 *sync.Map
allKeys2 *sync.Map
ignoreKeys string
valsProcessed uint64
}
var di = newDiffer()
// diffCmd is for comparing two redis databases.
var diffCmd = &cobra.Command{
Use: "diff",
Short: "Compares two redis databases",
Long: `Compares two redis databases using scans and pipelining`,
Run: di.diffCommand,
}
func init() {
rootCmd.AddCommand(diffCmd)
diffCmd.Flags().StringVarP(&di.ignoreKeys, "ignorekeys", "", "", "Regex for keys to ignore")
}
func newDiffer() *differ {
return &differ{
allKeys1: new(sync.Map),
allKeys2: new(sync.Map),
}
}
func (d *differ) diffCommand(cmd *cobra.Command, args []string) {
d.diff()
}
func (d *differ) diff() bool {
size1, err := sclient.DBSize().Result()
if err != nil {
panic(fmt.Sprintf("Error getting database 1 size: %v", err))
}
size2, err := dclient.DBSize().Result()
if err != nil {
panic(fmt.Sprintf("Error getting source database 2 size: %v", err))
}
ch1 := make(chan []string)
keysOnly := size1 != size2
go genericReadWithClose("", func(key string, cursor uint64, match string, count int64) ([]string, uint64, error) {
return sclient.Scan(cursor, "", count).Result()
}, ch1, compareCount, keysOnly)
var bar *pb.ProgressBar
var differ bool
if keysOnly {
logger.Debugf("Databases have different sizes: %v and %v...determining differing keys", size1, size2)
ch2 := make(chan []string)
go genericReadWithClose("", func(key string, cursor uint64, match string, count int64) ([]string, uint64, error) {
return dclient.Scan(cursor, "", count).Result()
}, ch2, compareCount, keysOnly)
bar = pb.StartNew(int(size1) + int(size2))
differ = d.diffKeys(ch1, ch2, size1, size2, bar)
} else {
bar = pb.StartNew(int(size1))
differ = d.resultsDiffer(ch1, size1, bar)
}
var msg string
if size1 != size2 {
msg = "The redises have different sizes!"
} else if differ {
msg = "The redises are different!"
} else {
msg = "The redises are the same!"
}
bar.FinishPrint(msg)
return differ
}
func (d *differ) diffKeys(ch1, ch2 chan []string, size1, size2 int64, bar *pb.ProgressBar) bool {
var wg sync.WaitGroup
wg.Add(2)
go d.diffOnChan(ch1, d.allKeys1, d.allKeys2, bar, &wg, size1)
go d.diffOnChan(ch2, d.allKeys2, d.allKeys1, bar, &wg, size2)
wg.Wait()
return d.checkKeys("DB1", d.allKeys1) || d.checkKeys("DB2", d.allKeys2)
}
func (d *differ) checkKeys(name string, keys *sync.Map) bool {
length := 0
keys.Range(func(_, _ interface{}) bool {
length++
return true
})
if length > 0 {
logger.Debugf("Remaining keys for %v: %+v", name, keys)
return true
}
return false
}
func (d *differ) diffOnChan(ch chan []string, chanKeys, otherKeys *sync.Map,
bar *pb.ProgressBar, wg *sync.WaitGroup, size int64) {
defer wg.Done()
if size == 0 {
return
}
var matchesKey = regexp.MustCompile(d.ignoreKeys)
for keys := range ch {
for _, key := range keys {
if d.ignoreKeys != "" && matchesKey.MatchString(key) {
bar.Increment()
continue
}
if _, ok := otherKeys.Load(key); ok {
// Delete matching keys as we go and don't add them to avoid consuming too much memory.
atomic.AddUint64(&d.valsProcessed, 1)
otherKeys.Delete(key)
} else {
chanKeys.Store(key, "")
}
bar.Increment()
}
}
}
func (d *differ) resultsDiffer(ch chan []string, size int64, bar *pb.ProgressBar) bool {
if size == 0 {
return false
}
processed := int64(0)
for {
keys := <-ch
if d.valuesDiffer(keys, bar) {
return true
}
processed += int64(len(keys))
if processed == size {
break
}
}
return false
}
func (d *differ) valuesDiffer(keys []string, bar *pb.ProgressBar) bool {
spl := sclient.Pipeline()
for _, key := range keys {
spl.Type(key)
}
cmds, err := spl.Exec()
if err != nil {
panic(fmt.Sprintf("Could not exec types pipeline: %v", err))
}
spl.Close()
//dpl := dclient.Pipeline()
for i, cmd := range cmds {
keyType := d.toVal(cmd)
switch keyType {
case "string":
if d.stringDiffers(keys[i]) {
return true
}
case "list":
if d.listDiffers(keys[i]) {
return true
}
case "set":
if d.setDiffers(keys[i], sclient.SScan, dclient.SScan, false) {
return true
}
case "zset":
if d.setDiffers(keys[i], sclient.ZScan, dclient.ZScan, true) {
return true
}
case "hash":
if d.hashDiffers(keys[i]) {
return true
}
case "stream":
logger.Debug("handling stream")
default:
logger.Debug("handling default")
}
atomic.AddUint64(&d.valsProcessed, uint64(1))
bar.Increment()
}
return false
}
type resulter interface {
Result() (string, error)
}
type sliceResulter interface {
Result() ([]string, error)
}
type scanResulter interface {
Result() ([]string, uint64, error)
}
func (d *differ) toVal(cmd redis.Cmder) string {
switch cmd.(type) {
case *redis.StatusCmd:
return d.result(cmd.(*redis.StatusCmd))
case *redis.StringCmd:
return d.result(cmd.(*redis.StringCmd))
default:
logger.Debug("Got other type: %v *************", reflect.TypeOf(cmd))
}
panic(fmt.Sprintf("Could not handle command %v", cmd))
}
func (d *differ) result(res resulter) string {
if val, err := res.Result(); err != nil {
panic(fmt.Sprintf("Could not result for type pipeline: %v", err))
} else {
return val
}
}
func (d *differ) sliceResult(res sliceResulter) []string {
if val, err := res.Result(); err != nil {
panic(fmt.Sprintf("Could not result for type pipeline: %v", err))
} else {
return val
}
}
func (d *differ) scanResult(res scanResulter) ([]string, uint64) {
if val, cursor, err := res.Result(); err != nil {
panic(fmt.Sprintf("Could not result for type pipeline: %v", err))
} else {
return val, cursor
}
}
func (d *differ) stringDiffers(key string) bool {
return sclient.Get(key).Val() != dclient.Get(key).Val()
}
func (d *differ) listDiffers(key string) bool {
const count = int64(10000)
cursor := int64(0)
for {
newCursor := cursor + count
svals := d.sliceResult(sclient.LRange(key, cursor, newCursor))
dvals := d.sliceResult(dclient.LRange(key, cursor, newCursor))
if len(svals) != len(dvals) {
return true
}
for i, v := range svals {
if v != dvals[i] {
return true
}
}
if len(svals) == 0 || len(dvals) == 0 {
break
}
cursor = newCursor + 1
}
return false
}
func (d *differ) setDiffers(key string, source, dest scanf, skip bool) bool {
diff, _ := d.setDiffersWithCount(key, int64(10000), source, dest, skip)
return diff
}
type scanf func(string, uint64, string, int64) *redis.ScanCmd
func (d *differ) setDiffersWithCount(key string, count int64, source, dest scanf, skip bool) (bool, int) {
smap := make(map[string]bool)
dmap := make(map[string]bool)
scursor := uint64(0)
dcursor := uint64(0)
processed := 0
f := func(vals []string, a, b map[string]bool) {
for i, v := range vals {
// zsets include their score as well, which we skip.
if skip && i%2 != 0 {
continue
}
if _, ok := b[v]; ok {
delete(b, v)
processed++
} else {
a[v] = true
}
}
}
for {
var svals, dvals []string
svals, scursor = d.scanResult(source(key, scursor, "", count))
dvals, dcursor = d.scanResult(dest(key, dcursor, "", count))
f(svals, smap, dmap)
f(dvals, dmap, smap)
if scursor == 0 || dcursor == 0 {
break
}
}
if len(smap) != 0 || len(dmap) != 0 {
return true, processed
}
return false, processed
}
func (d *differ) hashDiffers(key string) bool {
differs, _ := d.hashDiffersWithCount(key, int64(10000))
return differs
}
func (d *differ) hashDiffersWithCount(key string, count int64) (bool, int) {
smap := make(map[string]string)
dmap := make(map[string]string)
scursor := uint64(0)
dcursor := uint64(0)
processed := 0
f := func(kvs []string, a, b map[string]string) bool {
for i := 0; i < len(kvs); i += 2 {
k := kvs[i]
v := kvs[i+1]
if bv, ok := b[k]; ok {
if bv == v {
// Remove this key from the other DB map to save memory -- at this
// point the keys and values check out and are equal.
delete(b, k)
processed++
} else {
return true
}
} else {
a[k] = v
}
}
return false
}
for {
var svals, dvals []string
svals, scursor = d.scanResult(sclient.HScan(key, scursor, "", count))
dvals, dcursor = d.scanResult(dclient.HScan(key, dcursor, "", count))
if f(svals, smap, dmap) {
return true, processed
}
if f(dvals, dmap, smap) {
return true, processed
}
if scursor == 0 || dcursor == 0 {
break
}
}
if len(smap) != 0 || len(dmap) != 0 {
return true, processed
}
return false, processed
}