| 1 | /* |
| 2 | Package lmdbsync provides advanced synchronization for LMDB environments at the |
| 3 | cost of performance. The package provides a drop-in replacement for *lmdb.Env |
| 4 | that can be used in situations where the database may be resized or where the |
| 5 | flag lmdb.NoLock is used. |
| 6 | |
| 7 | Bypassing an Env's methods to access the underlying lmdb.Env is not safe. The |
| 8 | severity of such usage depends such behavior should be strictly avoided as it |
| 9 | may produce undefined behavior from the LMDB C library. |
| 10 | |
| 11 | Resizing the environment |
| 12 | |
| 13 | The Env type synchronizes all calls to Env.SetMapSize so that it may, with some |
| 14 | caveats, be safely called in the presence of concurrent transactions after an |
| 15 | environment has been opened. All running transactions must complete before the |
| 16 | method will be called on the underlying lmdb.Env. |
| 17 | |
| 18 | If an open transaction depends on a call to Env.SetMapSize then the Env will |
| 19 | deadlock and block all future transactions. When using a Handler to |
| 20 | automatically call Env.SetMapSize this implies the restriction that |
| 21 | transactions must terminate independently of the creation/termination of other |
| 22 | transactions to avoid deadlock. |
| 23 | |
| 24 | In the simplest example, a view transaction that attempts an update on the |
| 25 | underlying Env will deadlock the environment if the map is full and a Handler |
| 26 | attempts to resize the map so the update may be retried. |
| 27 | |
| 28 | env.View(func(txn *lmdb.Txn) (err error) { |
| 29 | v, err := txn.Get(db, key) |
| 30 | if err != nil { |
| 31 | return err |
| 32 | } |
| 33 | err = env.Update(func(txn *lmdb.Txn) (err error) { // deadlock on lmdb.MapFull! |
| 34 | txn.Put(dbi, key, append(v, b...)) |
| 35 | }) |
| 36 | return err |
| 37 | } |
| 38 | |
| 39 | The update should instead be prepared inside the view and then executed |
| 40 | following its termination. This removes the implicit dependence of the view on |
| 41 | calls to Env.SetMapSize(). |
| 42 | |
| 43 | var v []byte |
| 44 | env.View(func(txn *lmdb.Txn) (err error) { |
| 45 | // RawRead isn't used because the value will be used outside the |
| 46 | // transaction. |
| 47 | v, err = txn.Get(db, key) |
| 48 | if err != nil { |
| 49 | return err |
| 50 | } |
| 51 | return nil |
| 52 | } |
| 53 | if err != nil { |
| 54 | // ... |
| 55 | } |
| 56 | err = env.Update(func(txn *lmdb.Txn) (err error) { // no deadlock, even if env is resized! |
| 57 | txn.Put(dbi, key, append(v, b...)) |
| 58 | }) |
| 59 | |
| 60 | The developers of LMDB officially recommend against applications changing the |
| 61 | memory map size for an open database. It requires careful synchronization by |
| 62 | all processes accessing the database file. And, a large memory map will not |
| 63 | affect disk usage on operating systems that support sparse files (e.g. Linux, |
| 64 | not OS X). |
| 65 | |
| 66 | See mdb_env_set_mapsize. |
| 67 | |
| 68 | MapFull |
| 69 | |
| 70 | The MapFullHandler function configures an Env to automatically call increase |
| 71 | the map size with Env.SetMapSize and retry transactions when a lmdb.MapFull |
| 72 | error prevents an update from being committed. |
| 73 | |
| 74 | Because updates may need to execute multiple times in the presence of |
| 75 | lmdb.MapFull it is important to make sure their TxnOp functions are idempotent |
| 76 | and do not cause unwanted additive change to the program state. |
| 77 | |
| 78 | See mdb_txn_commit and MDB_MAP_FULL. |
| 79 | |
| 80 | MapResized |
| 81 | |
| 82 | When multiple processes access and resize an environment it is not uncommon to |
| 83 | encounter a MapResized error which prevents the TxnOp from being executed and |
| 84 | requires a synchronized call to Env.SetMapSize before continuing normal |
| 85 | operation. |
| 86 | |
| 87 | The MapResizedHandler function configures an Env to automatically adopt a new |
| 88 | map size when a lmdb.MapResized error is encountered and retry execution of the |
| 89 | TxnOp. |
| 90 | |
| 91 | See mdb_txn_begin and MDB_MAP_RESIZED. |
| 92 | |
| 93 | NoLock |
| 94 | |
| 95 | When the lmdb.NoLock flag is set on an environment Env handles all transaction |
| 96 | synchronization using Go structures and is an experimental feature. It is |
| 97 | unclear what benefits this provides. |
| 98 | |
| 99 | Usage of lmdb.NoLock requires that update transactions acquire an exclusive |
| 100 | lock on the environment. In such cases it is required that view transactions |
| 101 | execute independently of update transactions, a requirement more strict than |
| 102 | that from handling MapFull. |
| 103 | |
| 104 | See mdb_env_open and MDB_NOLOCK. |
| 105 | */ |
| 106 | package lmdbsync |
| 107 | |
| 108 | import ( |
| 109 | "fmt" |
| 110 | "os" |
| 111 | "sync" |
| 112 | "time" |
| 113 | |
| 114 | "golang.org/x/net/context" |
| 115 | |
| 116 | "github.com/bmatsuo/lmdb-go/lmdb" |
| 117 | ) |
| 118 | |
| 119 | // Env wraps an *lmdb.Env, receiving all the same methods and proxying some to |
| 120 | // provide transaction management. Transactions run by an Env handle |
| 121 | // lmdb.MapResized error transparently through additional synchronization. |
| 122 | // Additionally, Env is safe to use on environments setting the lmdb.NoLock |
| 123 | // flag. When in NoLock mode write transactions block all read transactions |
| 124 | // from running (in addition to blocking other write transactions like a normal |
| 125 | // lmdb.Env would). |
| 126 | // |
| 127 | // Env proxies several methods to provide synchronization required for safe |
| 128 | // operation in some scenarios. It is important not byprass proxies and call |
| 129 | // the methods directly on the underlying lmdb.Env or synchronization may be |
| 130 | // interfered with. Calling proxied methods directly on the lmdb.Env may |
| 131 | // result in poor transaction performance or unspecified behavior in from the C |
| 132 | // library. |
| 133 | type Env struct { |
| 134 | *lmdb.Env |
| 135 | Handlers HandlerChain |
| 136 | ctx context.Context |
| 137 | noLock bool |
| 138 | txnlock sync.RWMutex |
| 139 | } |
| 140 | |
| 141 | // NewEnv returns an newly allocated Env that wraps env. If env is nil then |
| 142 | // lmdb.NewEnv() will be called to allocate an lmdb.Env. |
| 143 | func NewEnv(env *lmdb.Env, h ...Handler) (*Env, error) { |
| 144 | var err error |
| 145 | if env == nil { |
| 146 | env, err = lmdb.NewEnv() |
| 147 | if err != nil { |
| 148 | return nil, err |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | flags, err := env.Flags() |
| 153 | if err != nil { |
| 154 | return nil, err |
| 155 | } |
| 156 | noLock := flags&lmdb.NoLock != 0 |
| 157 | |
| 158 | chain := append(HandlerChain(nil), h...) |
| 159 | |
| 160 | _env := &Env{ |
| 161 | Env: env, |
| 162 | Handlers: chain, |
| 163 | noLock: noLock, |
| 164 | ctx: context.Background(), |
| 165 | } |
| 166 | return _env, nil |
| 167 | } |
| 168 | |
| 169 | // Open is a proxy for r.Env.Open() that detects the lmdb.NoLock flag to |
| 170 | // properly manage transaction synchronization. |
| 171 | func (r *Env) Open(path string, flags uint, mode os.FileMode) error { |
| 172 | err := r.Env.Open(path, flags, mode) |
| 173 | if err != nil { |
| 174 | // no update to flags occurred |
| 175 | return err |
| 176 | } |
| 177 | |
| 178 | if flags&lmdb.NoLock != 0 { |
| 179 | r.noLock = true |
| 180 | } |
| 181 | |
| 182 | return nil |
| 183 | } |
| 184 | |
| 185 | // SetMapSize is a proxy for r.Env.SetMapSize() that blocks while concurrent |
| 186 | // transactions are in progress. |
| 187 | func (r *Env) SetMapSize(size int64) error { |
| 188 | return r.setMapSize(size, 0) |
| 189 | } |
| 190 | |
| 191 | func (r *Env) setMapSize(size int64, delay time.Duration) error { |
| 192 | r.txnlock.Lock() |
| 193 | if delay > 0 { |
| 194 | // wait before adopting a map size set from another process. hold on to |
| 195 | // the transaction lock so that other transactions don't attempt to |
| 196 | // begin while waiting. |
| 197 | time.Sleep(delay) |
| 198 | } |
| 199 | err := r.Env.SetMapSize(size) |
| 200 | r.txnlock.Unlock() |
| 201 | return err |
| 202 | } |
| 203 | |
| 204 | // BeginTxn overrides the r.Env.BeginTxn and always returns an error. An |
| 205 | // unmanaged transaction. |
| 206 | func (r *Env) BeginTxn(parent *lmdb.Txn, flags uint) (*lmdb.Txn, error) { |
| 207 | return nil, fmt.Errorf("lmdbsync: unmanaged transactions are not supported") |
| 208 | } |
| 209 | |
| 210 | // RunTxn is a proxy for r.Env.RunTxn(). |
| 211 | // |
| 212 | // If lmdb.NoLock is set on r.Env then RunTxn will block while other updates |
| 213 | // are in progress, regardless of flags. |
| 214 | func (r *Env) RunTxn(flags uint, op lmdb.TxnOp) (err error) { |
| 215 | readonly := flags&lmdb.Readonly != 0 |
| 216 | return r.runHandler(readonly, func() error { return r.Env.RunTxn(flags, op) }, r.Handlers) |
| 217 | } |
| 218 | |
| 219 | // View is a proxy for r.Env.View(). |
| 220 | // |
| 221 | // If lmdb.NoLock is set on r.Env then View will block until any running update |
| 222 | // completes. |
| 223 | func (r *Env) View(op lmdb.TxnOp) error { |
| 224 | return r.runHandler(true, func() error { return r.Env.View(op) }, r.Handlers) |
| 225 | } |
| 226 | |
| 227 | // Update is a proxy for r.Env.Update(). |
| 228 | // |
| 229 | // If lmdb.NoLock is set on r.Env then Update blocks until all other |
| 230 | // transactions have terminated and blocks all other transactions from running |
| 231 | // while in progress (including readonly transactions). |
| 232 | func (r *Env) Update(op lmdb.TxnOp) error { |
| 233 | return r.runHandler(false, func() error { return r.Env.Update(op) }, r.Handlers) |
| 234 | } |
| 235 | |
| 236 | // UpdateLocked is a proxy for r.Env.UpdateLocked(). |
| 237 | // |
| 238 | // If lmdb.NoLock is set on r.Env then UpdateLocked blocks until all other |
| 239 | // transactions have terminated and blocks all other transactions from running |
| 240 | // while in progress (including readonly transactions). |
| 241 | func (r *Env) UpdateLocked(op lmdb.TxnOp) error { |
| 242 | return r.runHandler(false, func() error { return r.Env.UpdateLocked(op) }, r.Handlers) |
| 243 | } |
| 244 | |
| 245 | // WithHandler returns a TxnRunner than handles transaction errors r.Handlers |
| 246 | // chained with h. |
| 247 | func (r *Env) WithHandler(h Handler) TxnRunner { |
| 248 | return &handlerRunner{ |
| 249 | env: r, |
| 250 | h: r.Handlers.Append(h), |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | func (r *Env) runHandler(readonly bool, fn func() error, h Handler) error { |
| 255 | ctx := r.ctx |
| 256 | for { |
| 257 | err := r.run(readonly, fn) |
| 258 | ctx, err = h.HandleTxnErr(ctx, r, err) |
| 259 | if err != ErrTxnRetry { |
| 260 | return err |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | func (r *Env) run(readonly bool, fn func() error) error { |
| 265 | var err error |
| 266 | if r.noLock && !readonly { |
| 267 | r.txnlock.Lock() |
| 268 | err = fn() |
| 269 | r.txnlock.Unlock() |
| 270 | } else { |
| 271 | r.txnlock.RLock() |
| 272 | err = fn() |
| 273 | r.txnlock.RUnlock() |
| 274 | } |
| 275 | return err |
| 276 | } |