generated from keboola/template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fslocker.go
90 lines (77 loc) · 2.05 KB
/
fslocker.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package testproject
import (
"fmt"
"os"
"path/filepath"
"strconv"
"sync"
"github.com/gofrs/flock"
)
// fsLocker is factory constructing fsProjectLockers.
type fsLocker struct {
locksDir string
}
func newFsLocker() (*fsLocker, error) {
// Get locks dir name
lockDirName, found := os.LookupEnv(TestKbcProjectsLockDirNameKey)
if !found {
// Default value
lockDirName = ".keboola-as-code-locks"
}
// Create locks dir if not exists
locksDir := filepath.Join(os.TempDir(), lockDirName)
if err := os.MkdirAll(locksDir, 0o700); err != nil {
return nil, fmt.Errorf(`cannot create locks dir: %w`, err)
}
return &fsLocker{
locksDir: locksDir,
}, nil
}
// fsProjectLocker is implementation of locker using flock and mutex to perform mutual exclusion of project access on both process and goroutine level.
type fsProjectLocker struct {
fsLocker *fsLocker
projectID string
lock *sync.Mutex // lock between goroutines
fsLock *flock.Flock // fsLock between processes
locked bool
}
func (fl *fsLocker) newForProject(p *Project) projectLocker {
// Get lock file name
projectID := p.definition.Host + `-` + strconv.Itoa(p.definition.ProjectID) + `.lock`
lockPath := filepath.Join(fl.locksDir, projectID)
fsLock := flock.New(lockPath)
return &fsProjectLocker{
fsLocker: fl,
projectID: projectID,
lock: &sync.Mutex{},
fsLock: fsLock,
}
}
func (fl *fsProjectLocker) tryLock() bool {
// This FS lock works between processes
if locked, err := fl.fsLock.TryLock(); err != nil {
panic(fmt.Errorf(`cannot lock test project: %w`, err))
} else if !locked {
// Busy
return false
}
// This lock works inside one process, between goroutines
if !fl.lock.TryLock() {
// Busy
return false
}
// Locked
fl.locked = true
return true
}
// unlock project if it is no more needed in test.
func (fl *fsProjectLocker) unlock() {
defer fl.lock.Unlock()
fl.locked = false
if err := fl.fsLock.Unlock(); err != nil {
panic(fmt.Errorf(`cannot unlock test project: %w`, err))
}
}
func (fl *fsProjectLocker) isLocked() bool {
return fl.locked
}