forked from recoilme/sniper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chunk.go
694 lines (629 loc) · 15.3 KB
/
chunk.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
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
package sniper
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"strings"
"sync"
"time"
"github.com/recoilme/sortedset"
)
const (
chunkVersion = 1
versionMarker = 255
deleted = 42 // flag for removed, tribute 2 dbf
)
var (
sizeHeaders = map[int]uint32{0: 8, 1: 12}
sizeHead = sizeHeaders[chunkVersion]
)
// chunk - local shard
type chunk struct {
sync.RWMutex
f *os.File // file storage
m map[uint32]addrSize // keys: hash / addr&len
h map[uint32]byte // holes: addr / size
needFsync bool
indexList []string
}
type addrSize struct {
addr uint32
size byte
}
type Header struct {
sizeb uint8
status uint8
keylen uint16
vallen uint32
expire uint32
}
// https://github.com/thejerf/gomempool/blob/master/pool.go#L519
// http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
// suitably modified to work on 32-bit
/*func nextPowerOf2(v uint32) uint32 {
v--
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v++
return v
}*/
// NextPowerOf2 return next power of 2 for v and it's value
// return maxuint32 in case of overflow
func NextPowerOf2(v uint32) (power byte, val uint32) {
if v == 0 {
return 0, 0
}
for power = 0; power < 32; power++ {
val = 1 << power
if val >= v {
break
}
}
if power == 32 {
//overflow
val = 4294967295
}
return
}
func detectChunkVersion(file *os.File) (version int, err error) {
b := make([]byte, 2)
n, errRead := file.Read(b)
if errRead != nil {
return -1, errRead
}
if n != 2 {
return -1, errors.New("file too short")
}
// 255 version marker
if b[0] == versionMarker {
if b[1] == 0 || b[1] == deleted {
// first version
return 0, nil
}
return int(b[1]), nil
}
if b[1] == 0 || b[1] == deleted {
// first version
return 0, nil
}
return -1, nil
}
func makeHeader(k, v []byte, expire uint32) (header *Header) {
header = &Header{}
header.status = 0
header.keylen = uint16(len(k))
header.vallen = uint32(len(v))
header.expire = expire
sizeb, _ := NextPowerOf2(uint32(header.keylen) + header.vallen + sizeHead)
header.sizeb = sizeb
return
}
func parseHeaderV0(b []byte) (header *Header) {
header = &Header{}
header.sizeb = b[0]
header.status = b[1]
header.keylen = binary.BigEndian.Uint16(b[2:4])
header.vallen = binary.BigEndian.Uint32(b[4:8])
return
}
func parseHeader(b []byte) (header *Header) {
header = &Header{}
header.sizeb = b[0]
header.status = b[1]
header.keylen = binary.BigEndian.Uint16(b[2:4])
header.vallen = binary.BigEndian.Uint32(b[4:8])
header.expire = binary.BigEndian.Uint32(b[8:12])
return
}
func readHeader(r io.Reader, version int) (header *Header, err error) {
b := make([]byte, sizeHeaders[version])
n, err := io.ReadFull(r, b)
if n != int(sizeHeaders[version]) {
if err == io.EOF {
err = nil
}
return
}
switch version {
case 0:
header = parseHeaderV0(b)
case 1:
header = parseHeader(b)
default:
err = fmt.Errorf("unknown header version %d", version)
}
return
}
func writeHeader(b []byte, header *Header) {
b[0] = header.sizeb
b[1] = header.status
binary.BigEndian.PutUint16(b[2:4], header.keylen)
binary.BigEndian.PutUint32(b[4:8], header.vallen)
binary.BigEndian.PutUint32(b[8:12], header.expire)
//return
}
// pack addr & size to addrSize
func addrSizeMarshal(addr uint32, size byte) addrSize {
return addrSize{addr, size}
}
// unpack addr & size
func addrSizeUnmarshal(as addrSize) (addr, size uint32) {
return as.addr, 1 << as.size
}
func packetMarshal(k, v []byte, expire uint32) (header *Header, b []byte) {
// write head
header = makeHeader(k, v, expire)
size := 1 << header.sizeb
b = make([]byte, size)
writeHeader(b, header)
// write body: val and key
copy(b[sizeHead:], v)
copy(b[sizeHead+header.vallen:], k)
return
}
func packetUnmarshal(packet []byte) (header *Header, k, v []byte) {
header = parseHeader(packet)
k = packet[sizeHead+header.vallen : sizeHead+header.vallen+uint32(header.keylen)]
v = packet[sizeHead : sizeHead+header.vallen]
return
}
func (c *chunk) init(name string, ss *sortedset.SortedSet) (err error) {
c.Lock()
defer c.Unlock()
f, err := os.OpenFile(name, os.O_CREATE|os.O_RDWR, os.FileMode(fileMode))
if err != nil {
return
}
err = f.Sync()
if err != nil {
return err
}
c.f = f
c.m = make(map[uint32]addrSize)
c.h = make(map[uint32]byte)
//read if f not empty
if fi, e := c.f.Stat(); e == nil {
// new file
if fi.Size() == 0 {
// write chunk version info
c.f.Write([]byte{versionMarker, chunkVersion})
return
}
//read file
var seek int
// detect chunk version
version, errDetect := detectChunkVersion(c.f)
if errDetect != nil {
err = errDetect
return
}
if version < 0 || version > 1 {
err = errors.New("unknown chunk version in file " + name)
return
}
if version == 0 {
// rewind to begin
c.f.Seek(0, 0)
} else {
// real chunk begin
seek = 2
}
// if load chunk with old version create file in new format
if version != chunkVersion {
var newfile *os.File
fmt.Printf("Load from old version chunk %s, do inplace upgrade v%d -> v%d\n", name, version, chunkVersion)
newname := name + ".new"
newfile, err = os.OpenFile(newname, os.O_CREATE|os.O_RDWR|os.O_TRUNC, os.FileMode(fileMode))
if err != nil {
return
}
// write chunk version info
newfile.Write([]byte{versionMarker, chunkVersion})
seek := 2
oldsizehead := sizeHeaders[version]
sizediff := sizeHead - oldsizehead
for {
var header *Header
var errRead error
header, errRead = readHeader(c.f, version)
if errRead != nil {
newfile.Close()
return errRead
}
if header == nil {
break
}
oldsizedata := (1 << header.sizeb) - oldsizehead
sizeb, size := NextPowerOf2(uint32(sizeHead) + uint32(header.keylen) + header.vallen)
header.sizeb = sizeb
b := make([]byte, size+sizediff)
writeHeader(b, header)
n, errRead := c.f.Read(b[sizeHead : sizeHead+oldsizedata])
if errRead != nil {
return fmt.Errorf("%s: %w", errRead.Error(), ErrFormat)
}
if n != int(oldsizedata) {
return fmt.Errorf("n != record length: %w", ErrFormat)
}
// skip deleted or expired entry
if header.status == deleted || (header.expire != 0 && int64(header.expire) < time.Now().Unix()) {
continue
}
keyidx := int(sizeHead) + int(header.vallen)
h := hash(b[keyidx : keyidx+int(header.keylen)])
c.m[h] = addrSizeMarshal(uint32(seek), header.sizeb)
n, errRead = newfile.Write(b[0:size])
if errRead != nil {
return fmt.Errorf("%s: %w", errRead.Error(), ErrFormat)
}
seek += n
}
// close old chunk file
errRead := c.f.Close()
if errRead != nil {
return fmt.Errorf("%s: %w", errRead.Error(), ErrFormat)
}
// set new file for chunk
c.f = newfile
// remove old chunk file from disk
errRead = os.Remove(name)
if errRead != nil {
return fmt.Errorf("%s: %w", errRead.Error(), ErrFormat)
}
// rename new file to old file
errRead = os.Rename(newname, name)
if errRead != nil {
return fmt.Errorf("%s: %w", errRead.Error(), ErrFormat)
}
return
}
var n int
for {
header, errRead := readHeader(c.f, version)
if errRead != nil {
return fmt.Errorf("%s: %w", errRead.Error(), ErrFormat)
}
if header == nil {
break
}
// skip val
_, seekerr := c.f.Seek(int64(header.vallen), 1)
if seekerr != nil {
return fmt.Errorf("%s: %w", seekerr.Error(), ErrFormat)
}
// read key
key := make([]byte, header.keylen)
n, errRead = c.f.Read(key)
if errRead != nil {
return fmt.Errorf("%s: %w", errRead.Error(), ErrFormat)
}
if n != int(header.keylen) {
return fmt.Errorf("n != key length: %w", ErrFormat)
}
shiftv := 1 << header.sizeb //2^pow
ret, seekerr := c.f.Seek(int64(shiftv-int(header.keylen)-int(header.vallen)-int(sizeHead)), 1) // skip empty tail
if seekerr != nil {
return ErrFormat
}
// map store
if header.status != deleted && (header.expire == 0 || int64(header.expire) >= time.Now().Unix()) {
h := hash(key)
c.m[h] = addrSizeMarshal(uint32(seek), header.sizeb)
// Put Index
c.put(ss, key)
} else {
//deleted blocks store
c.h[uint32(seek)] = header.sizeb // seek / size
}
seek = int(ret)
}
}
return
}
//fsync commits the current contents of the file to stable storage
func (c *chunk) fsync() error {
if c.needFsync {
c.Lock()
defer c.Unlock()
c.needFsync = false
return c.f.Sync()
}
return nil
}
//expirekeys walk all keys and delete expired
func (c *chunk) expirekeys() error {
c.Lock()
defer c.Unlock()
for h, addrsize := range c.m {
addr, _ := addrSizeUnmarshal(addrsize)
headerbuf := make([]byte, sizeHead)
_, err := c.f.ReadAt(headerbuf, int64(addr))
if err != nil {
return err
}
header := parseHeader(headerbuf)
if header.expire != 0 && int64(header.expire) < time.Now().Unix() {
delb := []byte{deleted}
_, err = c.f.WriteAt(delb, int64(addr+1))
if err != nil {
return err
}
delete(c.m, h)
c.h[addr] = header.sizeb
}
}
return nil
}
// set - write data to file & in map
func (c *chunk) set(k, v []byte, h uint32, expire uint32) (err error) {
c.Lock()
defer c.Unlock()
c.needFsync = true
header, b := packetMarshal(k, v, expire)
// write at file
pos := int64(-1)
if addrsize, ok := c.m[h]; ok {
addr, size := addrSizeUnmarshal(addrsize)
packet := make([]byte, size)
_, err = c.f.ReadAt(packet, int64(addr))
if err != nil {
return err
}
headerold, key, _ := packetUnmarshal(packet)
if !bytes.Equal(key, k) {
//println(string(key), string(k))
return ErrCollision
}
if headerold.sizeb == header.sizeb {
//overwrite
pos = int64(addr)
} else {
// mark old k/v as deleted
delb := []byte{deleted}
_, err = c.f.WriteAt(delb, int64(addr+1))
if err != nil {
return err
}
c.h[addr] = headerold.sizeb
// try to find optimal empty hole
for addrh, sizeh := range c.h {
if sizeh == header.sizeb {
pos = int64(addrh)
delete(c.h, addrh)
break
}
}
}
}
// write at end or in hole or overwrite
if pos < 0 {
pos, err = c.f.Seek(0, 2) // append to the end of file
}
_, err = c.f.WriteAt(b, pos)
if err != nil {
return err
}
c.m[h] = addrSizeMarshal(uint32(pos), header.sizeb)
return
}
// touch - write data to file & in map
func (c *chunk) touch(k []byte, h uint32, expire uint32) (err error) {
c.Lock()
defer c.Unlock()
if addrsize, ok := c.m[h]; ok {
addr, size := addrSizeUnmarshal(addrsize)
packet := make([]byte, size)
_, err = c.f.ReadAt(packet, int64(addr))
if err != nil {
return err
}
header, key, _ := packetUnmarshal(packet)
if !bytes.Equal(key, k) {
return ErrCollision
}
if header.expire != 0 && int64(header.expire) < time.Now().Unix() {
return ErrNotFound
}
header.expire = expire
b := make([]byte, sizeHead)
writeHeader(b, header)
_, err = c.f.WriteAt(b, int64(addr))
if err != nil {
return err
}
c.needFsync = true
} else {
return ErrNotFound
}
return
}
// get return val by key
func (c *chunk) get(k []byte, h uint32) (v []byte, header *Header, err error) {
c.RLock()
defer c.RUnlock()
if addrsize, ok := c.m[h]; ok {
addr, size := addrSizeUnmarshal(addrsize)
packet := make([]byte, size)
_, err = c.f.ReadAt(packet, int64(addr))
if err != nil {
return
}
header, key, val := packetUnmarshal(packet)
if !bytes.Equal(key, k) {
return nil, nil, ErrCollision
}
if header.expire != 0 && int64(header.expire) < time.Now().Unix() {
c.RUnlock()
_, err := c.delete(k, h)
c.RLock()
if err != nil {
return nil, nil, err
}
return nil, nil, ErrNotFound
}
v = val
} else {
return nil, nil, ErrNotFound
}
return
}
// return map length
func (c *chunk) count() int {
c.RLock()
defer c.RUnlock()
return len(c.m)
}
// close file
func (c *chunk) close() (err error) {
c.Lock()
defer c.Unlock()
return c.f.Close()
}
func (c *chunk) fileSize() (int64, error) {
c.Lock()
defer c.Unlock()
is, err := c.f.Stat()
if err != nil {
return -1, err
}
return is.Size(), nil
}
// delete mark item as deleted at specified position
func (c *chunk) delete(k []byte, h uint32) (isDeleted bool, err error) {
c.Lock()
defer c.Unlock()
if addrsize, ok := c.m[h]; ok {
addr, size := addrSizeUnmarshal(addrsize)
packet := make([]byte, size)
_, err = c.f.ReadAt(packet, int64(addr))
if err != nil {
return
}
header, key, _ := packetUnmarshal(packet)
if !bytes.Equal(key, k) {
return false, ErrCollision
}
delb := []byte{deleted}
_, err = c.f.WriteAt(delb, int64(addr+1))
if err != nil {
return
}
delete(c.m, h)
c.h[addr] = header.sizeb
isDeleted = true
}
return
}
// TODO - optimize
func (c *chunk) incrdecr(k []byte, h uint32, v uint64, isIncr bool) (counter uint64, err error) {
mutex.Lock()
defer mutex.Unlock()
old, header, err := c.get(k, h)
expire := uint32(0)
if header != nil {
expire = header.expire
}
if err == ErrNotFound {
//create empty counter
old = make([]byte, 8)
err = nil
}
if len(old) != 8 {
//better, then panic
return 0, errors.New("unexpected value format")
}
if err != nil {
return
}
counter = binary.BigEndian.Uint64(old)
if isIncr {
counter += v
} else {
//decr
counter -= v
}
new := make([]byte, 8)
binary.BigEndian.PutUint64(new, counter)
err = c.set(k, new, h, expire)
return
}
func (c *chunk) backup(w io.Writer) (err error) {
c.Lock()
defer c.Unlock()
_, seekerr := c.f.Seek(2, 0)
if seekerr != nil {
return fmt.Errorf("%s: %w", seekerr.Error(), ErrFormat)
}
for {
var header *Header
var errRead error
header, errRead = readHeader(c.f, chunkVersion)
if errRead != nil {
return errRead
}
if header == nil {
break
}
size := int(sizeHead) + int(header.vallen) + int(header.keylen) // record size
b := make([]byte, size)
writeHeader(b, header)
n, errRead := c.f.Read(b[sizeHead:])
if errRead != nil {
return fmt.Errorf("%s: %w", errRead.Error(), ErrFormat)
}
if n != size-int(sizeHead) {
return fmt.Errorf("n != record length: %d != %d %w", n, size-int(sizeHead), ErrFormat)
}
shiftv := 1 << header.sizeb //2^pow
_, seekerr := c.f.Seek(int64(shiftv-int(header.keylen)-int(header.vallen)-int(sizeHead)), 1) // skip empty tail
if seekerr != nil {
return ErrFormat
}
// skip deleted or expired entry
if header.status == deleted || (header.expire != 0 && int64(header.expire) < time.Now().Unix()) {
continue
}
_, errRead = w.Write(b)
if errRead != nil {
return fmt.Errorf("%s: %w", errRead.Error(), ErrFormat)
}
}
return nil
}
// index methods - only use loading the database
func (s *chunk) getKey(k []byte) (bucketName, key string) {
for _, indexName := range s.indexList {
if strings.HasPrefix(string(k), indexName) {
bucketName = indexName
break
}
}
if bucketName != "" {
return bucketName, strings.Replace(string(k), bucketName, "", 1)
}
return
}
//
func (s *chunk) put(ss *sortedset.SortedSet, k []byte) (err error) {
bucketName, key := s.getKey(k)
if bucketName != "" {
bucket := sortedset.Bucket(ss, bucketName)
bucket.Put(key)
}
return
}
/*
TODO: not needed yet :)
func (s *chunk) remove(ss *sortedset.SortedSet, k []byte) (err error) {
bucketName, key := s.getKey(k)
if bucketName != "" {
ss.Delete(key)
}
return
}*/