/
segment_bloom_filters.go
350 lines (285 loc) · 8.74 KB
/
segment_bloom_filters.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
// _ _
// __ _____ __ ___ ___ __ _| |_ ___
// \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
// \ V V / __/ (_| |\ V /| | (_| | || __/
// \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
//
// Copyright © 2016 - 2023 Weaviate B.V. All rights reserved.
//
// CONTACT: hello@weaviate.io
//
package lsmkv
import (
"bytes"
"encoding/binary"
"fmt"
"hash/crc32"
"os"
"path/filepath"
"strings"
"time"
"github.com/willf/bloom"
)
func (s *segment) bloomFilterPath() string {
extless := strings.TrimSuffix(s.path, filepath.Ext(s.path))
return fmt.Sprintf("%s.bloom", extless)
}
func (s *segment) bloomFilterSecondaryPath(pos int) string {
extless := strings.TrimSuffix(s.path, filepath.Ext(s.path))
return fmt.Sprintf("%s.secondary.%d.bloom", extless, pos)
}
func (s *segment) initBloomFilters() error {
if err := s.initBloomFilter(); err != nil {
return fmt.Errorf("init bloom filter for primary index: %w", err)
}
if s.secondaryIndexCount > 0 {
s.secondaryBloomFilters = make([]*bloom.BloomFilter, s.secondaryIndexCount)
for i := range s.secondaryBloomFilters {
if err := s.initSecondaryBloomFilter(i); err != nil {
return fmt.Errorf("init bloom filter for secondary index at %d: %w", i, err)
}
}
}
return nil
}
func (s *segment) initBloomFilter() error {
path := s.bloomFilterPath()
ok, err := fileExists(path)
if err != nil {
return err
}
if ok {
err = s.loadBloomFilterFromDisk()
if err == nil {
return nil
}
if err != ErrInvalidChecksum {
// not a recoverable error
return err
}
// now continue re-calculating
}
before := time.Now()
if err := s.computeAndStoreBloomFilter(path); err != nil {
return err
}
took := time.Since(before)
s.logger.WithField("action", "lsm_init_disk_segment_build_bloom_filter_primary").
WithField("path", s.path).
WithField("took", took).
Debugf("building bloom filter took %s\n", took)
return nil
}
func (s *segment) computeAndStoreBloomFilter(path string) error {
keys, err := s.index.AllKeys()
if err != nil {
return err
}
s.bloomFilter = bloom.NewWithEstimates(uint(len(keys)), 0.001)
for _, key := range keys {
s.bloomFilter.Add(key)
}
if err := s.storeBloomFilterOnDisk(path); err != nil {
return fmt.Errorf("store bloom filter on disk: %w", err)
}
return nil
}
func (s *segment) precomputeBloomFilters() ([]string, error) {
out := []string{}
if err := s.precomputeBloomFilter(); err != nil {
return nil, fmt.Errorf("precompute bloom filter for primary index: %w", err)
}
out = append(out, fmt.Sprintf("%s.tmp", s.bloomFilterPath()))
if s.secondaryIndexCount > 0 {
s.secondaryBloomFilters = make([]*bloom.BloomFilter, s.secondaryIndexCount)
for i := range s.secondaryBloomFilters {
if err := s.precomputeSecondaryBloomFilter(i); err != nil {
return nil, fmt.Errorf("precompute bloom filter for secondary index at %d: %w", i, err)
}
out = append(out, fmt.Sprintf("%s.tmp", s.bloomFilterSecondaryPath(i)))
}
}
return out, nil
}
func (s *segment) precomputeBloomFilter() error {
before := time.Now()
path := fmt.Sprintf("%s.tmp", s.bloomFilterPath())
ok, err := fileExists(path)
if err != nil {
return err
}
if ok {
return fmt.Errorf("a bloom filter already exists with path %s", path)
}
if err := s.computeAndStoreBloomFilter(path); err != nil {
return err
}
took := time.Since(before)
s.logger.WithField("action", "lsm_precompute_disk_segment_build_bloom_filter_primary").
WithField("path", s.path).
WithField("took", took).
Debugf("building bloom filter took %s\n", took)
return nil
}
func (s *segment) storeBloomFilterOnDisk(path string) error {
buf := new(bytes.Buffer)
_, err := s.bloomFilter.WriteTo(buf)
if err != nil {
return fmt.Errorf("write bloom filter: %w", err)
}
return writeWithChecksum(buf.Bytes(), path)
}
func (s *segment) loadBloomFilterFromDisk() error {
data, err := loadWithChecksum(s.bloomFilterPath(), -1)
if err != nil {
return err
}
s.bloomFilter = new(bloom.BloomFilter)
_, err = s.bloomFilter.ReadFrom(bytes.NewReader(data))
if err != nil {
return fmt.Errorf("read bloom filter from disk: %w", err)
}
return nil
}
func (s *segment) initSecondaryBloomFilter(pos int) error {
before := time.Now()
path := s.bloomFilterSecondaryPath(pos)
ok, err := fileExists(path)
if err != nil {
return err
}
if ok {
err = s.loadBloomFilterSecondaryFromDisk(pos)
if err == nil {
return nil
}
if err != ErrInvalidChecksum {
// not a recoverable error
return err
}
// now continue re-calculating
}
if err := s.computeAndStoreSecondaryBloomFilter(path, pos); err != nil {
return err
}
took := time.Since(before)
s.logger.WithField("action", "lsm_init_disk_segment_build_bloom_filter_secondary").
WithField("secondary_index_position", pos).
WithField("path", s.path).
WithField("took", took).
Debugf("building bloom filter took %s\n", took)
return nil
}
func (s *segment) computeAndStoreSecondaryBloomFilter(path string, pos int) error {
keys, err := s.secondaryIndices[pos].AllKeys()
if err != nil {
return err
}
s.secondaryBloomFilters[pos] = bloom.NewWithEstimates(uint(len(keys)), 0.001)
for _, key := range keys {
s.secondaryBloomFilters[pos].Add(key)
}
if err := s.storeBloomFilterSecondaryOnDisk(path, pos); err != nil {
return fmt.Errorf("store secondary bloom filter on disk: %w", err)
}
return nil
}
func (s *segment) precomputeSecondaryBloomFilter(pos int) error {
before := time.Now()
path := fmt.Sprintf("%s.tmp", s.bloomFilterSecondaryPath(pos))
ok, err := fileExists(path)
if err != nil {
return err
}
if ok {
return fmt.Errorf("a secondary bloom filter already exists with path %s", path)
}
if err := s.computeAndStoreSecondaryBloomFilter(path, pos); err != nil {
return err
}
took := time.Since(before)
s.logger.WithField("action", "lsm_precompute_disk_segment_build_bloom_filter_secondary").
WithField("secondary_index_position", pos).
WithField("path", s.path).
WithField("took", took).
Debugf("building bloom filter took %s\n", took)
return nil
}
func (s *segment) storeBloomFilterSecondaryOnDisk(path string, pos int) error {
buf := new(bytes.Buffer)
_, err := s.secondaryBloomFilters[pos].WriteTo(buf)
if err != nil {
return fmt.Errorf("write bloom filter: %w", err)
}
return writeWithChecksum(buf.Bytes(), path)
}
func (s *segment) loadBloomFilterSecondaryFromDisk(pos int) error {
data, err := loadWithChecksum(s.bloomFilterSecondaryPath(pos), -1)
if err != nil {
return err
}
s.secondaryBloomFilters[pos] = new(bloom.BloomFilter)
_, err = s.secondaryBloomFilters[pos].ReadFrom(bytes.NewReader(data))
if err != nil {
return fmt.Errorf("read bloom filter from disk: %w", err)
}
return nil
}
func writeWithChecksum(data []byte, path string) error {
chksm := crc32.ChecksumIEEE(data)
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("open file for writing: %w", err)
}
if err := binary.Write(f, binary.LittleEndian, chksm); err != nil {
// ignoring f.Close() error here, as we don't care about whether the file
// was flushed, the call is mainly intended to prevent a file descriptor
// leak. We still want to return the original error below.
f.Close()
return fmt.Errorf("write checkusm to file: %w", err)
}
if _, err := f.Write(data); err != nil {
// ignoring f.Close() error here, as we don't care about whether the file
// was flushed, the call is mainly intended to prevent a file descriptor
// leak. We still want to return the original error below.
f.Close()
return fmt.Errorf("write bloom filter to disk: %w", err)
}
if err := f.Close(); err != nil {
return fmt.Errorf("close bloom filter file: %w", err)
}
return nil
}
// use negative length check to indicate that no length check should be
// performed
func loadWithChecksum(path string, lengthCheck int) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("open file for reading: %w", err)
}
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(f); err != nil {
// ignoring f.Close() error here, as we don't care about whether the file
// was flushed, the call is mainly intended to prevent a file descriptor
// leak. We still want to return the original error below.
f.Close()
return nil, fmt.Errorf("read bloom filter data from file: %w", err)
}
if err := f.Close(); err != nil {
return nil, fmt.Errorf("close bloom filter file: %w", err)
}
data := buf.Bytes()
if lengthCheck > 0 && len(data) != lengthCheck {
return nil, ErrInvalidChecksum
}
if len(data) < 4 {
// the file does not even contain the full checksum, we must consider it corrupt
return nil, ErrInvalidChecksum
}
chcksm := binary.LittleEndian.Uint32(data[:4])
actual := crc32.ChecksumIEEE(data[4:])
if chcksm != actual {
return nil, ErrInvalidChecksum
}
return data[4:], nil
}