-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathmdb_store.go
346 lines (298 loc) · 6.92 KB
/
mdb_store.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
package raftmdb
import (
"fmt"
"github.com/armon/gomdb"
"github.com/hashicorp/raft"
"os"
"path/filepath"
)
const (
dbLogs = "logs"
dbConf = "conf"
dbMaxMapSize = 128 * 1024 * 1024 // 128MB default max map size
)
// Sub-dir used for MDB
var mdbPath = "mdb/"
// MDBStore provides an implementation of LogStore and StableStore,
// all backed by a single MDB database.
type MDBStore struct {
env *mdb.Env
path string
maxSize uint64
}
// NewMDBStore returns a new MDBStore and potential
// error. Requres a base directory from which to operate.
// Uses the default maximum size.
func NewMDBStore(base string) (*MDBStore, error) {
return NewMDBStoreWithSize(base, 0)
}
// NewMDBStore returns a new MDBStore and potential
// error. Requres a base directory from which to operate,
// and a maximum size. If maxSize is not 0, a default value is used.
func NewMDBStoreWithSize(base string, maxSize uint64) (*MDBStore, error) {
// Get the paths
path := filepath.Join(base, mdbPath)
if err := os.MkdirAll(path, 0755); err != nil {
return nil, err
}
// Set the maxSize if not given
if maxSize == 0 {
maxSize = dbMaxMapSize
}
// Create the env
env, err := mdb.NewEnv()
if err != nil {
return nil, err
}
// Create the struct
store := &MDBStore{
env: env,
path: path,
maxSize: maxSize,
}
// Initialize the db
if err := store.initialize(); err != nil {
env.Close()
return nil, err
}
return store, nil
}
// initialize is used to setup the mdb store
func (m *MDBStore) initialize() error {
// Allow up to 2 sub-dbs
if err := m.env.SetMaxDBs(mdb.DBI(2)); err != nil {
return err
}
// Increase the maximum map size
if err := m.env.SetMapSize(m.maxSize); err != nil {
return err
}
// Open the DB
if err := m.env.Open(m.path, mdb.NOTLS, 0755); err != nil {
return err
}
// Create all the tables
tx, _, err := m.startTxn(false, dbLogs, dbConf)
if err != nil {
tx.Abort()
return err
}
return tx.Commit()
}
// Close is used to gracefully shutdown the MDB store
func (m *MDBStore) Close() error {
m.env.Close()
return nil
}
// startTxn is used to start a transaction and open all the associated sub-databases
func (m *MDBStore) startTxn(readonly bool, open ...string) (*mdb.Txn, []mdb.DBI, error) {
var txFlags uint = 0
var dbFlags uint = 0
if readonly {
txFlags |= mdb.RDONLY
} else {
dbFlags |= mdb.CREATE
}
tx, err := m.env.BeginTxn(nil, txFlags)
if err != nil {
return nil, nil, err
}
var dbs []mdb.DBI
for _, name := range open {
dbi, err := tx.DBIOpen(name, dbFlags)
if err != nil {
tx.Abort()
return nil, nil, err
}
dbs = append(dbs, dbi)
}
return tx, dbs, nil
}
func (m *MDBStore) FirstIndex() (uint64, error) {
tx, dbis, err := m.startTxn(true, dbLogs)
if err != nil {
return 0, err
}
defer tx.Abort()
cursor, err := tx.CursorOpen(dbis[0])
if err != nil {
return 0, err
}
defer cursor.Close()
key, _, err := cursor.Get(nil, mdb.FIRST)
if err == mdb.NotFound {
return 0, nil
} else if err != nil {
return 0, err
}
// Convert the key to the index
return bytesToUint64(key), nil
}
func (m *MDBStore) LastIndex() (uint64, error) {
tx, dbis, err := m.startTxn(true, dbLogs)
if err != nil {
return 0, err
}
defer tx.Abort()
cursor, err := tx.CursorOpen(dbis[0])
if err != nil {
return 0, err
}
defer cursor.Close()
key, _, err := cursor.Get(nil, mdb.LAST)
if err == mdb.NotFound {
return 0, nil
} else if err != nil {
return 0, err
}
// Convert the key to the index
return bytesToUint64(key), nil
}
// Gets a log entry at a given index
func (m *MDBStore) GetLog(index uint64, logOut *raft.Log) error {
key := uint64ToBytes(index)
tx, dbis, err := m.startTxn(true, dbLogs)
if err != nil {
return err
}
defer tx.Abort()
val, err := tx.Get(dbis[0], key)
if err == mdb.NotFound {
return raft.ErrLogNotFound
} else if err != nil {
return err
}
// Convert the value to a log
return decodeMsgPack(val, logOut)
}
// Stores a log entry
func (m *MDBStore) StoreLog(log *raft.Log) error {
return m.StoreLogs([]*raft.Log{log})
}
// Stores multiple log entries
func (m *MDBStore) StoreLogs(logs []*raft.Log) error {
// Start write txn
tx, dbis, err := m.startTxn(false, dbLogs)
if err != nil {
return err
}
for _, log := range logs {
// Convert to an on-disk format
key := uint64ToBytes(log.Index)
val, err := encodeMsgPack(log)
if err != nil {
tx.Abort()
return err
}
// Write to the table
if err := tx.Put(dbis[0], key, val.Bytes(), 0); err != nil {
tx.Abort()
return err
}
}
return tx.Commit()
}
// Deletes a range of log entries. The range is inclusive.
func (m *MDBStore) DeleteRange(minIdx, maxIdx uint64) error {
// Start write txn
tx, dbis, err := m.startTxn(false, dbLogs)
if err != nil {
return err
}
defer tx.Abort()
// Hack around an LMDB bug by running the delete multiple
// times until there are no further rows.
var num int
DELETE:
num, err = m.innerDeleteRange(tx, dbis, minIdx, maxIdx)
if err != nil {
return err
}
if num > 0 {
goto DELETE
}
return tx.Commit()
}
// innerDeleteRange does a single pass to delete the indexes (inclusively)
func (m *MDBStore) innerDeleteRange(tx *mdb.Txn, dbis []mdb.DBI, minIdx, maxIdx uint64) (num int, err error) {
// Open a cursor
cursor, err := tx.CursorOpen(dbis[0])
if err != nil {
return num, err
}
var key []byte
didDelete := false
for {
if didDelete {
key, _, err = cursor.Get(nil, mdb.GET_CURRENT)
didDelete = false
// LMDB will return EINVAL(22) for the GET_CURRENT op if
// there is no further keys. We treat this as no more
// keys being found.
if num, ok := err.(mdb.Errno); ok && num == 22 {
err = mdb.NotFound
}
} else {
key, _, err = cursor.Get(nil, mdb.NEXT)
}
if err == mdb.NotFound || len(key) == 0 {
break
} else if err != nil {
return num, err
}
// Check if the key is in the range
keyVal := bytesToUint64(key)
if keyVal < minIdx {
continue
}
if keyVal > maxIdx {
break
}
// Attempt delete
if err := cursor.Del(0); err != nil {
return num, err
}
didDelete = true
num++
}
return num, nil
}
// Set a K/V pair
func (m *MDBStore) Set(key []byte, val []byte) error {
// Start write txn
tx, dbis, err := m.startTxn(false, dbConf)
if err != nil {
return err
}
if err := tx.Put(dbis[0], key, val, 0); err != nil {
tx.Abort()
return err
}
return tx.Commit()
}
// Get a K/V pair
func (m *MDBStore) Get(key []byte) ([]byte, error) {
// Start read txn
tx, dbis, err := m.startTxn(true, dbConf)
if err != nil {
return nil, err
}
defer tx.Abort()
val, err := tx.Get(dbis[0], key)
if err == mdb.NotFound {
return nil, fmt.Errorf("not found")
} else if err != nil {
return nil, err
}
return val, nil
}
func (m *MDBStore) SetUint64(key []byte, val uint64) error {
return m.Set(key, uint64ToBytes(val))
}
func (m *MDBStore) GetUint64(key []byte) (uint64, error) {
buf, err := m.Get(key)
if err != nil {
return 0, err
}
return bytesToUint64(buf), nil
}