forked from akrylysov/pogreb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
397 lines (352 loc) · 8.49 KB
/
db.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
package pogreb
import (
"bytes"
"context"
"math"
"os"
"sync"
"time"
"github.com/akrylysov/pogreb/fs"
"github.com/akrylysov/pogreb/internal/errors"
"github.com/akrylysov/pogreb/internal/hash"
)
const (
// MaxKeyLength is the maximum size of a key in bytes.
MaxKeyLength = math.MaxUint16
// MaxValueLength is the maximum size of a value in bytes.
MaxValueLength = 512 << 20 // 512 MiB
// MaxKeys is the maximum numbers of keys in the DB.
MaxKeys = math.MaxUint32
metaExt = ".pmt"
dbMetaName = "db" + metaExt
)
// DB represents the key-value storage.
// All DB methods are safe for concurrent use by multiple goroutines.
type DB struct {
mu sync.RWMutex // Allows multiple database readers or a single writer.
opts *Options
index *index
datalog *datalog
lock fs.LockFile // Prevents opening multiple instances of the same database.
hashSeed uint32
metrics *Metrics
syncWrites bool
cancelBgWorker context.CancelFunc
closeWg sync.WaitGroup
compactionRunning int32 // Prevents running compactions concurrently.
}
type dbMeta struct {
HashSeed uint32
}
// Open opens or creates a new DB.
// The DB must be closed after use, by calling Close method.
func Open(path string, opts *Options) (*DB, error) {
opts = opts.copyWithDefaults(path)
if err := os.MkdirAll(path, 0755); err != nil {
return nil, err
}
// Try to acquire a file lock.
lock, acquiredExistingLock, err := createLockFile(opts)
if err != nil {
if err == os.ErrExist {
err = errLocked
}
return nil, errors.Wrap(err, "creating lock file")
}
if acquiredExistingLock {
// Lock file already existed, but the process managed to acquire it.
// It means the database wasn't closed properly.
// Start recovery process.
if err := backupNonsegmentFiles(opts.FileSystem); err != nil {
return nil, err
}
}
index, err := openIndex(opts)
if err != nil {
return nil, errors.Wrap(err, "opening index")
}
datalog, err := openDatalog(opts)
if err != nil {
return nil, errors.Wrap(err, "opening datalog")
}
db := &DB{
opts: opts,
index: index,
datalog: datalog,
lock: lock,
metrics: &Metrics{},
syncWrites: opts.BackgroundSyncInterval == -1,
}
if index.count() == 0 {
// The index is empty, make a new hash seed.
seed, err := hash.RandSeed()
if err != nil {
return nil, err
}
db.hashSeed = seed
} else {
if err := db.readMeta(); err != nil {
return nil, errors.Wrap(err, "reading db meta")
}
}
if acquiredExistingLock {
if err := db.recover(); err != nil {
return nil, errors.Wrap(err, "recovering")
}
}
if db.opts.BackgroundSyncInterval > 0 || db.opts.BackgroundCompactionInterval > 0 {
db.startBackgroundWorker()
}
return db, nil
}
func cloneBytes(src []byte) []byte {
dst := make([]byte, len(src))
copy(dst, src)
return dst
}
func (db *DB) writeMeta() error {
m := dbMeta{
HashSeed: db.hashSeed,
}
return writeGobFile(db.opts.FileSystem, dbMetaName, m)
}
func (db *DB) readMeta() error {
m := dbMeta{}
if err := readGobFile(db.opts.FileSystem, dbMetaName, &m); err != nil {
return err
}
db.hashSeed = m.HashSeed
return nil
}
func (db *DB) hash(data []byte) uint32 {
return hash.Sum32WithSeed(data, db.hashSeed)
}
// newNullableTicker is a wrapper around time.NewTicker that allows creating a nil ticker.
// A nil ticker never ticks.
func newNullableTicker(d time.Duration) (<-chan time.Time, func()) {
if d > 0 {
t := time.NewTicker(d)
return t.C, t.Stop
}
return nil, func() {}
}
func (db *DB) startBackgroundWorker() {
ctx, cancel := context.WithCancel(context.Background())
db.cancelBgWorker = cancel
db.closeWg.Add(1)
go func() {
defer db.closeWg.Done()
syncC, syncStop := newNullableTicker(db.opts.BackgroundSyncInterval)
defer syncStop()
compactC, compactStop := newNullableTicker(db.opts.BackgroundCompactionInterval)
defer compactStop()
for {
select {
case <-ctx.Done():
return
case <-syncC:
if err := db.Sync(); err != nil {
logger.Printf("error synchronizing database: %v", err)
}
case <-compactC:
if cr, err := db.Compact(); err != nil {
logger.Printf("error compacting database: %v", err)
} else if cr.CompactedSegments > 0 {
logger.Printf("compacted database: %+v", cr)
}
}
}
}()
}
// Get returns the value for the given key stored in the DB or nil if the key doesn't exist.
func (db *DB) Get(key []byte) ([]byte, error) {
h := db.hash(key)
db.metrics.Gets.Add(1)
db.mu.RLock()
defer db.mu.RUnlock()
var retValue []byte
err := db.index.get(h, func(sl slot) (bool, error) {
if uint16(len(key)) != sl.keySize {
return false, nil
}
slKey, value, err := db.datalog.readKeyValue(sl)
if err != nil {
return true, err
}
if bytes.Equal(key, slKey) {
retValue = cloneBytes(value)
return true, nil
}
db.metrics.HashCollisions.Add(1)
return false, nil
})
if err != nil {
return nil, err
}
return retValue, nil
}
// Has returns true if the DB contains the given key.
func (db *DB) Has(key []byte) (bool, error) {
h := db.hash(key)
db.metrics.Gets.Add(1)
found := false
db.mu.RLock()
defer db.mu.RUnlock()
err := db.index.get(h, func(sl slot) (bool, error) {
if uint16(len(key)) != sl.keySize {
return false, nil
}
slKey, err := db.datalog.readKey(sl)
if err != nil {
return true, err
}
if bytes.Equal(key, slKey) {
found = true
return true, nil
}
return false, nil
})
if err != nil {
return false, err
}
return found, nil
}
func (db *DB) put(sl slot, key []byte) error {
return db.index.put(sl, func(cursl slot) (bool, error) {
if uint16(len(key)) != cursl.keySize {
return false, nil
}
slKey, err := db.datalog.readKey(cursl)
if err != nil {
return true, err
}
if bytes.Equal(key, slKey) {
db.datalog.trackDel(cursl) // Overwriting existing key.
return true, nil
}
return false, nil
})
}
// Put sets the value for the given key. It updates the value for the existing key.
func (db *DB) Put(key []byte, value []byte) error {
if len(key) > MaxKeyLength {
return errKeyTooLarge
}
if len(value) > MaxValueLength {
return errValueTooLarge
}
h := db.hash(key)
db.metrics.Puts.Add(1)
db.mu.Lock()
defer db.mu.Unlock()
segID, offset, err := db.datalog.put(key, value)
if err != nil {
return err
}
sl := slot{
hash: h,
segmentID: segID,
keySize: uint16(len(key)),
valueSize: uint32(len(value)),
offset: offset,
}
if err := db.put(sl, key); err != nil {
return err
}
if db.syncWrites {
return db.sync()
}
return nil
}
func (db *DB) del(h uint32, key []byte, writeWAL bool) error {
err := db.index.delete(h, func(sl slot) (b bool, e error) {
if uint16(len(key)) != sl.keySize {
return false, nil
}
slKey, err := db.datalog.readKey(sl)
if err != nil {
return true, err
}
if bytes.Equal(key, slKey) {
db.datalog.trackDel(sl)
var err error
if writeWAL {
err = db.datalog.del(key)
}
return true, err
}
return false, nil
})
return err
}
// Delete deletes the given key from the DB.
func (db *DB) Delete(key []byte) error {
h := db.hash(key)
db.metrics.Dels.Add(1)
db.mu.Lock()
defer db.mu.Unlock()
if err := db.del(h, key, true); err != nil {
return err
}
if db.syncWrites {
return db.sync()
}
return nil
}
// Close closes the DB.
func (db *DB) Close() error {
if db.cancelBgWorker != nil {
db.cancelBgWorker()
}
db.closeWg.Wait()
db.mu.Lock()
defer db.mu.Unlock()
if err := db.writeMeta(); err != nil {
return err
}
if err := db.datalog.close(); err != nil {
return err
}
if err := db.index.close(); err != nil {
return err
}
if err := db.lock.Unlock(); err != nil {
return err
}
return nil
}
func (db *DB) sync() error {
return db.datalog.sync()
}
// Items returns a new ItemIterator.
func (db *DB) Items() *ItemIterator {
return &ItemIterator{db: db}
}
// Sync commits the contents of the database to the backing FileSystem.
func (db *DB) Sync() error {
db.mu.Lock()
defer db.mu.Unlock()
return db.sync()
}
// Count returns the number of keys in the DB.
func (db *DB) Count() uint32 {
db.mu.RLock()
defer db.mu.RUnlock()
return db.index.count()
}
// Metrics returns the DB metrics.
func (db *DB) Metrics() *Metrics {
return db.metrics
}
// FileSize returns the total size of the disk storage used by the DB.
func (db *DB) FileSize() (int64, error) {
var size int64
files, err := db.opts.FileSystem.ReadDir(".")
if err != nil {
return 0, err
}
for _, file := range files {
size += file.Size()
}
return size, nil
}