forked from tidwall/tile38
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaof.go
More file actions
746 lines (722 loc) · 17.1 KB
/
Copy pathaof.go
File metadata and controls
746 lines (722 loc) · 17.1 KB
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
package controller
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/boltdb/bolt"
"github.com/google/btree"
"github.com/tidwall/tile38/client"
"github.com/tidwall/tile38/log"
)
const backwardsBufferSize = 50000
var errCorruptedAOF = errors.New("corrupted aof file")
type AOFReader struct {
r io.Reader // reader
rerr error // read error
chunk []byte // chunk buffer
buf []byte // main buffer
l int // length of valid data in buffer
p int // pointer
}
func (rd *AOFReader) ReadCommand() ([]byte, error) {
if rd.l >= 4 {
sz1 := int(binary.LittleEndian.Uint32(rd.buf[rd.p:]))
if rd.l >= sz1+9 {
// we have enough data for a record
sz2 := int(binary.LittleEndian.Uint32(rd.buf[rd.p+4+sz1:]))
if sz2 != sz1 || rd.buf[rd.p+4+sz1+4] != 0 {
return nil, errCorruptedAOF
}
buf := rd.buf[rd.p+4 : rd.p+4+sz1]
rd.p += sz1 + 9
rd.l -= sz1 + 9
return buf, nil
}
}
// need more data
if rd.rerr != nil {
if rd.rerr == io.EOF {
rd.rerr = nil // we want to return EOF, but we want to be able to try again
if rd.l != 0 {
return nil, io.ErrUnexpectedEOF
}
return nil, io.EOF
}
return nil, rd.rerr
}
if rd.p != 0 {
// move p to the beginning
copy(rd.buf, rd.buf[rd.p:rd.p+rd.l])
rd.p = 0
}
var n int
n, rd.rerr = rd.r.Read(rd.chunk)
if n > 0 {
cbuf := rd.chunk[:n]
if len(rd.buf)-rd.l < n {
if len(rd.buf) == 0 {
rd.buf = make([]byte, len(cbuf))
copy(rd.buf, cbuf)
} else {
copy(rd.buf[rd.l:], cbuf[:len(rd.buf)-rd.l])
rd.buf = append(rd.buf, cbuf[len(rd.buf)-rd.l:]...)
}
} else {
copy(rd.buf[rd.l:], cbuf)
}
rd.l += n
}
return rd.ReadCommand()
}
func NewAOFReader(r io.Reader) *AOFReader {
rd := &AOFReader{r: r, chunk: make([]byte, 0xFFFF)}
return rd
}
func (c *Controller) loadAOF() error {
start := time.Now()
var count int
defer func() {
d := time.Now().Sub(start)
ps := float64(count) / (float64(d) / float64(time.Second))
log.Infof("AOF loaded %d commands: %s: %.0f/sec", count, d, ps)
}()
rd := NewAOFReader(c.f)
for {
buf, err := rd.ReadCommand()
if err != nil {
if err == io.EOF {
return nil
}
if err == io.ErrUnexpectedEOF || err == errCorruptedAOF {
log.Warnf("aof is corrupted, likely data loss. Truncating to %d", c.aofsz)
fname := c.f.Name()
c.f.Close()
if err := os.Truncate(c.f.Name(), int64(c.aofsz)); err != nil {
log.Fatalf("could not truncate aof, possible data loss. %s", err.Error())
return err
}
c.f, err = os.OpenFile(fname, os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
log.Fatalf("could not create aof, possible data loss. %s", err.Error())
return err
}
if _, err := c.f.Seek(int64(c.aofsz), 0); err != nil {
log.Fatalf("could not seek aof, possible data loss. %s", err.Error())
return err
}
}
return err
}
if _, _, err := c.command(string(buf), nil); err != nil {
return err
}
c.aofsz += 9 + len(buf)
count++
}
}
func writeCommand(w io.Writer, line []byte) (n int, err error) {
b := make([]byte, len(line)+9)
binary.LittleEndian.PutUint32(b, uint32(len(line)))
copy(b[4:], line)
binary.LittleEndian.PutUint32(b[len(b)-5:], uint32(len(line)))
return w.Write(b)
}
func (c *Controller) writeAOF(line string, d *commandDetailsT) error {
n, err := writeCommand(c.f, []byte(line))
if err != nil {
return err
}
c.aofsz += n
// notify aof live connections that we have new data
c.fcond.L.Lock()
c.fcond.Broadcast()
c.fcond.L.Unlock()
// write to live connection streams
if d != nil {
c.lcond.L.Lock()
c.lstack = append(c.lstack, d)
c.lcond.Broadcast()
c.lcond.L.Unlock()
}
return nil
}
type liveAOFSwitches struct {
pos int64
}
func (s liveAOFSwitches) Error() string {
return "going live"
}
func (c *Controller) cmdAOFMD5(line string) (string, error) {
start := time.Now()
var spos, ssize string
if line, spos = token(line); spos == "" {
return "", errInvalidNumberOfArguments
}
if line, ssize = token(line); ssize == "" {
return "", errInvalidNumberOfArguments
}
if line != "" {
return "", errInvalidNumberOfArguments
}
pos, err := strconv.ParseInt(spos, 10, 64)
if err != nil || pos < 0 {
return "", errInvalidArgument(spos)
}
size, err := strconv.ParseInt(ssize, 10, 64)
if err != nil || size < 0 {
return "", errInvalidArgument(ssize)
}
sum, err := c.checksum(pos, size)
if err != nil {
return "", err
}
return fmt.Sprintf(`{"ok":true,"md5":"%s","elapsed":"%s"}`, sum, time.Now().Sub(start)), nil
}
func (c *Controller) cmdAOF(line string, w io.Writer) error {
var spos string
if line, spos = token(line); spos == "" {
return errInvalidNumberOfArguments
}
if line != "" {
return errInvalidNumberOfArguments
}
pos, err := strconv.ParseInt(spos, 10, 64)
if err != nil || pos < 0 {
return errInvalidArgument(spos)
}
f, err := os.Open(c.f.Name())
if err != nil {
return err
}
defer f.Close()
n, err := f.Seek(0, 2)
if err != nil {
return err
}
if n < pos {
return errors.New("pos is too big, must be less that the aof_size of leader")
}
var s liveAOFSwitches
s.pos = pos
return s
}
func (c *Controller) liveAOF(pos int64, conn net.Conn, rd *bufio.Reader) error {
defer conn.Close()
if err := client.WriteMessage(conn, []byte(client.LiveJSON)); err != nil {
return nil // nil return is fine here
}
c.mu.RLock()
f, err := os.Open(c.f.Name())
c.mu.RUnlock()
if err != nil {
return err
}
defer f.Close()
if _, err := f.Seek(pos, 0); err != nil {
return err
}
cond := sync.NewCond(&sync.Mutex{})
var mustQuit bool
go func() {
defer func() {
cond.L.Lock()
mustQuit = true
cond.Broadcast()
cond.L.Unlock()
}()
for {
command, _, err := client.ReadMessage(rd, nil)
if err != nil {
if err != io.EOF {
log.Error(err)
}
return
}
cmd := string(command)
if cmd != "" && strings.ToLower(cmd) != "quit" {
log.Error("received a live command that was not QUIT")
return
}
}
}()
go func() {
defer func() {
cond.L.Lock()
mustQuit = true
cond.Broadcast()
cond.L.Unlock()
}()
err := func() error {
_, err := io.Copy(conn, f)
if err != nil {
return err
}
rd := NewAOFReader(f)
for {
cmd, err := rd.ReadCommand()
if err != io.EOF {
if err != nil {
return err
}
if _, err := writeCommand(conn, cmd); err != nil {
return err
}
continue
}
c.fcond.L.Lock()
c.fcond.Wait()
c.fcond.L.Unlock()
}
}()
if err != nil {
if !strings.Contains(err.Error(), "use of closed network connection") &&
!strings.Contains(err.Error(), "bad file descriptor") {
log.Error(err)
}
return
}
}()
for {
cond.L.Lock()
if mustQuit {
cond.L.Unlock()
return nil
}
cond.Wait()
cond.L.Unlock()
}
}
type treeKeyBoolT struct {
key string
}
func (k *treeKeyBoolT) Less(item btree.Item) bool {
return k.key < item.(*treeKeyBoolT).key
}
// aofshink shinks the aof file in the background
// When completed the only command that should exist in a shrunken aof is SET.
// We will read the commands backwards from last known position of the live aof
// and use an ondisk key value store for state. For now we use BoltDB, in the future
// we should use a store that is better performant.
// The following commands may exist in the aof.
// 'SET'
// - Has this key been marked 'ignore'?
// - Yes, then ignore
// - No, Has this id been marked 'soft-ignore' or 'hard-ignore'?
// - Yes, then ignore
// - No
// - Add command to key bucket
// - Mark id as 'soft-ignore'
// 'FSET'
// - Has this key been marked 'ignore'?
// - Yes, then ignore
// - No, Has this id been marked 'hard-ignore'?
// - Yes, then ignore
// - No
// - Add command to key bucket
// 'DEL'
// - Has this key been marked 'ignore'?
// - Yes, then ignore
// - No, Mark id as 'ignore'?
// 'DROP'
// - Has this key been marked 'ignore'?
// - Yes, then ignore
// - No, Mark key as 'ignore'?
// 'FLUSHDB'
// - Stop shrinking, nothing left to do
func (c *Controller) aofshrink() {
c.mu.Lock()
c.f.Sync()
if c.shrinking {
c.mu.Unlock()
return
}
c.shrinking = true
endpos := int64(c.aofsz)
start := time.Now()
log.Infof("aof shrink started at pos %d", endpos)
c.mu.Unlock()
var err error
defer func() {
c.mu.Lock()
c.shrinking = false
c.mu.Unlock()
os.RemoveAll(c.dir + "/shrink.db")
os.RemoveAll(c.dir + "/shrink")
if err != nil {
log.Error("aof shrink failed: " + err.Error())
} else {
log.Info("aof shrink completed: " + time.Now().Sub(start).String())
}
}()
var db *bolt.DB
db, err = bolt.Open(c.dir+"/shrink.db", 0600, nil)
if err != nil {
return
}
defer db.Close()
var nf *os.File
nf, err = os.Create(c.dir + "/shrink")
if err != nil {
return
}
defer nf.Close()
defer func() {
c.mu.Lock()
defer c.mu.Unlock()
if err == nil {
c.f.Sync()
_, err = nf.Seek(0, 2)
if err == nil {
var f *os.File
f, err = os.Open(c.dir + "/aof")
if err != nil {
return
}
defer f.Close()
_, err = f.Seek(endpos, 0)
if err == nil {
_, err = io.Copy(nf, f)
if err == nil {
f.Close()
nf.Close()
// At this stage we need to kill all aof followers. To do so we will
// write a KILLAOF command to the stream. KILLAOF isn't really a command.
// This will cause the followers will close their connection and then
// automatically reconnect. The reconnection will force a sync of the aof.
err = c.writeAOF("KILLAOF", nil)
if err == nil {
c.f.Close()
err = os.Rename(c.dir+"/shrink", c.dir+"/aof")
if err != nil {
log.Fatal("shink rename fatal operation")
}
c.f, err = os.OpenFile(c.dir+"/aof", os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
log.Fatal("shink openfile fatal operation")
}
var n int64
n, err = c.f.Seek(0, 2)
if err != nil {
log.Fatal("shink seek end fatal operation")
}
c.aofsz = int(n)
}
}
}
}
}
}()
var f *os.File
f, err = os.Open(c.dir + "/aof")
if err != nil {
return
}
defer f.Close()
var buf []byte
var pos int64
pos, err = f.Seek(endpos, 0)
if err != nil {
return
}
var readPreviousCommand func() ([]byte, error)
readPreviousCommand = func() ([]byte, error) {
if len(buf) >= 5 {
if buf[len(buf)-1] != 0 {
return nil, errCorruptedAOF
}
sz2 := int(binary.LittleEndian.Uint32(buf[len(buf)-5:]))
if len(buf) >= sz2+9 {
sz1 := int(binary.LittleEndian.Uint32(buf[len(buf)-(sz2+9):]))
if sz1 != sz2 {
return nil, errCorruptedAOF
}
command := buf[len(buf)-(sz2+5) : len(buf)-5]
buf = buf[:len(buf)-(sz2+9)]
return command, nil
}
}
if pos == 0 {
if len(buf) > 0 {
return nil, io.ErrUnexpectedEOF
} else {
return nil, io.EOF
}
}
sz := int64(backwardsBufferSize)
offset := pos - sz
if offset < 0 {
sz = pos
offset = 0
}
pos, err = f.Seek(offset, 0)
if err != nil {
return nil, err
}
nbuf := make([]byte, int(sz))
_, err = io.ReadFull(f, nbuf)
if err != nil {
return nil, err
}
if len(buf) > 0 {
nbuf = append(nbuf, buf...)
}
buf = nbuf
return readPreviousCommand()
}
var tx *bolt.Tx
tx, err = db.Begin(true)
if err != nil {
return
}
defer func() {
tx.Rollback()
}()
var keyIgnoreM = map[string]bool{}
var keyBucketM = btree.New(16)
var cmd, key, id, field string
var line string
var command []byte
var val []byte
var b *bolt.Bucket
reading:
for i := 0; ; i++ {
if i%500 == 0 {
if err = tx.Commit(); err != nil {
return
}
tx, err = db.Begin(true)
if err != nil {
return
}
}
command, err = readPreviousCommand()
if err != nil {
if err == io.EOF {
err = nil
break
}
return
}
// quick path
if len(command) == 0 {
continue // ignore blank commands
}
line, cmd = token(string(command))
cmd = strings.ToLower(cmd)
switch cmd {
case "flushdb":
break reading // all done
case "drop":
if line, key = token(line); key == "" {
err = errors.New("drop is missing key")
return
}
if !keyIgnoreM[key] {
keyIgnoreM[key] = true
}
case "del":
if line, key = token(line); key == "" {
err = errors.New("del is missing key")
return
}
if keyIgnoreM[key] {
continue // ignore
}
if line, id = token(line); id == "" {
err = errors.New("del is missing id")
return
}
if keyBucketM.Get(&treeKeyBoolT{key}) == nil {
if _, err = tx.CreateBucket([]byte(key + ".ids")); err != nil {
return
}
if _, err = tx.CreateBucket([]byte(key + ".ignore_ids")); err != nil {
return
}
keyBucketM.ReplaceOrInsert(&treeKeyBoolT{key})
}
b = tx.Bucket([]byte(key + ".ignore_ids"))
err = b.Put([]byte(id), []byte("2")) // 2 for hard ignore
if err != nil {
return
}
case "set":
if line, key = token(line); key == "" {
err = errors.New("SET is missing key")
return
}
if keyIgnoreM[key] {
continue // ignore
}
if line, id = token(line); id == "" {
err = errors.New("SET is missing id")
return
}
if keyBucketM.Get(&treeKeyBoolT{key}) == nil {
if _, err = tx.CreateBucket([]byte(key + ".ids")); err != nil {
return
}
if _, err = tx.CreateBucket([]byte(key + ".ignore_ids")); err != nil {
return
}
keyBucketM.ReplaceOrInsert(&treeKeyBoolT{key})
}
b = tx.Bucket([]byte(key + ".ignore_ids"))
val = b.Get([]byte(id))
if val == nil {
if err = b.Put([]byte(id), []byte("1")); err != nil {
return
}
b = tx.Bucket([]byte(key + ".ids"))
if err = b.Put([]byte(id), command); err != nil {
return
}
} else {
switch string(val) {
default:
err = errors.New("invalid ignore")
case "1", "2":
continue // ignore
}
}
case "fset":
if line, key = token(line); key == "" {
err = errors.New("FSET is missing key")
return
}
if keyIgnoreM[key] {
continue // ignore
}
if line, id = token(line); id == "" {
err = errors.New("FSET is missing id")
return
}
if line, field = token(line); field == "" {
err = errors.New("FSET is missing field")
return
}
if keyBucketM.Get(&treeKeyBoolT{key}) == nil {
if _, err = tx.CreateBucket([]byte(key + ".ids")); err != nil {
return
}
if _, err = tx.CreateBucket([]byte(key + ".ignore_ids")); err != nil {
return
}
keyBucketM.ReplaceOrInsert(&treeKeyBoolT{key})
}
b = tx.Bucket([]byte(key + ".ignore_ids"))
val = b.Get([]byte(id))
if val == nil {
b = tx.Bucket([]byte(key + ":" + id + ":0"))
if b == nil {
if b, err = tx.CreateBucket([]byte(key + ":" + id + ":0")); err != nil {
return
}
}
if b.Get([]byte(field)) == nil {
if err = b.Put([]byte(field), command); err != nil {
return
}
}
} else {
switch string(val) {
default:
err = errors.New("invalid ignore")
case "1":
b = tx.Bucket([]byte(key + ":" + id + ":1"))
if b == nil {
if b, err = tx.CreateBucket([]byte(key + ":" + id + ":1")); err != nil {
return
}
}
if b.Get([]byte(field)) == nil {
if err = b.Put([]byte(field), command); err != nil {
return
}
}
case "2":
continue // ignore
}
}
}
}
if err = tx.Commit(); err != nil {
return
}
tx, err = db.Begin(false)
if err != nil {
return
}
keyBucketM.Ascend(func(item btree.Item) bool {
key := item.(*treeKeyBoolT).key
b := tx.Bucket([]byte(key + ".ids"))
if b != nil {
err = b.ForEach(func(id, command []byte) error {
// parse the SET command
_, fields, values, etype, eargs, err := c.parseSetArgs(string(command[4:]))
if err != nil {
return err
}
// store the fields in a map
var fieldm = map[string]float64{}
for i, field := range fields {
fieldm[field] = values[i]
}
// append old FSET values. these are FSETs that existed prior to the last SET.
f1 := tx.Bucket([]byte(key + ":" + string(id) + ":1"))
if f1 != nil {
err = f1.ForEach(func(field, command []byte) error {
d, err := c.parseFSetArgs(string(command[5:]))
if err != nil {
return err
}
if _, ok := fieldm[d.field]; !ok {
fieldm[d.field] = d.value
}
return nil
})
if err != nil {
return err
}
}
// append new FSET values. these are FSETs that were added after the last SET.
f0 := tx.Bucket([]byte(key + ":" + string(id) + ":0"))
if f0 != nil {
f0.ForEach(func(field, command []byte) error {
d, err := c.parseFSetArgs(string(command[5:]))
if err != nil {
return err
}
fieldm[d.field] = d.value
return nil
})
}
// rebuild the SET command
ncommand := "set " + key + " " + string(id)
for field, value := range fieldm {
if value != 0 {
ncommand += " field " + field + " " + strconv.FormatFloat(value, 'f', -1, 64)
}
}
ncommand += " " + strings.ToUpper(etype) + " " + eargs
_, err = writeCommand(nf, []byte(ncommand))
if err != nil {
return err
}
return nil
})
if err != nil {
return false
}
}
return true
})
}