forked from infinilabs/crawler
/
volume.go
95 lines (88 loc) · 2 KB
/
volume.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
package storage
import (
log "github.com/cihub/seelog"
"io"
"os"
"path"
"strconv"
"sync"
)
const (
SuperBlockSize = 8
)
type Volume struct {
Id uint32
dir string
dataFile *os.File
nm *NeedleMap
accessLock sync.Mutex
}
func NewVolume(dirname string, id uint32) (v *Volume) {
var e error
v = &Volume{dir: dirname, Id: id}
fileName := strconv.FormatUint(uint64(v.Id), 10)
v.dataFile, e = os.OpenFile(path.Join(v.dir, fileName+".dat"), os.O_RDWR|os.O_CREATE, 0644)
if e != nil {
log.Error("New Volume [ERROR] %s\n", e)
}
v.maybeWriteSuperBlock()
indexFile, ie := os.OpenFile(path.Join(v.dir, fileName+".idx"), os.O_RDWR|os.O_CREATE, 0644)
if ie != nil {
log.Error("Write Volume Index [ERROR] %s\n", ie)
}
v.nm = LoadNeedleMap(indexFile)
return
}
func (v *Volume) Size() int64 {
stat, e := v.dataFile.Stat()
if e == nil {
return stat.Size()
}
return -1
}
func (v *Volume) Close() {
v.nm.Close()
v.dataFile.Close()
}
func (v *Volume) maybeWriteSuperBlock() {
stat, _ := v.dataFile.Stat()
if stat.Size() == 0 {
header := make([]byte, SuperBlockSize)
header[0] = 1
v.dataFile.Write(header)
}
}
func (v *Volume) write(n *Needle) uint32 {
v.accessLock.Lock()
defer v.accessLock.Unlock()
offset, _ := v.dataFile.Seek(0, 2)
ret := n.Append(v.dataFile)
nv, ok := v.nm.Get(n.Key)
if !ok || int64(nv.Offset)*8 < offset {
v.nm.Put(n.Key, uint32(offset/8), n.Size)
}
return ret
}
func (v *Volume) delete(n *Needle) uint32 {
v.accessLock.Lock()
defer v.accessLock.Unlock()
nv, ok := v.nm.Get(n.Key)
//log.Println("key", n.Key, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
if ok {
v.nm.Delete(n.Key)
v.dataFile.Seek(int64(nv.Offset*8), 0)
n.Append(v.dataFile)
return nv.Size
}
return 0
}
func (v *Volume) read(n *Needle) (int, error) {
v.accessLock.Lock()
defer v.accessLock.Unlock()
nv, ok := v.nm.Get(n.Key)
if ok && nv.Offset > 0 {
v.dataFile.Seek(int64(nv.Offset)*8, 0)
return n.Read(v.dataFile, nv.Size)
}
return -1, io.EOF
}