From aec27be9b4ae94cdff50128fb6f2b60d55015bcc Mon Sep 17 00:00:00 2001 From: Dominic Wong Date: Mon, 8 Jun 2020 16:19:22 +0100 Subject: [PATCH] Fix race when opening DB for first time (#1691) --- store/file/file.go | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/store/file/file.go b/store/file/file.go index 71bd0f83..e6856289 100644 --- a/store/file/file.go +++ b/store/file/file.go @@ -105,7 +105,6 @@ func (f *fileStore) getDB(database, table string) (*fileHandle, error) { } k := key(database, table) - f.RLock() fd, ok := f.handles[k] f.RUnlock() @@ -115,6 +114,13 @@ func (f *fileStore) getDB(database, table string) (*fileHandle, error) { return fd, nil } + // double check locking + f.Lock() + defer f.Unlock() + if fd, ok := f.handles[k]; ok { + return fd, nil + } + // create a directory /tmp/micro dir := filepath.Join(DefaultDir, database) // create the database handle @@ -125,18 +131,16 @@ func (f *fileStore) getDB(database, table string) (*fileHandle, error) { dbPath := filepath.Join(dir, fname) // create new db handle + // Bolt DB only allows one process to open the file R/W so make sure we're doing this under a lock db, err := bolt.Open(dbPath, 0700, &bolt.Options{Timeout: 5 * time.Second}) if err != nil { return nil, err } - - f.Lock() fd = &fileHandle{ key: k, db: db, } f.handles[k] = fd - f.Unlock() return fd, nil }