forked from lni/dragonboat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snapshotio.go
312 lines (287 loc) · 7.69 KB
/
snapshotio.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
// Copyright 2017-2019 Lei Ni (nilei81@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rsm
import (
"bytes"
"encoding/binary"
"hash"
"hash/crc32"
"io"
"os"
"path/filepath"
"time"
"github.com/lni/dragonboat/internal/settings"
"github.com/lni/dragonboat/internal/utils/fileutil"
pb "github.com/lni/dragonboat/raftpb"
)
const (
// current snapshot binary format version.
currentSnapshotVersion = 1
// SnapshotHeaderSize is the size of snapshot in number of bytes.
SnapshotHeaderSize = settings.SnapshotHeaderSize
// which checksum type to use.
// CRC32IEEE and google's highway hash are supported
defaultChecksumType = pb.CRC32IEEE
)
func newCRC32Hash() hash.Hash {
return crc32.NewIEEE()
}
func getChecksum(t pb.ChecksumType) hash.Hash {
if t == pb.CRC32IEEE {
return newCRC32Hash()
} else if t == pb.HIGHWAY {
panic("highway hash not supported yet")
} else {
plog.Panicf("not supported checksum type %d", t)
}
panic("not suppose to reach here")
}
func getChecksumType() pb.ChecksumType {
return defaultChecksumType
}
func getDefaultChecksum() hash.Hash {
return getChecksum(getChecksumType())
}
// SnapshotWriter is an io.Writer used to write snapshot file.
type SnapshotWriter struct {
h hash.Hash
file *os.File
fp string
}
// NewSnapshotWriter creates a new snapshot writer instance.
func NewSnapshotWriter(fp string) (*SnapshotWriter, error) {
f, err := os.OpenFile(fp,
os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileutil.DefaultFileMode)
if err != nil {
return nil, err
}
dummy := make([]byte, SnapshotHeaderSize)
for i := uint64(0); i < SnapshotHeaderSize; i++ {
dummy[i] = 0
}
if _, err := f.Write(dummy); err != nil {
return nil, err
}
sw := &SnapshotWriter{
h: getDefaultChecksum(),
file: f,
fp: fp,
}
return sw, nil
}
// Close closes the snapshot writer instance.
func (sw *SnapshotWriter) Close() error {
if err := sw.file.Sync(); err != nil {
return err
}
if err := fileutil.SyncDir(filepath.Dir(sw.fp)); err != nil {
return err
}
return sw.file.Close()
}
// Write writes the specified data to the snapshot.
func (sw *SnapshotWriter) Write(data []byte) (int, error) {
if _, err := sw.h.Write(data); err != nil {
panic(err)
}
return sw.file.Write(data)
}
// SaveHeader saves the snapshot header to the snapshot.
func (sw *SnapshotWriter) SaveHeader(smsz uint64, sz uint64) error {
sh := pb.SnapshotHeader{
SessionSize: smsz,
DataStoreSize: sz,
UnreliableTime: uint64(time.Now().UnixNano()),
PayloadChecksum: sw.h.Sum(nil),
ChecksumType: getChecksumType(),
Version: currentSnapshotVersion,
}
data, err := sh.Marshal()
if err != nil {
panic(err)
}
headerHash := getDefaultChecksum()
if _, err := headerHash.Write(data); err != nil {
panic(err)
}
headerChecksum := headerHash.Sum(nil)
sh.HeaderChecksum = headerChecksum
data, err = sh.Marshal()
if err != nil {
panic(err)
}
if uint64(len(data)) > SnapshotHeaderSize-8 {
panic("snapshot header is too large")
}
if _, err = sw.file.Seek(0, 0); err != nil {
panic(err)
}
lenbuf := make([]byte, 8)
binary.LittleEndian.PutUint64(lenbuf, uint64(len(data)))
if _, err := sw.file.Write(lenbuf); err != nil {
return err
}
if _, err := sw.file.Write(data); err != nil {
return err
}
return nil
}
// SnapshotReader is an io.Reader for reading from snapshot files.
type SnapshotReader struct {
h hash.Hash
file *os.File
}
// NewSnapshotReader creates a new snapshot reader instance.
func NewSnapshotReader(fp string) (*SnapshotReader, error) {
f, err := os.OpenFile(fp, os.O_RDONLY, 0)
if err != nil {
return nil, err
}
return &SnapshotReader{file: f}, nil
}
// Close closes the snapshot reader instance.
func (sr *SnapshotReader) Close() error {
return sr.file.Close()
}
// GetHeader returns the snapshot header instance.
func (sr *SnapshotReader) GetHeader() (pb.SnapshotHeader, error) {
empty := pb.SnapshotHeader{}
lenbuf := make([]byte, 8)
n, err := io.ReadFull(sr.file, lenbuf)
if err != nil {
return empty, err
}
if n != len(lenbuf) {
return empty, io.ErrUnexpectedEOF
}
sz := binary.LittleEndian.Uint64(lenbuf)
if sz > SnapshotHeaderSize-8 {
panic("invalid snapshot header size")
}
data := make([]byte, sz)
n, err = io.ReadFull(sr.file, data)
if err != nil {
return empty, err
}
if n != len(data) {
return empty, io.ErrUnexpectedEOF
}
r := pb.SnapshotHeader{}
if err := r.Unmarshal(data); err != nil {
panic(err)
}
sr.h = getChecksum(r.ChecksumType)
offset, err := sr.file.Seek(int64(SnapshotHeaderSize), 0)
if err != nil {
return empty, err
}
if uint64(offset) != SnapshotHeaderSize {
return empty, io.ErrUnexpectedEOF
}
return r, nil
}
// Read reads up to len(data) bytes from the snapshot file.
func (sr *SnapshotReader) Read(data []byte) (int, error) {
n, err := sr.file.Read(data)
if err != nil {
return n, err
}
if _, err = sr.h.Write(data[:n]); err != nil {
panic(err)
}
return n, nil
}
// ValidatePayload validates whether the snapshot content matches the checksum
// recorded in the header.
func (sr *SnapshotReader) ValidatePayload(header pb.SnapshotHeader) {
checksum := sr.h.Sum(nil)
if !bytes.Equal(checksum, header.PayloadChecksum) {
panic("corrupted payload")
}
}
// ValidateHeader validates whether the header matches the header checksum
// recorded in the header.
func (sr *SnapshotReader) ValidateHeader(header pb.SnapshotHeader) {
checksum := header.HeaderChecksum
header.HeaderChecksum = nil
data, err := header.Marshal()
if err != nil {
panic(err)
}
headerHash := getChecksum(header.ChecksumType)
if _, err := headerHash.Write(data); err != nil {
panic(err)
}
headerChecksum := headerHash.Sum(nil)
if !bytes.Equal(headerChecksum, checksum) {
panic("corrupted snapshot header")
}
if header.Version != currentSnapshotVersion {
panic("unknown version")
}
}
// SnapshotValidator is the validator used to check incoming snapshot chunks.
type SnapshotValidator struct {
header pb.SnapshotHeader
h hash.Hash
}
// NewSnapshotValidator creates and returns a new SnapshotValidator instance.
func NewSnapshotValidator() *SnapshotValidator {
return &SnapshotValidator{}
}
func (v *SnapshotValidator) getHeader(data []byte) bool {
if uint64(len(data)) < SnapshotHeaderSize {
panic("first chunk is too small")
}
if v.h != nil {
panic("getHeader invoked twice")
}
sz := binary.LittleEndian.Uint64(data)
if sz > SnapshotHeaderSize-8 {
return false
}
headerData := data[8 : 8+sz]
r := pb.SnapshotHeader{}
if err := r.Unmarshal(headerData); err != nil {
return false
}
v.h = getChecksum(r.ChecksumType)
v.header = r
return true
}
// AddChunk adds a new snapshot chunk to the validator.
func (v *SnapshotValidator) AddChunk(data []byte, chunkID uint64) bool {
var chunkData []byte
if chunkID == 0 {
if !v.getHeader(data) {
return false
}
chunkData = data[SnapshotHeaderSize:]
} else {
chunkData = data
}
if v.h == nil {
panic("never got the first chunk")
}
n, err := v.h.Write(chunkData)
if err != nil {
return false
}
return n == len(chunkData)
}
// Validate validates the added chunks and return a boolean flag indicating
// whether the snapshot chunks are valid.
func (v *SnapshotValidator) Validate() bool {
return bytes.Equal(v.h.Sum(nil), v.header.PayloadChecksum)
}