/
file.go
480 lines (421 loc) · 11.6 KB
/
file.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
// KIProtect Hyper
// Copyright (C) 2021-2023 KIProtect GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package datastores
// Adapted from https://github.com/kiprotect/kodex/blob/master/parameters/file.go
/*
This implements an append-only file-based storage mechanism. It splits data
entries into chunks that are below the PIPE_BUF size limit, and thus will be
atomic on *most* POSIX-compliant file systems. This makes it possible to use
multiple instances of the storage mechanism in parallel, as the store will be
able to reassemble individual data chunks even if their order has been mangled
by parallel writes from different programs.
You should not use this to write data to network file systems like NFS, or other
file systems that do not implement proper atomic APPEND operations.
This storage mechanism is well suited for simple, append-only operations. You
can implement a compaction by e.g. regularly switching file names and rewriting
an in-memory copy to the new file. Again, parallel writing will not compromise
the file's integrity.
*/
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/kiprotect/go-helpers/forms"
"github.com/kiprotect/hyper"
"github.com/kiprotect/hyper/helpers"
"io"
"os"
"path/filepath"
"sort"
"sync"
)
var FileForm = forms.Form{
ErrorMsg: "invalid data encountered in the File config form",
Fields: []forms.Field{
{
Name: "filename",
Validators: []forms.Validator{
forms.IsString{},
},
},
},
}
func ValidateFileSettings(settings map[string]interface{}) (interface{}, error) {
if params, err := FileForm.Validate(settings); err != nil {
return nil, err
} else {
fileSettings := &FileSettings{}
if err := FileForm.Coerce(fileSettings, params); err != nil {
return nil, err
}
return fileSettings, nil
}
}
const BUFFER_SIZE = 255
const CHUNK_ID_LENGTH = 16
const CHUNK_HEADER_SIZE = 8 + CHUNK_ID_LENGTH
const CHUNK_VERSION = 1
const ENTRY_VERSION = 1
type DataChunk struct {
// The number of chunks for this hash
Chunks uint16
// The index of this chunk
Index uint16
// The actual ID of the entry this chunk belongs to
ID []byte
// The actual data in this chunk
Data []byte
}
func (d *DataChunk) Read(reader io.Reader) error {
d.ID = nil
d.Data = nil
d.Chunks = 0
d.Index = 0
bs2 := make([]byte, 2)
bs1 := make([]byte, 1)
// version
if _, err := io.ReadFull(reader, bs1); err != nil {
if err == io.EOF {
return nil
}
return err
}
version := bs1[0]
if version != 1 {
return fmt.Errorf("unknown version: %d", version)
}
// chunks
if _, err := io.ReadFull(reader, bs2); err != nil {
return err
}
d.Chunks = binary.LittleEndian.Uint16(bs2)
// index
if _, err := io.ReadFull(reader, bs2); err != nil {
return err
}
d.Index = binary.LittleEndian.Uint16(bs2)
// id length
if _, err := io.ReadFull(reader, bs2); err != nil {
return err
}
idLength := binary.LittleEndian.Uint16(bs2)
d.ID = make([]byte, idLength)
// id
if _, err := io.ReadFull(reader, d.ID); err != nil {
return err
}
if _, err := io.ReadFull(reader, bs2); err != nil {
return err
}
dataLength := binary.LittleEndian.Uint16(bs2)
d.Data = make([]byte, dataLength)
// data
if _, err := io.ReadFull(reader, d.Data); err != nil {
return err
}
return nil
}
// Writes a data chunkn to the given writer
func (d *DataChunk) Write(writer io.Writer) error {
var buffer bytes.Buffer
// we write the version
if size, err := buffer.Write([]byte{CHUNK_VERSION}); err != nil {
return err
} else if size != 1 {
return fmt.Errorf("could not write")
}
// we write the number of chunks
bs2 := make([]byte, 2)
binary.LittleEndian.PutUint16(bs2, d.Chunks)
if size, err := buffer.Write(bs2); err != nil {
return err
} else if size != 2 {
return fmt.Errorf("could not write")
}
// we write the chunk index
binary.LittleEndian.PutUint16(bs2, d.Index)
if size, err := buffer.Write(bs2); err != nil {
return err
} else if size != 2 {
return fmt.Errorf("could not write")
}
// we write the ID length
if len(d.ID) >= 1<<16 {
return fmt.Errorf("ID is too long")
}
binary.LittleEndian.PutUint16(bs2, uint16(len(d.ID)))
if size, err := buffer.Write(bs2); err != nil {
return err
} else if size != 2 {
return fmt.Errorf("could not write")
}
if size, err := buffer.Write(d.ID); err != nil {
return err
} else if size != len(d.ID) {
return fmt.Errorf("could not write")
}
// we write the data length
binary.LittleEndian.PutUint16(bs2, uint16(len(d.Data)))
if size, err := buffer.Write(bs2); err != nil {
return err
} else if size != 2 {
return fmt.Errorf("could not write")
}
if size, err := buffer.Write(d.Data); err != nil {
return err
} else if size != len(d.Data) {
return fmt.Errorf("could not write")
}
bytes := buffer.Bytes()
if size, err := writer.Write(bytes); err != nil {
return err
} else if size != len(bytes) {
return fmt.Errorf("could not write buffer")
}
return nil
}
func ToBytes(e *hyper.DataEntry) []byte {
bytes := make([]byte, len(e.Data)+len(e.ID)+4)
bytes[0] = ENTRY_VERSION
bytes[1] = e.Type
binary.LittleEndian.PutUint16(bytes[2:4], uint16(len(e.ID)))
copy(bytes[4:4+len(e.ID)], e.ID)
copy(bytes[4+len(e.ID):len(bytes)], e.Data)
return bytes
}
func FromBytes(data []byte) (*hyper.DataEntry, error) {
e := &hyper.DataEntry{}
if data[0] != ENTRY_VERSION {
return nil, fmt.Errorf("invalid version")
}
e.Type = data[1]
idLength := binary.LittleEndian.Uint16(data[2:4])
if int(idLength) > len(data)+4 {
return nil, fmt.Errorf("ID out of bounds")
}
e.ID = data[4 : 4+idLength]
e.Data = data[4+idLength : len(data)]
return e, nil
}
func MakeDataChunk(id []byte, chunks, index uint16, data []byte) *DataChunk {
return &DataChunk{
Chunks: chunks,
Index: index,
Data: data,
ID: id,
}
}
// Splits a data entry into multiple data chunks.
func Split(e *hyper.DataEntry) ([]*DataChunk, error) {
bytes := ToBytes(e)
effectiveBufferSize := BUFFER_SIZE - CHUNK_HEADER_SIZE
chunks := len(bytes) / effectiveBufferSize
if len(bytes)%effectiveBufferSize != 0 {
chunks += 1
}
if chunks >= 1<<16 {
return nil, fmt.Errorf("data is too large")
}
dataChunks := make([]*DataChunk, chunks)
id, err := helpers.RandomID(CHUNK_ID_LENGTH)
if err != nil {
return nil, err
}
for i := 0; i < chunks; i++ {
end := (i + 1) * effectiveBufferSize
if end > len(bytes) {
end = len(bytes)
}
dataChunks[i] = MakeDataChunk(
id, uint16(chunks), uint16(i), bytes[i*effectiveBufferSize:end],
)
}
hyper.Log.Debugf("Split into %d entries", len(dataChunks))
return dataChunks, nil
}
func Reassemble(chunks []*DataChunk) (*hyper.DataEntry, error) {
e := &hyper.DataEntry{}
e.Type = hyper.NullType
e.Data = nil
e.ID = nil
data := make([]byte, 0, 100)
for i, chunk := range chunks {
if chunk.Index != uint16(i) {
return nil, fmt.Errorf("invalid chunk data")
}
data = append(data, chunk.Data...)
}
if len(data) < 1 {
return nil, fmt.Errorf("invalid entry")
}
return FromBytes(data)
}
type ByPosition struct {
Entries []*hyper.DataEntry
Positions map[string]int
}
func (b ByPosition) Len() int {
return len(b.Entries)
}
func (b ByPosition) Swap(i, j int) {
b.Entries[i], b.Entries[j] = b.Entries[j], b.Entries[i]
}
func (b ByPosition) Less(i, j int) bool {
posI := b.Positions[string(b.Entries[i].ID)]
posJ := b.Positions[string(b.Entries[j].ID)]
return posI < posJ
}
// Reassembles data entries from a list of data chunks. Returns any remaining
// data chunks (which might be used later).
func reassemble(chunks []*DataChunk) ([]*hyper.DataEntry, []*DataChunk, error) {
/*
We can assume that chunks occur in the right order, but they still can
be interleaved within each other.
*/
chunkPositions := make(map[string]int)
entryPositions := make(map[string]int)
dataEntries := make([]*hyper.DataEntry, 0, 10)
remainingChunks := make([]*DataChunk, 0, 10)
chunksByID := make(map[string][]*DataChunk)
for i, chunk := range chunks {
id := string(chunk.ID)
if _, ok := chunkPositions[id]; !ok {
chunkPositions[id] = i
}
existingChunks, ok := chunksByID[id]
if ok {
existingChunks = append(existingChunks, chunk)
} else {
existingChunks = make([]*DataChunk, 1, 10)
existingChunks[0] = chunk
}
chunksByID[id] = existingChunks
}
for id, idChunks := range chunksByID {
dataEntry, err := Reassemble(idChunks)
if err != nil {
return nil, nil, err
}
entryPositions[string(dataEntry.ID)] = chunkPositions[id]
if dataEntry.ID == nil {
remainingChunks = append(remainingChunks, idChunks...)
continue
}
dataEntries = append(dataEntries, dataEntry)
}
sortedByPosition := &ByPosition{
Entries: dataEntries,
Positions: entryPositions,
}
sort.Sort(sortedByPosition)
hyper.Log.Debugf("Found %d entries, %d remaining chunks", len(dataEntries), len(remainingChunks))
return sortedByPosition.Entries, remainingChunks, nil
}
// A file-based data store
type FileDatastore struct {
settings *FileSettings
mutex sync.Mutex
wfile *os.File
rfile *os.File
chunks []*DataChunk
}
type FileSettings struct {
Filename string `json:"filename"`
}
func MakeFile(settings interface{}) (hyper.Datastore, error) {
fileSettings := settings.(FileSettings)
return &FileDatastore{
settings: &fileSettings,
mutex: sync.Mutex{},
chunks: make([]*DataChunk, 0, 10),
}, nil
}
func (f *FileDatastore) Init() error {
f.mutex.Lock()
defer f.mutex.Unlock()
// we try to create the directory if it doesn't exist
dir := filepath.Dir(f.settings.Filename)
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return err
}
} else if err != nil {
return err
}
wfile, err := os.OpenFile(f.settings.Filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0700)
if err != nil {
return err
}
f.wfile = wfile
rfile, err := os.OpenFile(f.settings.Filename, os.O_CREATE|os.O_RDONLY, 0700)
if err != nil {
return err
}
f.rfile = rfile
return nil
}
func (f *FileDatastore) readChunks() ([]*DataChunk, error) {
chunks := make([]*DataChunk, 0, 10)
for {
chunk := &DataChunk{}
position, err := f.rfile.Seek(0, 1)
if err != nil {
return nil, err
}
if err := chunk.Read(f.rfile); err != nil {
if _, seekErr := f.rfile.Seek(position, 0); seekErr != nil {
hyper.Log.Errorf("Warning, two errors occured.")
hyper.Log.Error(seekErr)
}
return nil, err
}
if chunk.ID == nil {
break
}
chunks = append(chunks, chunk)
}
return chunks, nil
}
func (f *FileDatastore) Read() ([]*hyper.DataEntry, error) {
f.mutex.Lock()
defer f.mutex.Unlock()
chunks, err := f.readChunks()
if err != nil {
return nil, err
}
if f.chunks != nil {
chunks = append(f.chunks, chunks...)
}
dataEntries, remainingChunks, err := reassemble(chunks)
if err != nil {
return nil, err
}
f.chunks = remainingChunks
return dataEntries, nil
}
func (f *FileDatastore) Write(entry *hyper.DataEntry) error {
if chunks, err := Split(entry); err != nil {
return err
} else {
for _, chunk := range chunks {
if err := chunk.Write(f.wfile); err != nil {
return err
}
}
}
// we make sure the changes were all written to disk
return f.wfile.Sync()
}