forked from vmware-archive/atc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lock.go
269 lines (209 loc) · 4.96 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package lock
import (
"database/sql"
"errors"
"fmt"
"hash/crc32"
"strconv"
"strings"
"sync"
"code.cloudfoundry.org/lager"
)
const (
LockTypeResourceConfigChecking = iota
LockTypeBuildTracking
LockTypePipelineScheduling
LockTypeBatch
LockTypeVolumeCreating
LockTypeContainerCreating
)
var ErrLostLock = errors.New("lock was lost while held, possibly due to connection breakage")
func NewBuildTrackingLockID(buildID int) LockID {
return LockID{LockTypeBuildTracking, buildID}
}
func NewResourceConfigCheckingLockID(resourceConfigID int) LockID {
return LockID{LockTypeResourceConfigChecking, resourceConfigID}
}
func NewPipelineSchedulingLockLockID(pipelineID int) LockID {
return LockID{LockTypePipelineScheduling, pipelineID}
}
func NewTaskLockID(taskName string) LockID {
return LockID{LockTypeBatch, lockIDFromString(taskName)}
}
func NewVolumeCreatingLockID(volumeID int) LockID {
return LockID{LockTypeVolumeCreating, volumeID}
}
func NewContainerCreatingLockID(containerID int) LockID {
return LockID{LockTypeContainerCreating, containerID}
}
//go:generate counterfeiter . LockFactory
type LockFactory interface {
Acquire(logger lager.Logger, ids LockID) (Lock, bool, error)
}
type lockFactory struct {
db LockDB
locks lockRepo
acquireMutex *sync.Mutex
}
func NewLockFactory(conn *sql.DB) LockFactory {
return &lockFactory{
db: &lockDB{
conn: conn,
mutex: &sync.Mutex{},
},
locks: lockRepo{
locks: map[string]bool{},
mutex: &sync.Mutex{},
},
acquireMutex: &sync.Mutex{},
}
}
func NewTestLockFactory(db LockDB) LockFactory {
return &lockFactory{
db: db,
locks: lockRepo{
locks: map[string]bool{},
mutex: &sync.Mutex{},
},
acquireMutex: &sync.Mutex{},
}
}
func (f *lockFactory) Acquire(logger lager.Logger, id LockID) (Lock, bool, error) {
l := &lock{
logger: logger,
db: f.db,
id: id,
locks: f.locks,
acquireMutex: f.acquireMutex,
}
acquired, err := l.Acquire()
if err != nil {
return nil, false, err
}
if !acquired {
return nil, false, nil
}
return l, true, nil
}
//go:generate counterfeiter . Lock
type Lock interface {
Release() error
}
//go:generate counterfeiter . LockDB
type LockDB interface {
Acquire(id LockID) (bool, error)
Release(id LockID) (bool, error)
}
type lock struct {
id LockID
logger lager.Logger
db LockDB
locks lockRepo
acquireMutex *sync.Mutex
}
func (l *lock) Acquire() (bool, error) {
l.acquireMutex.Lock()
defer l.acquireMutex.Unlock()
logger := l.logger.Session("acquire", lager.Data{"id": l.id})
if l.locks.IsRegistered(l.id) {
logger.Debug("not-acquired-already-held-locally")
return false, nil
}
acquired, err := l.db.Acquire(l.id)
if err != nil {
logger.Error("failed-to-register-in-db", err)
return false, err
}
if !acquired {
logger.Debug("not-acquired-already-held-in-db")
return false, nil
}
l.locks.Register(l.id)
logger.Debug("acquired")
return true, nil
}
func (l *lock) Release() error {
logger := l.logger.Session("release", lager.Data{"id": l.id})
released, err := l.db.Release(l.id)
if err != nil {
logger.Error("failed-to-release-in-db-but-continuing-anyway", err)
}
l.locks.Unregister(l.id)
if !released {
logger.Error("failed-to-release", ErrLostLock)
return ErrLostLock
}
logger.Debug("released")
return nil
}
type lockDB struct {
conn *sql.DB
mutex *sync.Mutex
}
func (db *lockDB) Acquire(id LockID) (bool, error) {
db.mutex.Lock()
defer db.mutex.Unlock()
var acquired bool
err := db.conn.QueryRow(`SELECT pg_try_advisory_lock(`+id.toDBParams()+`)`, id.toDBArgs()...).Scan(&acquired)
if err != nil {
return false, err
}
return acquired, nil
}
func (db *lockDB) Release(id LockID) (bool, error) {
db.mutex.Lock()
defer db.mutex.Unlock()
var released bool
err := db.conn.QueryRow(`SELECT pg_advisory_unlock(`+id.toDBParams()+`)`, id.toDBArgs()...).Scan(&released)
if err != nil {
return false, err
}
return released, nil
}
type lockRepo struct {
locks map[string]bool
mutex *sync.Mutex
}
func (lr lockRepo) IsRegistered(id LockID) bool {
lr.mutex.Lock()
defer lr.mutex.Unlock()
if _, ok := lr.locks[id.toKey()]; ok {
return true
}
return false
}
func (lr lockRepo) Register(id LockID) {
lr.mutex.Lock()
defer lr.mutex.Unlock()
lr.locks[id.toKey()] = true
}
func (lr lockRepo) Unregister(id LockID) {
lr.mutex.Lock()
defer lr.mutex.Unlock()
delete(lr.locks, id.toKey())
}
type LockID []int
func (l LockID) toKey() string {
s := []string{}
for i := range l {
s = append(s, strconv.Itoa(l[i]))
}
return strings.Join(s, "+")
}
func (l LockID) toDBParams() string {
s := []string{}
for i := range l {
s = append(s, fmt.Sprintf("$%d", i+1))
}
return strings.Join(s, ",")
}
func (l LockID) toDBArgs() []interface{} {
result := []interface{}{}
for i := range l {
result = append(result, l[i])
}
return result
}
func lockIDFromString(taskName string) int {
return int(int32(crc32.ChecksumIEEE([]byte(taskName))))
}