forked from hootsuite/atlantis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrent_run_locker.go
43 lines (36 loc) · 1.08 KB
/
concurrent_run_locker.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
package server
import (
"fmt"
"sync"
)
// ConcurrentRunLocker is used to prevent multiple runs and commands from occurring at the same time for a single
// repo, pull, and environment
type ConcurrentRunLocker struct {
mutex sync.Mutex
locks map[string]interface{}
}
func NewConcurrentRunLocker() *ConcurrentRunLocker {
return &ConcurrentRunLocker{
locks: make(map[string]interface{}),
}
}
// TryLock returns true if you acquired the lock and false if someone else already has the lock
func (c *ConcurrentRunLocker) TryLock(repoFullName string, env string, pullNum int) bool {
c.mutex.Lock()
defer c.mutex.Unlock()
key := c.key(repoFullName, env, pullNum)
if _, ok := c.locks[key]; !ok {
c.locks[key] = true
return true
}
return false
}
// Unlock unlocks the repo and environment
func (c *ConcurrentRunLocker) Unlock(repoFullName, env string, pullNum int) {
c.mutex.Lock()
defer c.mutex.Unlock()
delete(c.locks, c.key(repoFullName, env, pullNum))
}
func (c *ConcurrentRunLocker) key(repo string, env string, pull int) string {
return fmt.Sprintf("%s/%s/%d", repo, env, pull)
}