-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
288 lines (230 loc) · 5.26 KB
/
utils.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
package kvndb
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"github.com/golang/snappy"
"io"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
)
func hexToBytes(s string) []byte {
b, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
return b
}
func generateSnapshotName(n uint) string {
return fmt.Sprintf("%06d.kvndb", n)
}
func generateChecksumName(n uint) string {
return fmt.Sprintf("%06d.sha256", n)
}
var (
re = regexp.MustCompile(`^[0-9]{6}\.kvndb$`)
)
func isSnapshotName(s string) bool {
return re.MatchString(s)
}
func parseSnapshotName(s string) uint {
ds := strings.Split(s, ".")[0]
d, err := strconv.Atoi(ds)
if err != nil {
panic(err)
}
return uint(d)
}
func getAllSnapshotIds(dir string) ([]uint, error) {
result := make([]uint, 0)
fileInfos, err := ioutil.ReadDir(dir)
if err != nil {
return nil, err
}
for _, fi := range fileInfos {
// ignore anything that is not regular file
if !fi.Mode().IsRegular() {
continue
}
// ignore any file that is not named like snapshot
if !isSnapshotName(fi.Name()) {
continue
}
result = append(result, parseSnapshotName(fi.Name()))
}
sort.Slice(result, func(i, j int) bool {
return result[i] < result[j]
})
return result, nil
}
func getSnapshotFDForReading(id uint, dir string) (*snappy.Reader, error) {
fd, err := os.Open(getSnapshotFilepath(dir, id))
if err != nil {
return nil, err
}
r := snappy.NewReader(fd)
return r, nil
}
func getSnapshotFDForWriting(id uint, dir string) (*snappy.Writer, error) {
fd, err := os.OpenFile(getSnapshotFilepath(dir, id), os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return nil, err
}
w := snappy.NewBufferedWriter(fd)
return w, nil
}
func getSnapshotFilepath(dir string, id uint) string {
return filepath.Clean(fmt.Sprintf("%s/%s", dir, generateSnapshotName(id)))
}
func getChecksumFilepath(dir string, id uint) string {
return filepath.Clean(fmt.Sprintf("%s/%s", dir, generateChecksumName(id)))
}
func getMaxSnapshotId(dir string) (uint, error) {
fileInfos, err := ioutil.ReadDir(dir)
if err != nil {
return 0, err
}
var maxId uint
for _, fi := range fileInfos {
// ignore anything that is not regular file
if !fi.Mode().IsRegular() {
continue
}
// ignore any file that is not named like snapshot
if !isSnapshotName(fi.Name()) {
continue
}
id := parseSnapshotName(fi.Name())
if id > maxId {
maxId = id
}
}
return maxId, nil
}
func packBytes(key, value []byte) []byte {
result := make([]byte, 0)
dataFrameLength := 8 + len(key) + len(value)
result = append(result, uint32ToBytes(uint32(dataFrameLength))...)
result = append(result, uint32ToBytes(uint32(len(key)))...)
result = append(result, key...)
result = append(result, uint32ToBytes(uint32(len(value)))...)
result = append(result, value...)
return result
}
var (
errReadToLittle = errors.New("io: read less than expected")
errDataSizeMismatch = errors.New("io: data size mismatch")
)
func readNext(fd *snappy.Reader) ([]byte, []byte, error) {
r := func(l uint32) ([]byte, error) {
buf := make([]byte, l)
read, err := io.ReadFull(fd, buf)
if err != nil {
return nil, err
}
if read != int(l) {
return nil, errReadToLittle
}
return buf, nil
}
dfLenBytes, err := r(4)
if err != nil {
return nil, nil, err
}
dfLen := bytesToUint32(dfLenBytes)
kLenBytes, err := r(4)
if err != nil {
return nil, nil, err
}
kLen := bytesToUint32(kLenBytes)
key, err := r(kLen)
if err != nil {
return nil, nil, err
}
vLenBytes, err := r(4)
if err != nil {
return nil, nil, err
}
vLen := bytesToUint32(vLenBytes)
value, err := r(vLen)
if err != nil {
return nil, nil, err
}
if dfLen != 8+kLen+vLen {
return nil, nil, errDataSizeMismatch
}
return key, value, nil
}
func bytesToUint32(data []byte) uint32 {
return binary.LittleEndian.Uint32(data)
}
func uint32ToBytes(data uint32) []byte {
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, data)
return bs
}
func cleanupSnapshotsUpTo(dir string, hist uint) error {
keep := hist + 1
ids, err := getAllSnapshotIds(dir)
if err != nil {
return err
}
if len(ids) <= int(keep) {
return nil
}
toDelete := ids[:(len(ids) - int(keep))]
for _, id := range toDelete {
err = os.Remove(getSnapshotFilepath(dir, id))
if err != nil {
return err
}
err = os.Remove(getChecksumFilepath(dir, id))
if err != nil {
return err
}
}
return nil
}
func getSnapshotChecksum(id uint, dir string) ([]byte, error) {
fd, err := getSnapshotFDForReading(id, dir)
if err != nil {
return nil, err
}
hasher := sha256.New()
if _, err := io.Copy(hasher, fd); err != nil {
return nil, err
}
return hasher.Sum(nil), nil
}
func writeSnapshotChecksum(id uint, dir string) error {
hash, err := getSnapshotChecksum(id, dir)
if err != nil {
return err
}
return ioutil.WriteFile(getChecksumFilepath(dir, id), hash, 0600)
}
func verifySnapshotChecksum(id uint, dir string) error {
// read stored checksum
storedHash, err := ioutil.ReadFile(getChecksumFilepath(dir, id))
if err != nil {
return err
}
// calculate file checksum
hash, err := getSnapshotChecksum(id, dir)
if err != nil {
return err
}
// compare checksums
if !bytes.Equal(storedHash, hash) {
return ErrBadSnapshot
}
return nil
}