Skip to content

Commit

Permalink
Fix race when opening DB for first time (micro#1691)
Browse files Browse the repository at this point in the history
  • Loading branch information
domwong committed Jun 12, 2020
1 parent 86dfcb8 commit aec27be
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions store/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
Expand All @@ -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
}
Expand Down

0 comments on commit aec27be

Please sign in to comment.