/
leveldb.go
297 lines (239 loc) · 5.91 KB
/
leveldb.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
package leveldb
import (
"context"
"fmt"
"os"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/Dharitri-org/drtg-core/core"
logger "github.com/Dharitri-org/drtg-logger"
"github.com/Dharitri-org/drtg-storage/common"
"github.com/Dharitri-org/drtg-storage/types"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
)
var _ types.Persister = (*DB)(nil)
// read + write + execute for owner only
const rwxOwner = 0700
const mkdirAllFunction = "mkdirAll"
const openLevelDBFunction = "openLevelDB"
var log = logger.GetOrCreate("storage/leveldb")
// DB holds a pointer to the leveldb database and the path to where it is stored.
type DB struct {
*baseLevelDb
maxBatchSize int
batchDelaySeconds int
sizeBatch int
batch types.Batcher
mutBatch sync.RWMutex
cancel context.CancelFunc
}
// NewDB is a constructor for the leveldb persister
// It creates the files in the location given as parameter
func NewDB(path string, batchDelaySeconds int, maxBatchSize int, maxOpenFiles int) (s *DB, err error) {
constructorName := "NewDB"
sw := core.NewStopWatch()
sw.Start(constructorName)
sw.Start(mkdirAllFunction)
err = os.MkdirAll(path, rwxOwner)
if err != nil {
return nil, err
}
sw.Stop(mkdirAllFunction)
if maxOpenFiles < 1 {
return nil, common.ErrInvalidNumOpenFiles
}
options := &opt.Options{
// disable internal cache
BlockCacheCapacity: -1,
OpenFilesCacheCapacity: maxOpenFiles,
}
sw.Start(openLevelDBFunction)
db, err := openLevelDB(path, options)
if err != nil {
return nil, fmt.Errorf("%w for path %s", err, path)
}
sw.Stop(openLevelDBFunction)
bldb := &baseLevelDb{
db: db,
path: path,
}
ctx, cancel := context.WithCancel(context.Background())
dbStore := &DB{
baseLevelDb: bldb,
maxBatchSize: maxBatchSize,
batchDelaySeconds: batchDelaySeconds,
sizeBatch: 0,
cancel: cancel,
}
dbStore.batch = dbStore.createBatch()
go dbStore.batchTimeoutHandle(ctx)
runtime.SetFinalizer(dbStore, func(db *DB) {
_ = db.Close()
})
crtCounter := atomic.AddUint32(&loggingDBCounter, 1)
sw.Stop(constructorName)
logArguments := []interface{}{"path", path, "created pointer", fmt.Sprintf("%p", bldb.db), "global db counter", crtCounter}
logArguments = append(logArguments, sw.GetMeasurements()...)
log.Debug("opened level db persister", logArguments...)
return dbStore, nil
}
func (s *DB) batchTimeoutHandle(ctx context.Context) {
interval := time.Duration(s.batchDelaySeconds) * time.Second
timer := time.NewTimer(interval)
defer timer.Stop()
for {
timer.Reset(interval)
select {
case <-timer.C:
s.mutBatch.Lock()
err := s.putBatch(s.batch)
if err != nil {
log.Warn("leveldb putBatch", "error", err.Error())
s.mutBatch.Unlock()
continue
}
s.batch.Reset()
s.sizeBatch = 0
s.mutBatch.Unlock()
case <-ctx.Done():
log.Debug("closing the timed batch handler", "path", s.path)
return
}
}
}
func (s *DB) updateBatchWithIncrement() error {
s.mutBatch.Lock()
defer s.mutBatch.Unlock()
s.sizeBatch++
if s.sizeBatch < s.maxBatchSize {
return nil
}
err := s.putBatch(s.batch)
if err != nil {
log.Warn("leveldb putBatch", "error", err.Error())
return err
}
s.batch.Reset()
s.sizeBatch = 0
return nil
}
// Put adds the value to the (key, val) storage medium
func (s *DB) Put(key, val []byte) error {
s.mutBatch.RLock()
err := s.batch.Put(key, val)
s.mutBatch.RUnlock()
if err != nil {
return err
}
return s.updateBatchWithIncrement()
}
// Get returns the value associated to the key
func (s *DB) Get(key []byte) ([]byte, error) {
db := s.getDbPointer()
if db == nil {
return nil, common.ErrDBIsClosed
}
if s.batch.IsRemoved(key) {
return nil, common.ErrKeyNotFound
}
data := s.batch.Get(key)
if data != nil {
return data, nil
}
data, err := db.Get(key, nil)
if err == leveldb.ErrNotFound {
return nil, common.ErrKeyNotFound
}
if err != nil {
return nil, err
}
return data, nil
}
// Has returns nil if the given key is present in the persistence medium
func (s *DB) Has(key []byte) error {
db := s.getDbPointer()
if db == nil {
return common.ErrDBIsClosed
}
if s.batch.IsRemoved(key) {
return common.ErrKeyNotFound
}
data := s.batch.Get(key)
if data != nil {
return nil
}
has, err := db.Has(key, nil)
if err != nil {
return err
}
if has {
return nil
}
return common.ErrKeyNotFound
}
// CreateBatch returns a batcher to be used for batch writing data to the database
func (s *DB) createBatch() types.Batcher {
return NewBatch()
}
// putBatch writes the Batch data into the database
func (s *DB) putBatch(b types.Batcher) error {
dbBatch, ok := b.(*batch)
if !ok {
return common.ErrInvalidBatch
}
wopt := &opt.WriteOptions{
Sync: true,
}
db := s.getDbPointer()
if db == nil {
return common.ErrDBIsClosed
}
return db.Write(dbBatch.batch, wopt)
}
// Close closes the files/resources associated to the storage medium
func (s *DB) Close() error {
s.mutBatch.Lock()
_ = s.putBatch(s.batch)
s.sizeBatch = 0
s.mutBatch.Unlock()
s.cancel()
db := s.makeDbPointerNilReturningLast()
if db != nil {
return db.Close()
}
return nil
}
// Remove removes the data associated to the given key
func (s *DB) Remove(key []byte) error {
s.mutBatch.Lock()
_ = s.batch.Delete(key)
s.mutBatch.Unlock()
return s.updateBatchWithIncrement()
}
// Destroy removes the storage medium stored data
func (s *DB) Destroy() error {
s.mutBatch.Lock()
s.batch.Reset()
s.sizeBatch = 0
s.mutBatch.Unlock()
s.cancel()
db := s.makeDbPointerNilReturningLast()
if db != nil {
err := db.Close()
if err != nil {
return err
}
}
return os.RemoveAll(s.path)
}
// DestroyClosed removes the already closed storage medium stored data
func (s *DB) DestroyClosed() error {
return os.RemoveAll(s.path)
}
// IsInterfaceNil returns true if there is no value under the interface
func (s *DB) IsInterfaceNil() bool {
return s == nil
}