| 1 | package lmdbpool |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "log" |
| 6 | "sync" |
| 7 | "sync/atomic" |
| 8 | |
| 9 | "github.com/bmatsuo/lmdb-go/lmdb" |
| 10 | ) |
| 11 | |
| 12 | // UpdateHandling describes how a TxnPool handles existing lmdb.Readonly |
| 13 | // transactions when an environment update occurs. Applications with a high |
| 14 | // rate of large updates may need to choose non-default settings to reduce |
| 15 | // their storage requirements at the cost of read throughput. |
| 16 | // |
| 17 | // The zero-value of UpdateHandling causes a TxnPool to ignore all updates and |
| 18 | // defers to the application and the lmdb.Txn finalizers clear stale readers |
| 19 | // (pulling an lmdb.Readonly transaction out of the pool is enough to release |
| 20 | // its stale pages). |
| 21 | type UpdateHandling uint |
| 22 | |
| 23 | const ( |
| 24 | // HandleOutstanding causes a TxnPool to abort any lmdb.Readonly |
| 25 | // transactions that are being returned to the pool after an update. |
| 26 | HandleOutstanding UpdateHandling = 1 << iota |
| 27 | |
| 28 | // HandleIdle causes a TxnPool to actively attempt aborting idle |
| 29 | // transactions in the sync.Pool after an update has been committed. There |
| 30 | // is no guarantee when using AbortIdle that all idle readers will be |
| 31 | // aborted. |
| 32 | HandleIdle |
| 33 | |
| 34 | // HandleRenew modifies how other UpdateHandling flags are interpretted and |
| 35 | // causes a TxnPool to renew transactions and put them back in the pool |
| 36 | // instead of aborting them. |
| 37 | HandleRenew |
| 38 | |
| 39 | // HandleAll is a convenient alias for the combination of HandleOutstanding |
| 40 | // and HandleIdle. |
| 41 | HandleAll = HandleOutstanding | HandleIdle |
| 42 | ) |
| 43 | |
| 44 | // TxnPool is a pool for reusing transactions through their Reset and Renew |
| 45 | // methods. However, even though TxnPool can only reuse lmdb.Readonly |
| 46 | // transactions it this way it should be used to create and terminate all Txns |
| 47 | // if it is used at all. Update transactions can cause LMDB to use excessive |
| 48 | // numbers of pages when there are long-lived lmdb.Readonly transactions in a |
| 49 | // TxnPool. Executing all transactions using the TxnPool allows it to track |
| 50 | // updates and prevent long-lived updates from causing excessive disk |
| 51 | // utilization. |
| 52 | type TxnPool struct { |
| 53 | // UpdateHandling determines how a TxnPool behaves after updates have been |
| 54 | // committed. It is not safe to modify UpdateHandling if TxnPool is being |
| 55 | // used concurrently. |
| 56 | UpdateHandling UpdateHandling |
| 57 | |
| 58 | lastid uintptr |
| 59 | idleGuard uintptr |
| 60 | env *lmdb.Env |
| 61 | pool sync.Pool |
| 62 | } |
| 63 | |
| 64 | // NewTxnPool initializes returns a new TxnPool. |
| 65 | func NewTxnPool(env *lmdb.Env) *TxnPool { |
| 66 | p := &TxnPool{ |
| 67 | env: env, |
| 68 | } |
| 69 | return p |
| 70 | } |
| 71 | |
| 72 | // Close flushes the pool of transactions and aborts them to free resources so |
| 73 | // that the pool Env may be closed. |
| 74 | func (p *TxnPool) Close() { |
| 75 | txn, ok := (*lmdb.Txn)(nil), true |
| 76 | for ok { |
| 77 | txn, ok = p.pool.Get().(*lmdb.Txn) |
| 78 | if ok { |
| 79 | txn.Abort() |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | // BeginTxn is analogous to the BeginTxn method on lmdb.Env but may only be |
| 85 | // used to create lmdb.Readonly transactions. Any call to BeginTxn that does |
| 86 | // not include lmdb.Readonly will return an error |
| 87 | func (p *TxnPool) BeginTxn(flags uint) (*lmdb.Txn, error) { |
| 88 | // We can only re-use transactions with exactly the same flags. So |
| 89 | // instead of masking flags with lmdb.Readonly an equality comparison |
| 90 | // is necessary. |
| 91 | if flags != lmdb.Readonly { |
| 92 | return nil, fmt.Errorf("flag lmdb.Readonly not provided") |
| 93 | } |
| 94 | |
| 95 | return p.beginReadonly() |
| 96 | } |
| 97 | |
| 98 | func (p *TxnPool) beginReadonly() (*lmdb.Txn, error) { |
| 99 | txn, ok := p.pool.Get().(*lmdb.Txn) |
| 100 | if !ok { |
| 101 | return p.env.BeginTxn(nil, lmdb.Readonly) |
| 102 | } |
| 103 | |
| 104 | // If txn was holding stale pages the call to txn.Renew() should release |
| 105 | // them when txn aquires a new lock (this is an implication made by the |
| 106 | // LMDB documentation as of 0.9.19). |
| 107 | err := txn.Renew() |
| 108 | if err != nil { |
| 109 | p.renewError(err) |
| 110 | |
| 111 | // Nothing we can do with txn now other than destroy it. |
| 112 | txn.Abort() |
| 113 | |
| 114 | // For now it's not clear what better handling of a renew error would |
| 115 | // entail so we just try to create a new transaction. It is assumed |
| 116 | // that it will fail with the same error... But maybe not? |
| 117 | return p.env.BeginTxn(nil, lmdb.Readonly) |
| 118 | } |
| 119 | |
| 120 | // Clear txn.Pooled to let a warning be emitted from the Txn finalizer |
| 121 | // again. And, make sure to clear RawRead to make the Txn appear like it |
| 122 | // was just allocated. |
| 123 | txn.RawRead = false |
| 124 | txn.Pooled = false |
| 125 | |
| 126 | return txn, nil |
| 127 | } |
| 128 | |
| 129 | func (p *TxnPool) renewError(err error) { |
| 130 | // TODO: |
| 131 | // When this is integrated directly in the lmdb package this can use |
| 132 | // the same logging functionality that the Txn finalizer uses. |
| 133 | log.Printf("lmdbpool: failed to renew transaction: %v", err) |
| 134 | } |
| 135 | |
| 136 | func (p *TxnPool) abortReadonly(txn *lmdb.Txn) { |
| 137 | if !returnTxnToPool { |
| 138 | // If the pool is disabled from race detection then we just abort the |
| 139 | // Txn instead of waiting for the finalizer. See the files put.go and |
| 140 | // putrace.go for more information. |
| 141 | txn.Abort() |
| 142 | return |
| 143 | } |
| 144 | |
| 145 | // We want to make sure that we handle updates in some way before we call |
| 146 | // either txn.ID() or p.getLastID() as both (can) incurr overhead. |
| 147 | if p.handlesUpdates() && txn.ID() < p.getLastID() { |
| 148 | ok, err := p.handleReadonly(txn, HandleOutstanding) |
| 149 | if err != nil { |
| 150 | // We attempted to renew the transaction but failed and the |
| 151 | // transaction was automatically aborted. |
| 152 | p.renewError(err) |
| 153 | return |
| 154 | } |
| 155 | if !ok { |
| 156 | // The transaction was aborted instead of being renewed. |
| 157 | return |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | // Don't waste cycles resetting RawRead here -- the cost be paid when the |
| 162 | // Txn is reused (if at all). All we need to do is set txn.Pooled to avoid |
| 163 | // any warning emitted from the Txn finalizer. |
| 164 | txn.Pooled = true |
| 165 | txn.Reset() |
| 166 | p.pool.Put(txn) |
| 167 | } |
| 168 | |
| 169 | func (p *TxnPool) handleReadonly(txn *lmdb.Txn, condition UpdateHandling) (renewed bool, err error) { |
| 170 | if p.UpdateHandling&condition == 0 { |
| 171 | return |
| 172 | } |
| 173 | |
| 174 | if p.UpdateHandling&HandleRenew != 0 { |
| 175 | err = txn.Renew() |
| 176 | if err != nil { |
| 177 | // There is not much to do with txn other than abort it. |
| 178 | txn.Abort() |
| 179 | } |
| 180 | return true, err |
| 181 | } |
| 182 | txn.Abort() |
| 183 | return false, nil |
| 184 | } |
| 185 | |
| 186 | // getLastID safely retrieves the value of p.lastid so routines operating on |
| 187 | // the sync.Pool know if a transaction can continue to be used without bloating |
| 188 | // the database. |
| 189 | func (p *TxnPool) getLastID() uintptr { |
| 190 | return atomic.LoadUintptr(&p.lastid) |
| 191 | } |
| 192 | |
| 193 | // CommitID sets the TxnPool's last-known transaction id to invalidate |
| 194 | // previously created lmdb.Readonly transactions and prevent their reuse. |
| 195 | // |
| 196 | // CommitID should only be called if p is not used to create/commit update |
| 197 | // transactions. |
| 198 | func (p *TxnPool) CommitID(id uintptr) { |
| 199 | if !p.handlesUpdates() { |
| 200 | return |
| 201 | } |
| 202 | |
| 203 | updated := false |
| 204 | |
| 205 | // As long as we think we are holding a newer id than lastid we keep trying |
| 206 | // to CAS until we see a newer id or the CAS succeeds. |
| 207 | lastid := atomic.LoadUintptr(&p.lastid) |
| 208 | for lastid < id { |
| 209 | if atomic.CompareAndSwapUintptr(&p.lastid, lastid, id) { |
| 210 | updated = true |
| 211 | break |
| 212 | } |
| 213 | lastid = atomic.LoadUintptr(&p.lastid) |
| 214 | } |
| 215 | |
| 216 | if updated && p.UpdateHandling&HandleIdle != 0 { |
| 217 | // In the case where a single transaction enters and exits the pool |
| 218 | // repeatedly we are actually doing a disservice to the application because |
| 219 | // it will need to allocate more Txns than it would otherwise if we were to |
| 220 | // terminate them. Renewing them preemptively runs the risk of wasting |
| 221 | // resources. |
| 222 | // |
| 223 | // The questions surrounding this require more benchmarks and real world |
| 224 | // experimentation. |
| 225 | |
| 226 | // NOTE: |
| 227 | // If the cost of creating a goroutine here is disruptive in some way |
| 228 | // it would be worth experimenting to see if sending over a channel to |
| 229 | // notify a worker goroutine would improve performance or other runtime |
| 230 | // characteristics. |
| 231 | go p.handleIdle() |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | func (p *TxnPool) handleIdle() { |
| 236 | // We don't want multiple handleIdle goroutines to run simultaneously. But |
| 237 | // we don't really want them to block and run serially because the running |
| 238 | // one will probably do the work of the waiting one. So we just attempt to |
| 239 | // CAS a guarding value and continue if the we succeeded (ensuring that we |
| 240 | // reset the value with defer). |
| 241 | if !atomic.CompareAndSwapUintptr(&p.idleGuard, 0, 1) { |
| 242 | return |
| 243 | } |
| 244 | // Don't CAS when we reset. Just reset. It will make sure that handleIdle |
| 245 | // can run again. |
| 246 | defer atomic.StoreUintptr(&p.idleGuard, 0) |
| 247 | |
| 248 | var txnPutBack *lmdb.Txn |
| 249 | for { |
| 250 | txn, ok := p.pool.Get().(*lmdb.Txn) |
| 251 | if txnPutBack != nil { |
| 252 | // If we had a Txn to put back into the pool we wait so that we |
| 253 | // don't grab the one we just saw. |
| 254 | p.pool.Put(txnPutBack) |
| 255 | txnPutBack = nil |
| 256 | } |
| 257 | if !ok { |
| 258 | // No Txn objects in the pool, so we just break out. |
| 259 | break |
| 260 | } |
| 261 | |
| 262 | // NOTE: |
| 263 | // We should not cache p.getLastID or take it as an argument because |
| 264 | // this function can run concurrent with updates which are getting |
| 265 | // committed. |
| 266 | if txn.ID() >= p.getLastID() { |
| 267 | // This transaction is not holding stale pages. We just assume that we |
| 268 | // are done now and stop trying to find more transactions. |
| 269 | p.pool.Put(txn) |
| 270 | break |
| 271 | } |
| 272 | |
| 273 | // This transaction has stale pages and must be dealt with |
| 274 | ok, err := p.handleReadonly(txn, HandleIdle) |
| 275 | if err != nil { |
| 276 | // We attempted to renew the transaction but failed and the |
| 277 | // transaction was automatically aborted. |
| 278 | p.renewError(err) |
| 279 | continue |
| 280 | } |
| 281 | if ok { |
| 282 | // txn was renewed so we can put it back in the pool. |
| 283 | txnPutBack = txn |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | // handlesUpdates returns if updates are handled in any way. |
| 289 | func (p *TxnPool) handlesUpdates() bool { |
| 290 | return p.UpdateHandling&HandleAll != 0 |
| 291 | } |
| 292 | |
| 293 | // Abort aborts the txn and allows it to be reused if possible. Abort must |
| 294 | // only be passed lmdb.Txn objects which it returned from a call to BeginTxn. |
| 295 | // Aborting a transaction created through other means will have undefined |
| 296 | // results. |
| 297 | func (p *TxnPool) Abort(txn *lmdb.Txn) { |
| 298 | p.abortReadonly(txn) |
| 299 | } |
| 300 | |
| 301 | // Update is analogous to the Update method on lmdb.Env. |
| 302 | func (p *TxnPool) Update(fn lmdb.TxnOp) error { |
| 303 | var id uintptr |
| 304 | err := p.env.Update(func(txn *lmdb.Txn) (err error) { |
| 305 | err = fn(txn) |
| 306 | if err != nil { |
| 307 | return err |
| 308 | } |
| 309 | |
| 310 | // Save the transaction identifier once we know fn succeeded so that |
| 311 | // the p.lastid field can be set appropriately once the txn has |
| 312 | // committed successfully. |
| 313 | id = txn.ID() |
| 314 | |
| 315 | return nil |
| 316 | }) |
| 317 | if err != nil { |
| 318 | return err |
| 319 | } |
| 320 | |
| 321 | p.CommitID(id) |
| 322 | |
| 323 | return nil |
| 324 | } |
| 325 | |
| 326 | // View is analogous to the View method on lmdb.Env. |
| 327 | func (p *TxnPool) View(fn lmdb.TxnOp) error { |
| 328 | txn, err := p.beginReadonly() |
| 329 | if err != nil { |
| 330 | return err |
| 331 | } |
| 332 | defer p.abortReadonly(txn) |
| 333 | return txn.RunOp(fn, false) |
| 334 | } |