forked from deis/builder
/
lock.go
67 lines (56 loc) · 1.92 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
package sshd
import (
"fmt"
"sync"
"time"
)
// 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. In the case the repository is already locked
// it waits until a timeout to get the lock. If it was not possible to get the
// lock after the timeout an error is returned.
Lock(repoName string, timeout time.Duration) error
// Unlock releases the lock for a repository or returns an error if the specified
// name doesn't exist. In the case the repository is already locked it waits until
// a timeout to get the lock. If it was not possible to get the lock after the timeout
// an error is returned.
Unlock(repoName string, timeout time.Duration) error
}
// NewInMemoryRepositoryLock returns a new instance of a RepositoryLock.
func NewInMemoryRepositoryLock() RepositoryLock {
return &inMemoryRepoLock{
mutex: &sync.RWMutex{},
dataMap: make(map[string]bool),
}
}
type inMemoryRepoLock struct {
mutex *sync.RWMutex
dataMap map[string]bool
}
// Lock aquires a lock associated with the specified name.
// This implementation ignores the timeout.
func (rl *inMemoryRepoLock) Lock(repoName string, timeout time.Duration) 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. This implementation ignores the timeout.
func (rl *inMemoryRepoLock) Unlock(repoName string, timeout time.Duration) 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
}