Debian Codegraph @

lmdb/env.go

raw symbols SCIP
1 package lmdb
2
3 /*
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include "lmdb.h"
7 #include "lmdbgo.h"
8 */
9 import "C"
10
11 import (
12 "errors"
13 "os"
14 "runtime"
15 "sync"
16 "unsafe"
17 )
18
19 // success is a value returned from the LMDB API to indicate a successful call.
20 // The functions in this API this behavior and its use is not required.
21 const success = C.MDB_SUCCESS
22
23 // These flags are used exclusively for Env types and are set with Env.Open.
24 // Some flags may be set/unset later using Env.Set/.Unset methods. Others will
25 // produce syscall.EINVAL. Refer to the C documentation for detailed
26 // information.
27 const (
28 // Flags for Env.Open.
29 //
30 // See mdb_env_open
31
32 FixedMap = C.MDB_FIXEDMAP // Danger zone. Map memory at a fixed address.
33 NoSubdir = C.MDB_NOSUBDIR // Argument to Open is a file, not a directory.
34 Readonly = C.MDB_RDONLY // Used in several functions to denote an object as readonly.
35 WriteMap = C.MDB_WRITEMAP // Use a writable memory map.
36 NoMetaSync = C.MDB_NOMETASYNC // Don't fsync metapage after commit.
37 NoSync = C.MDB_NOSYNC // Don't fsync after commit.
38 MapAsync = C.MDB_MAPASYNC // Flush asynchronously when using the WriteMap flag.
39 NoTLS = C.MDB_NOTLS // Danger zone. When unset reader locktable slots are tied to their thread.
40 NoLock = C.MDB_NOLOCK // Danger zone. LMDB does not use any locks.
41 NoReadahead = C.MDB_NORDAHEAD // Disable readahead. Requires OS support.
42 NoMemInit = C.MDB_NOMEMINIT // Disable LMDB memory initialization.
43 )
44
45 // These flags are exclusively used in the Env.CopyFlags and Env.CopyFDFlags
46 // methods.
47 const (
48 // Flags for Env.CopyFlags
49 //
50 // See mdb_env_copy2
51
52 CopyCompact = C.MDB_CP_COMPACT // Perform compaction while copying
53 )
54
55 // DBI is a handle for a database in an Env.
56 //
57 // See MDB_dbi
58 type DBI C.MDB_dbi
59
60 // Env is opaque structure for a database environment. A DB environment
61 // supports multiple databases, all residing in the same shared-memory map.
62 //
63 // See MDB_env.
64 type Env struct {
65 _env *C.MDB_env
66
67 // closeLock is used to allow the Txn finalizer to check if the Env has
68 // been closed, so that it may know if it must abort.
69 closeLock sync.RWMutex
70
71 ckey *C.MDB_val
72 cval *C.MDB_val
73 }
74
75 // NewEnv allocates and initializes a new Env.
76 //
77 // See mdb_env_create.
78 func NewEnv() (*Env, error) {
79 env := new(Env)
80 ret := C.mdb_env_create(&env._env)
81 if ret != success {
82 return nil, operrno("mdb_env_create", ret)
83 }
84 env.ckey = (*C.MDB_val)(C.malloc(C.size_t(unsafe.Sizeof(C.MDB_val{}))))
85 env.cval = (*C.MDB_val)(C.malloc(C.size_t(unsafe.Sizeof(C.MDB_val{}))))
86
87 runtime.SetFinalizer(env, (*Env).Close)
88 return env, nil
89 }
90
91 // Open an environment handle. If this function fails Close() must be called to
92 // discard the Env handle. Open passes flags|NoTLS to mdb_env_open.
93 //
94 // See mdb_env_open.
95 func (env *Env) Open(path string, flags uint, mode os.FileMode) error {
96 cpath := C.CString(path)
97 defer C.free(unsafe.Pointer(cpath))
98 ret := C.mdb_env_open(env._env, cpath, C.uint(NoTLS|flags), C.mdb_mode_t(mode))
99 return operrno("mdb_env_open", ret)
100 }
101
102 var errNotOpen = errors.New("enivornment is not open")
103 var errNegSize = errors.New("negative size")
104
105 // FD returns the open file descriptor (or Windows file handle) for the given
106 // environment. An error is returned if the environment has not been
107 // successfully Opened (where C API just retruns an invalid handle).
108 //
109 // See mdb_env_get_fd.
110 func (env *Env) FD() (uintptr, error) {
111 // fdInvalid is the value -1 as a uintptr, which is used by LMDB in the
112 // case that env has not been opened yet. the strange construction is done
113 // to avoid constant value overflow errors at compile time.
114 const fdInvalid = ^uintptr(0)
115
116 mf := new(C.mdb_filehandle_t)
117 ret := C.mdb_env_get_fd(env._env, mf)
118 err := operrno("mdb_env_get_fd", ret)
119 if err != nil {
120 return 0, err
121 }
122 fd := uintptr(*mf)
123
124 if fd == fdInvalid {
125 return 0, errNotOpen
126 }
127 return fd, nil
128 }
129
130 // ReaderList dumps the contents of the reader lock table as text. Readers
131 // start on the second line as space-delimited fields described by the first
132 // line.
133 //
134 // See mdb_reader_list.
135 func (env *Env) ReaderList(fn func(string) error) error {
136 ctx, done := newMsgFunc(fn)
137 defer done()
138 if fn == nil {
139 ctx = 0
140 }
141
142 ret := C.lmdbgo_mdb_reader_list(env._env, C.size_t(ctx))
143 if ret >= 0 {
144 return nil
145 }
146 if ret < 0 && ctx != 0 {
147 err := ctx.get().err
148 if err != nil {
149 return err
150 }
151 }
152 return operrno("mdb_reader_list", ret)
153 }
154
155 // ReaderCheck clears stale entries from the reader lock table and returns the
156 // number of entries cleared.
157 //
158 // See mdb_reader_check()
159 func (env *Env) ReaderCheck() (int, error) {
160 var _dead C.int
161 ret := C.mdb_reader_check(env._env, &_dead)
162 return int(_dead), operrno("mdb_reader_check", ret)
163 }
164
165 func (env *Env) close() bool {
166 if env._env == nil {
167 return false
168 }
169
170 env.closeLock.Lock()
171 C.mdb_env_close(env._env)
172 env._env = nil
173 env.closeLock.Unlock()
174
175 C.free(unsafe.Pointer(env.ckey))
176 C.free(unsafe.Pointer(env.cval))
177 env.ckey = nil
178 env.cval = nil
179 return true
180 }
181
182 // Close shuts down the environment, releases the memory map, and clears the
183 // finalizer on env.
184 //
185 // See mdb_env_close.
186 func (env *Env) Close() error {
187 if env.close() {
188 runtime.SetFinalizer(env, nil)
189 return nil
190 }
191 return errors.New("environment is already closed")
192 }
193
194 // CopyFD copies env to the the file descriptor fd.
195 //
196 // See mdb_env_copyfd.
197 func (env *Env) CopyFD(fd uintptr) error {
198 ret := C.mdb_env_copyfd(env._env, C.mdb_filehandle_t(fd))
199 return operrno("mdb_env_copyfd", ret)
200 }
201
202 // CopyFDFlag copies env to the file descriptor fd, with options.
203 //
204 // See mdb_env_copyfd2.
205 func (env *Env) CopyFDFlag(fd uintptr, flags uint) error {
206 ret := C.mdb_env_copyfd2(env._env, C.mdb_filehandle_t(fd), C.uint(flags))
207 return operrno("mdb_env_copyfd2", ret)
208 }
209
210 // Copy copies the data in env to an environment at path.
211 //
212 // See mdb_env_copy.
213 func (env *Env) Copy(path string) error {
214 cpath := C.CString(path)
215 defer C.free(unsafe.Pointer(cpath))
216 ret := C.mdb_env_copy(env._env, cpath)
217 return operrno("mdb_env_copy", ret)
218 }
219
220 // CopyFlag copies the data in env to an environment at path created with flags.
221 //
222 // See mdb_env_copy2.
223 func (env *Env) CopyFlag(path string, flags uint) error {
224 cpath := C.CString(path)
225 defer C.free(unsafe.Pointer(cpath))
226 ret := C.mdb_env_copy2(env._env, cpath, C.uint(flags))
227 return operrno("mdb_env_copy2", ret)
228 }
229
230 // Stat contains database status information.
231 //
232 // See MDB_stat.
233 type Stat struct {
234 PSize uint // Size of a database page. This is currently the same for all databases.
235 Depth uint // Depth (height) of the B-tree
236 BranchPages uint64 // Number of internal (non-leaf) pages
237 LeafPages uint64 // Number of leaf pages
238 OverflowPages uint64 // Number of overflow pages
239 Entries uint64 // Number of data items
240 }
241
242 // Stat returns statistics about the environment.
243 //
244 // See mdb_env_stat.
245 func (env *Env) Stat() (*Stat, error) {
246 var _stat C.MDB_stat
247 ret := C.mdb_env_stat(env._env, &_stat)
248 if ret != success {
249 return nil, operrno("mdb_env_stat", ret)
250 }
251 stat := Stat{PSize: uint(_stat.ms_psize),
252 Depth: uint(_stat.ms_depth),
253 BranchPages: uint64(_stat.ms_branch_pages),
254 LeafPages: uint64(_stat.ms_leaf_pages),
255 OverflowPages: uint64(_stat.ms_overflow_pages),
256 Entries: uint64(_stat.ms_entries)}
257 return &stat, nil
258 }
259
260 // EnvInfo contains information an environment.
261 //
262 // See MDB_envinfo.
263 type EnvInfo struct {
264 MapSize int64 // Size of the data memory map
265 LastPNO int64 // ID of the last used page
266 LastTxnID int64 // ID of the last committed transaction
267 MaxReaders uint // maximum number of threads for the environment
268 NumReaders uint // maximum number of threads used in the environment
269 }
270
271 // Info returns information about the environment.
272 //
273 // See mdb_env_info.
274 func (env *Env) Info() (*EnvInfo, error) {
275 var _info C.MDB_envinfo
276 ret := C.mdb_env_info(env._env, &_info)
277 if ret != success {
278 return nil, operrno("mdb_env_info", ret)
279 }
280 info := EnvInfo{
281 MapSize: int64(_info.me_mapsize),
282 LastPNO: int64(_info.me_last_pgno),
283 LastTxnID: int64(_info.me_last_txnid),
284 MaxReaders: uint(_info.me_maxreaders),
285 NumReaders: uint(_info.me_numreaders),
286 }
287 return &info, nil
288 }
289
290 // Sync flushes buffers to disk. If force is true a synchronous flush occurs
291 // and ignores any NoSync or MapAsync flag on the environment.
292 //
293 // See mdb_env_sync.
294 func (env *Env) Sync(force bool) error {
295 ret := C.mdb_env_sync(env._env, cbool(force))
296 return operrno("mdb_env_sync", ret)
297 }
298
299 // SetFlags sets flags in the environment.
300 //
301 // See mdb_env_set_flags.
302 func (env *Env) SetFlags(flags uint) error {
303 ret := C.mdb_env_set_flags(env._env, C.uint(flags), C.int(1))
304 return operrno("mdb_env_set_flags", ret)
305 }
306
307 // UnsetFlags clears flags in the environment.
308 //
309 // See mdb_env_set_flags.
310 func (env *Env) UnsetFlags(flags uint) error {
311 ret := C.mdb_env_set_flags(env._env, C.uint(flags), C.int(0))
312 return operrno("mdb_env_set_flags", ret)
313 }
314
315 // Flags returns the flags set in the environment.
316 //
317 // See mdb_env_get_flags.
318 func (env *Env) Flags() (uint, error) {
319 var _flags C.uint
320 ret := C.mdb_env_get_flags(env._env, &_flags)
321 if ret != success {
322 return 0, operrno("mdb_env_get_flags", ret)
323 }
324 return uint(_flags), nil
325 }
326
327 // Path returns the path argument passed to Open. Path returns a non-nil error
328 // if env.Open() was not previously called.
329 //
330 // See mdb_env_get_path.
331 func (env *Env) Path() (string, error) {
332 var cpath *C.char
333 ret := C.mdb_env_get_path(env._env, &cpath)
334 if ret != success {
335 return "", operrno("mdb_env_get_path", ret)
336 }
337 if cpath == nil {
338 return "", errNotOpen
339 }
340 return C.GoString(cpath), nil
341 }
342
343 // SetMapSize sets the size of the environment memory map.
344 //
345 // See mdb_env_set_mapsize.
346 func (env *Env) SetMapSize(size int64) error {
347 if size < 0 {
348 return errNegSize
349 }
350 ret := C.mdb_env_set_mapsize(env._env, C.size_t(size))
351 return operrno("mdb_env_set_mapsize", ret)
352 }
353
354 // SetMaxReaders sets the maximum number of reader slots in the environment.
355 //
356 // See mdb_env_set_maxreaders.
357 func (env *Env) SetMaxReaders(size int) error {
358 if size < 0 {
359 return errNegSize
360 }
361 ret := C.mdb_env_set_maxreaders(env._env, C.uint(size))
362 return operrno("mdb_env_set_maxreaders", ret)
363 }
364
365 // MaxReaders returns the maximum number of reader slots for the environment.
366 //
367 // See mdb_env_get_maxreaders.
368 func (env *Env) MaxReaders() (int, error) {
369 var max C.uint
370 ret := C.mdb_env_get_maxreaders(env._env, &max)
371 return int(max), operrno("mdb_env_get_maxreaders", ret)
372 }
373
374 // MaxKeySize returns the maximum allowed length for a key.
375 //
376 // See mdb_env_get_maxkeysize.
377 func (env *Env) MaxKeySize() int {
378 if env == nil {
379 return int(C.mdb_env_get_maxkeysize(nil))
380 }
381 return int(C.mdb_env_get_maxkeysize(env._env))
382 }
383
384 // SetMaxDBs sets the maximum number of named databases for the environment.
385 //
386 // See mdb_env_set_maxdbs.
387 func (env *Env) SetMaxDBs(size int) error {
388 if size < 0 {
389 return errNegSize
390 }
391 ret := C.mdb_env_set_maxdbs(env._env, C.MDB_dbi(size))
392 return operrno("mdb_env_set_maxdbs", ret)
393 }
394
395 // BeginTxn is an unsafe, low-level method to initialize a new transaction on
396 // env. The Txn returned by BeginTxn is unmanaged and must be terminated by
397 // calling either its Abort or Commit methods to ensure that its resources are
398 // released.
399 //
400 // BeginTxn does not call runtime.LockOSThread. Unless the Readonly flag is
401 // passed goroutines must call runtime.LockOSThread before calling BeginTxn and
402 // the returned Txn must not have its methods called from another goroutine.
403 // Failure to meet these restrictions can have undefined results that may
404 // include deadlocking your application.
405 //
406 // Instead of calling BeginTxn users should prefer calling the View and Update
407 // methods, which assist in management of Txn objects and provide OS thread
408 // locking required for write transactions.
409 //
410 // A finalizer detects unreachable, live transactions and logs thems to
411 // standard error. The transactions are aborted, but their presence should be
412 // interpreted as an application error which should be patched so transactions
413 // are terminated explicitly. Unterminated transactions can adversly effect
414 // database performance and cause the database to grow until the map is full.
415 //
416 // See mdb_txn_begin.
417 func (env *Env) BeginTxn(parent *Txn, flags uint) (*Txn, error) {
418 txn, err := beginTxn(env, parent, flags)
419 if txn != nil {
420 runtime.SetFinalizer(txn, func(v interface{}) { v.(*Txn).finalize() })
421 }
422 return txn, err
423 }
424
425 // RunTxn creates a new Txn and calls fn with it as an argument. Run commits
426 // the transaction if fn returns nil otherwise the transaction is aborted.
427 // Because RunTxn terminates the transaction goroutines should not retain
428 // references to it or its data after fn returns.
429 //
430 // RunTxn does not call runtime.LockOSThread. Unless the Readonly flag is
431 // passed the calling goroutine should ensure it is locked to its thread and
432 // any goroutines started by fn must not call methods on the Txn object it is
433 // passed.
434 //
435 // See mdb_txn_begin.
436 func (env *Env) RunTxn(flags uint, fn TxnOp) error {
437 return env.run(false, flags, fn)
438 }
439
440 // View creates a readonly transaction with a consistent view of the
441 // environment and passes it to fn. View terminates its transaction after fn
442 // returns. Any error encountered by View is returned.
443 //
444 // Unlike with Update transactions, goroutines created by fn are free to call
445 // methods on the Txn passed to fn provided they are synchronized in their
446 // accesses (e.g. using a mutex or channel).
447 //
448 // Any call to Commit, Abort, Reset or Renew on a Txn created by View will
449 // panic.
450 func (env *Env) View(fn TxnOp) error {
451 return env.run(false, Readonly, fn)
452 }
453
454 // Update calls fn with a writable transaction. Update commits the transaction
455 // if fn returns a nil error otherwise Update aborts the transaction and
456 // returns the error.
457 //
458 // Update calls runtime.LockOSThread to lock the calling goroutine to its
459 // thread and until fn returns and the transaction has been terminated, at
460 // which point runtime.UnlockOSThread is called. If the calling goroutine is
461 // already known to be locked to a thread, use UpdateLocked instead to avoid
462 // premature unlocking of the goroutine.
463 //
464 // Neither Update nor UpdateLocked cannot be called safely from a goroutine
465 // where it isn't known if runtime.LockOSThread has been called. In such
466 // situations writes must either be done in a newly created goroutine which can
467 // be safely locked, or through a worker goroutine that accepts updates to
468 // apply and delivers transaction results using channels. See the package
469 // documentation and examples for more details.
470 //
471 // Goroutines created by the operation fn must not use methods on the Txn
472 // object that fn is passed. Doing so would have undefined and unpredictable
473 // results for your program (likely including data loss, deadlock, etc).
474 //
475 // Any call to Commit, Abort, Reset or Renew on a Txn created by Update will
476 // panic.
477 func (env *Env) Update(fn TxnOp) error {
478 return env.run(true, 0, fn)
479 }
480
481 // UpdateLocked behaves like Update but does not lock the calling goroutine to
482 // its thread. UpdateLocked should be used if the calling goroutine is already
483 // locked to its thread for another purpose.
484 //
485 // Neither Update nor UpdateLocked cannot be called safely from a goroutine
486 // where it isn't known if runtime.LockOSThread has been called. In such
487 // situations writes must either be done in a newly created goroutine which can
488 // be safely locked, or through a worker goroutine that accepts updates to
489 // apply and delivers transaction results using channels. See the package
490 // documentation and examples for more details.
491 //
492 // Goroutines created by the operation fn must not use methods on the Txn
493 // object that fn is passed. Doing so would have undefined and unpredictable
494 // results for your program (likely including data loss, deadlock, etc).
495 //
496 // Any call to Commit, Abort, Reset or Renew on a Txn created by UpdateLocked
497 // will panic.
498 func (env *Env) UpdateLocked(fn TxnOp) error {
499 return env.run(false, 0, fn)
500 }
501
502 func (env *Env) run(lock bool, flags uint, fn TxnOp) error {
503 if lock {
504 runtime.LockOSThread()
505 defer runtime.UnlockOSThread()
506 }
507 txn, err := beginTxn(env, nil, flags)
508 if err != nil {
509 return err
510 }
511 return txn.runOpTerm(fn)
512 }
513
514 // CloseDBI closes the database handle, db. Normally calling CloseDBI
515 // explicitly is not necessary.
516 //
517 // It is the caller's responsibility to serialize calls to CloseDBI.
518 //
519 // See mdb_dbi_close.
520 func (env *Env) CloseDBI(db DBI) {
521 C.mdb_dbi_close(env._env, C.MDB_dbi(db))
522 }