forked from deis/builder
/
lock.go
101 lines (87 loc) · 2.29 KB
/
lock.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
91
92
93
94
95
96
97
98
99
100
101
package sshd
import (
"errors"
"fmt"
"sync"
"time"
)
var (
errAlreadyLocked = errors.New("already locked")
)
// RepositoryLock interface that allows the creation of a lock associated
// with a repository name to avoid simultaneous git operations.
type RepositoryLock interface {
// Lock acquires a lock for a repository.
Lock(repoName string) error
// Unlock releases the lock for a repository or returns an error if the specified
// name doesn't exist.
Unlock(repoName string) error
// Timeout returns the time duration for which it has to hold the lock
Timeout() time.Duration
}
func wrapInLock(lck RepositoryLock, repoName string, fn func() error) error {
if err := lck.Lock(repoName); err != nil {
return errAlreadyLocked
}
timer := time.NewTimer(lck.Timeout())
defer timer.Stop()
doneCh := make(chan struct{})
fnCh := make(chan error)
go func() {
err := fn()
select {
case fnCh <- err:
case <-doneCh:
}
}()
defer lck.Unlock(repoName)
select {
case <-timer.C:
defer close(doneCh)
return fmt.Errorf("%s lock exceeded timeout", repoName)
case err := <-fnCh:
return err
}
}
// NewInMemoryRepositoryLock returns a new instance of a RepositoryLock.
func NewInMemoryRepositoryLock(timeout time.Duration) RepositoryLock {
return &inMemoryRepoLock{
mutex: &sync.RWMutex{},
dataMap: make(map[string]bool),
timeout: timeout,
}
}
type inMemoryRepoLock struct {
mutex *sync.RWMutex
dataMap map[string]bool
timeout time.Duration
}
// Lock acquires a lock associated with the specified name.
func (rl *inMemoryRepoLock) Lock(repoName string) error {
rl.mutex.Lock()
defer rl.mutex.Unlock()
_, exists := rl.dataMap[repoName]
if !exists {
rl.dataMap[repoName] = true
return nil
}
return fmt.Errorf("repository %q already locked", repoName)
}
// Unlock releases the lock for a repository or returns an error if the specified name doesn't
// exist.
func (rl *inMemoryRepoLock) Unlock(repoName string) error {
rl.mutex.Lock()
defer rl.mutex.Unlock()
locked, exists := rl.dataMap[repoName]
if !exists {
return fmt.Errorf("repository %q not found", repoName)
}
if locked {
delete(rl.dataMap, repoName)
}
return nil
}
// Timeout returns the time duration for which a gitpush should hold the lock
func (rl *inMemoryRepoLock) Timeout() time.Duration {
return rl.timeout
}