From eda338a3190d78625d85d4e2adad87373bd7e824 Mon Sep 17 00:00:00 2001 From: Janos Guljas Date: Mon, 14 Jan 2019 13:52:33 +0100 Subject: [PATCH] swarm/storage/localstore: fix a race in testDB_collectGarbageWorker --- swarm/storage/localstore/gc.go | 1 + swarm/storage/localstore/gc_test.go | 36 ++++++++++++++++------------- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/swarm/storage/localstore/gc.go b/swarm/storage/localstore/gc.go index 00e02d8bca..5d9f08ccd8 100644 --- a/swarm/storage/localstore/gc.go +++ b/swarm/storage/localstore/gc.go @@ -159,6 +159,7 @@ func (db *DB) getGCSize() (count int64) { func (db *DB) triggerGarbageCollection() { select { case db.collectGarbageTrigger <- struct{}{}: + case <-db.close: default: } } diff --git a/swarm/storage/localstore/gc_test.go b/swarm/storage/localstore/gc_test.go index da32b9dcbb..15400a03bb 100644 --- a/swarm/storage/localstore/gc_test.go +++ b/swarm/storage/localstore/gc_test.go @@ -29,12 +29,7 @@ import ( // TestDB_collectGarbageWorker tests garbage collection runs // by uploading and syncing a number of chunks. func TestDB_collectGarbageWorker(t *testing.T) { - db, cleanupFunc := newTestDB(t, &Options{ - Capacity: 100, - }) - defer cleanupFunc() - - testDB_collectGarbageWorker(t, db) + testDB_collectGarbageWorker(t) } // TestDB_collectGarbageWorker_multipleBatches tests garbage @@ -46,20 +41,12 @@ func TestDB_collectGarbageWorker_multipleBatches(t *testing.T) { defer func(s int64) { gcBatchSize = s }(gcBatchSize) gcBatchSize = 2 - db, cleanupFunc := newTestDB(t, &Options{ - Capacity: 100, - }) - defer cleanupFunc() - - testDB_collectGarbageWorker(t, db) + testDB_collectGarbageWorker(t) } // testDB_collectGarbageWorker is a helper test function to test // garbage collection runs by uploading and syncing a number of chunks. -func testDB_collectGarbageWorker(t *testing.T, db *DB) { - uploader := db.NewPutter(ModePutUpload) - syncer := db.NewSetter(ModeSetSync) - +func testDB_collectGarbageWorker(t *testing.T) { chunkCount := 150 testHookCollectGarbageChan := make(chan int64) @@ -67,6 +54,14 @@ func testDB_collectGarbageWorker(t *testing.T, db *DB) { testHookCollectGarbageChan <- collectedCount })() + db, cleanupFunc := newTestDB(t, &Options{ + Capacity: 100, + }) + defer cleanupFunc() + + uploader := db.NewPutter(ModePutUpload) + syncer := db.NewSetter(ModeSetSync) + addrs := make([]storage.Address, 0) // upload random chunks @@ -121,6 +116,15 @@ func testDB_collectGarbageWorker(t *testing.T, db *DB) { t.Fatal(err) } }) + + // cleanup: drain the last testHookCollectGarbageChan + // element before calling deferred functions not to block + // collectGarbageWorker loop, preventing the race in + // setting testHookCollectGarbage function + select { + case <-testHookCollectGarbageChan: + default: + } } // TestDB_collectGarbageWorker_withRequests is a helper test function