/
flatfile.go
395 lines (342 loc) · 8.25 KB
/
flatfile.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
package flatfile
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io/ioutil"
"log"
"path"
"path/filepath"
"sync"
"time"
lru "github.com/hashicorp/golang-lru"
"os"
"strconv"
)
type FlatFile interface {
//append item uint64o flat file, return item index
Append([]byte) (uint64, error)
//read item in flatfile with specific index (return from append)
Read(index uint64) ([]byte, error)
//read recent data, return data channel, errpr channel, and cancel function
ReadFromIndex(index uint64) (chan []byte, chan uint64, func())
//truncate flat file system
Truncate(lastIndex uint64) error
//return current size of ff
Size() uint64
//Path
Path() string
FileSize() uint64
}
type FlatFileManager struct {
dataDir string
fileSizeLimit uint64 //number of item
folderMap map[uint64]bool
currentFD *os.File
currentFile uint64
currentFileSize uint64
parseCache *lru.Cache
itemCache *lru.Cache
lock *sync.RWMutex
}
type ReadInfo struct {
fd *os.File
offset int64
size int64
}
func (ff *FlatFileManager) FileSize() uint64 {
return ff.fileSizeLimit
}
func (ff *FlatFileManager) Path() string {
return ff.dataDir
}
func (ff *FlatFileManager) Size() uint64 {
return ff.currentFile*ff.fileSizeLimit + ff.currentFileSize
}
func (ff *FlatFileManager) Truncate(lastIndex uint64) error {
lastFile := lastIndex / ff.fileSizeLimit
files, err := ioutil.ReadDir(ff.dataDir)
if err != nil {
return err
}
for _, f := range files {
name := filepath.Base(f.Name())
i, err := strconv.Atoi(name)
if err == nil {
if uint64(i) < lastFile {
err := os.Remove(path.Join(ff.dataDir, name))
log.Println("truncate file ", lastIndex, uint64(i), lastFile, err)
}
}
}
//newff, err := NewFlatFile(ff.dataDir, ff.fileSizeLimit)
//if err != nil {
// return nil
//}
//*ff = *newff
return nil
}
func (f *FlatFileManager) PasreFile(fileID uint64) (map[uint64]ReadInfo, error) {
f.lock.RLock()
defer f.lock.RUnlock()
//TODO: concert int64
p := path.Join(f.dataDir, strconv.Itoa(int(fileID)))
fd, err := os.Open(p)
if err != nil {
return nil, err
}
readInfos := make(map[uint64]ReadInfo)
offset := int64(0)
size := 0
for {
b := make([]byte, 8)
n, err := fd.ReadAt(b, offset)
if err != nil && err.Error() != "EOF" {
return nil, err
}
var result int64
err = binary.Read(bytes.NewBuffer(b), binary.LittleEndian, &result)
if err != nil || n == 0 {
break
}
readInf := ReadInfo{
fd,
offset + 8,
result,
}
id := len(readInfos)
readInfos[uint64(id)] = readInf
offset += 8
offset += result
size++
}
f.parseCache.Add(fileID, readInfos)
return readInfos, nil
}
func (f FlatFileManager) Read(index uint64) ([]byte, error) {
//get from cache byte firm
cacheByte, ok := f.itemCache.Get(index)
if ok {
return cacheByte.([]byte), nil
}
//else, parse and read
fileID := index / f.fileSizeLimit
itemFileIndex := index % f.fileSizeLimit
var readInfo map[uint64]ReadInfo
var err error
//find parse info in cache first
v, ok := f.parseCache.Get(fileID)
if ok {
if int(itemFileIndex) < len(v.(map[uint64]ReadInfo)) {
readInfo = v.(map[uint64]ReadInfo)
} else { //if find item index is greater than len of cache <- could be new item, parse again
readInfo, err = f.PasreFile(fileID)
}
} else { //no cache, parse
readInfo, err = f.PasreFile(fileID)
}
if err != nil {
return nil, err
}
if int(itemFileIndex) >= len(readInfo) {
return nil, errors.New(fmt.Sprintf("Cannot read item at index %v", index))
}
b := make([]byte, readInfo[itemFileIndex].size)
readInfo[itemFileIndex].fd.ReadAt(b, int64(readInfo[itemFileIndex].offset))
rawB, err := ioutil.ReadAll(bytes.NewBuffer(b))
if err != nil {
return nil, err
}
return rawB, nil
}
func (f FlatFileManager) ReadFromIndex(index uint64) (chan []byte, chan uint64, func()) {
c := make(chan []byte)
e := make(chan uint64)
closed := false
var cancel = func() {
if !closed {
close(c)
closed = true
}
}
go func() {
fromFile := index / f.fileSizeLimit
offset := index % f.fileSizeLimit
for i := int64(fromFile); i <= int64(f.currentFile); i++ {
//find parse info in cache first
var readInfo map[uint64]ReadInfo
var err error
v, ok := f.parseCache.Get(i)
if ok {
if int(offset) < len(v.(map[uint64]ReadInfo)) {
readInfo = v.(map[uint64]ReadInfo)
} else { //if find item index is greater than len of cache <- could be new item, parse again
readInfo, err = f.PasreFile(uint64(i))
}
} else { //no cache, parse
readInfo, err = f.PasreFile(uint64(i))
}
if err != nil {
e <- 1
cancel()
}
startIndex := uint64(0)
if i == int64(fromFile) {
startIndex = offset
}
for j := int(startIndex); j < len(readInfo); j++ {
rawB := make([]byte, readInfo[uint64(j)].size)
readInfo[uint64(j)].fd.ReadAt(rawB, readInfo[uint64(j)].offset)
LOOP:
if !closed {
select {
case c <- rawB:
continue
default:
time.Sleep(time.Millisecond * 10)
goto LOOP
}
} else {
return
}
}
}
cancel()
}()
return c, e, cancel
}
func (f *FlatFileManager) newNextFile() (*os.File, error) {
i := 0
if f.currentFD != nil {
name := filepath.Base(f.currentFD.Name())
i, _ = strconv.Atoi(name)
i++
}
path := path.Join(f.dataDir, strconv.Itoa(i))
fd, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)
if err != nil {
return nil, err
}
f.currentFD = fd
f.currentFile = uint64(i)
f.currentFileSize = 0
f.folderMap[uint64(i)] = true
return fd, nil
}
//create new file if exceed size limit
func (f *FlatFileManager) update() error {
size, err := f.checkFileSize()
if err != nil {
return err
}
if size >= f.fileSizeLimit {
_, err := f.newNextFile()
if err != nil {
return err
}
} else {
f.currentFileSize = size
}
return nil
}
func (f *FlatFileManager) checkFileSize() (uint64, error) {
if f.currentFD == nil {
return 0, errors.New("Not yet open file!")
}
offset := uint64(0)
size := uint64(0)
for {
b := make([]byte, 8)
n, _ := f.currentFD.ReadAt(b, int64(offset))
var result uint64
err := binary.Read(bytes.NewBuffer(b), binary.LittleEndian, &result)
if err != nil || n == 0 {
break
}
offset += 8
offset += result
size++
}
return size, nil
}
func (f *FlatFileManager) Append(data []byte) (uint64, error) {
//fmt.Println("debug write", len(data))
f.lock.Lock()
defer f.lock.Unlock()
//append size-bytes uint64o current FD, if max -> create new file, update currentFD
var result = make([]byte, 8)
binary.LittleEndian.PutUint64(result, uint64(len(data)))
_, err := f.currentFD.Write(result)
if err != nil {
return 0, err
}
_, err = f.currentFD.Write(data)
if err != nil {
return 0, err
}
err = f.currentFD.Sync()
if err != nil {
return 0, err
}
addedItemIndex := f.currentFile*f.fileSizeLimit + f.currentFileSize
f.currentFileSize++
if f.currentFileSize >= f.fileSizeLimit {
f.newNextFile()
}
f.itemCache.Add(addedItemIndex, data)
return addedItemIndex, err
}
func NewFlatFile(dir string, fileBound uint64) (*FlatFileManager, error) {
cache, _ := lru.New(4)
itemCache, _ := lru.New(50)
ff := &FlatFileManager{
dataDir: dir,
fileSizeLimit: fileBound,
folderMap: make(map[uint64]bool),
lock: new(sync.RWMutex),
parseCache: cache,
itemCache: itemCache,
}
//read all file has number in folder -> uint64o folderMap, sortedFolder
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
return nil, err
}
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, err
}
currentFile := -1
for _, f := range files {
name := filepath.Base(f.Name())
i, err := strconv.Atoi(name)
if err == nil {
ff.folderMap[uint64(i)] = true
if currentFile < i {
currentFile = i
}
}
}
//open last file currentFD, update currentFileSize, if max -> create new file, update currentFD
if currentFile > -1 {
path := path.Join(ff.dataDir, strconv.Itoa(currentFile))
fd, err := os.OpenFile(path, os.O_APPEND|os.O_RDWR, 0666)
if err != nil {
return nil, err
}
ff.currentFD = fd
ff.currentFile = uint64(currentFile)
//read file size, and create new file in need
err = ff.update()
if err != nil {
return nil, err
}
} else {
_, err := ff.newNextFile()
if err != nil {
return nil, err
}
}
return ff, nil
}