From bd9145dc8c512675ed6561ed89b57ba6ecc74280 Mon Sep 17 00:00:00 2001 From: Alejandro Lopez Date: Mon, 14 Aug 2023 10:54:09 +0300 Subject: [PATCH] [#598] Fix use-after-close bug in badger writecache Signed-off-by: Alejandro Lopez --- .../writecache/writecachebadger/flush.go | 7 +++++++ .../writecache/writecachebadger/gc.go | 8 ++++++++ 2 files changed, 15 insertions(+) diff --git a/pkg/local_object_storage/writecache/writecachebadger/flush.go b/pkg/local_object_storage/writecache/writecachebadger/flush.go index fec6ecf88..8630026cd 100644 --- a/pkg/local_object_storage/writecache/writecachebadger/flush.go +++ b/pkg/local_object_storage/writecache/writecachebadger/flush.go @@ -80,6 +80,13 @@ func (c *cache) flushSmallObjects() { continue } + // Using the db after Close will panic and badger won't wait for outstanding txs, + // so we need to check manually. + if c.db.IsClosed() { + c.modeMtx.RUnlock() + return + } + _ = c.db.View(func(tx *badger.Txn) error { it := tx.NewIterator(badger.DefaultIteratorOptions) defer it.Close() diff --git a/pkg/local_object_storage/writecache/writecachebadger/gc.go b/pkg/local_object_storage/writecache/writecachebadger/gc.go index 51d3e9763..8432a9c04 100644 --- a/pkg/local_object_storage/writecache/writecachebadger/gc.go +++ b/pkg/local_object_storage/writecache/writecachebadger/gc.go @@ -20,6 +20,14 @@ func (c *cache) runGCLoop() { case <-c.closeCh: return case <-t.C: + // This serves to synchronize the c.db field when changing mode as well. + c.modeMtx.RLock() + ro := c.readOnly() + c.modeMtx.RUnlock() + if ro { + continue + } + // 0.5 is the recommended value so that write amplification of the value log is 2. // See https://pkg.go.dev/github.com/dgraph-io/badger/v4#DB.RunValueLogGC for more info. for c.db.RunValueLogGC(0.5) == nil {