forked from attic-labs/noms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_table_persister.go
94 lines (78 loc) · 2.46 KB
/
file_table_persister.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
// Copyright 2016 Attic Labs, Inc. All rights reserved.
// Licensed under the Apache License, version 2.0:
// http://www.apache.org/licenses/LICENSE-2.0
package nbs
import (
"bytes"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/attic-labs/noms/go/d"
)
const tempTablePrefix = "nbs_table_"
func newFSTablePersister(dir string, fc *fdCache, indexCache *indexCache) tablePersister {
d.PanicIfTrue(fc == nil)
return &fsTablePersister{dir, fc, indexCache}
}
type fsTablePersister struct {
dir string
fc *fdCache
indexCache *indexCache
}
func (ftp *fsTablePersister) Open(name addr, chunkCount uint32, stats *Stats) chunkSource {
return newMmapTableReader(ftp.dir, name, chunkCount, ftp.indexCache, ftp.fc)
}
func (ftp *fsTablePersister) Persist(mt *memTable, haver chunkReader, stats *Stats) chunkSource {
name, data, chunkCount := mt.write(haver, stats)
return ftp.persistTable(name, data, chunkCount, stats)
}
func (ftp *fsTablePersister) persistTable(name addr, data []byte, chunkCount uint32, stats *Stats) chunkSource {
if chunkCount == 0 {
return emptyChunkSource{}
}
tempName := func() string {
temp, err := ioutil.TempFile(ftp.dir, tempTablePrefix)
d.PanicIfError(err)
defer checkClose(temp)
io.Copy(temp, bytes.NewReader(data))
index := parseTableIndex(data)
if ftp.indexCache != nil {
ftp.indexCache.lockEntry(name)
defer ftp.indexCache.unlockEntry(name)
ftp.indexCache.put(name, index)
}
return temp.Name()
}()
err := os.Rename(tempName, filepath.Join(ftp.dir, name.String()))
d.PanicIfError(err)
return ftp.Open(name, chunkCount, stats)
}
func (ftp *fsTablePersister) ConjoinAll(sources chunkSources, stats *Stats) chunkSource {
plan := planConjoin(sources, stats)
if plan.chunkCount == 0 {
return emptyChunkSource{}
}
name := nameFromSuffixes(plan.suffixes())
tempName := func() string {
temp, err := ioutil.TempFile(ftp.dir, tempTablePrefix)
d.PanicIfError(err)
defer checkClose(temp)
for _, sws := range plan.sources {
r := sws.source.reader()
n, err := io.CopyN(temp, r, int64(sws.dataLen))
d.PanicIfError(err)
d.PanicIfFalse(uint64(n) == sws.dataLen)
}
_, err = temp.Write(plan.mergedIndex)
d.PanicIfError(err)
index := parseTableIndex(plan.mergedIndex)
if ftp.indexCache != nil {
ftp.indexCache.put(name, index)
}
return temp.Name()
}()
err := os.Rename(tempName, filepath.Join(ftp.dir, name.String()))
d.PanicIfError(err)
return ftp.Open(name, plan.chunkCount, stats)
}