This repository has been archived by the owner on Apr 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 35
/
fslock_test.go
328 lines (277 loc) · 7.38 KB
/
fslock_test.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package fslock_test
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
gc "gopkg.in/check.v1"
"github.com/juju/fslock"
)
func Test(t *testing.T) {
gc.TestingT(t)
}
const (
shortWait = 10 * time.Millisecond
longWait = 10 * shortWait
)
type fslockSuite struct{}
var _ = gc.Suite(&fslockSuite{})
func (s *fslockSuite) TestLockNoContention(c *gc.C) {
path := filepath.Join(c.MkDir(), "testing")
lock := fslock.New(path)
started := make(chan struct{})
acquired := make(chan struct{})
go func() {
close(started)
err := lock.Lock()
close(acquired)
c.Assert(err, gc.IsNil)
}()
select {
case <-started:
// good, goroutine started.
case <-time.After(shortWait * 2):
c.Fatalf("timeout waiting for goroutine to start")
}
select {
case <-acquired:
// got the lock. good.
case <-time.After(shortWait * 2):
c.Fatalf("Timed out waiting for lock acquisition.")
}
err := lock.Unlock()
c.Assert(err, gc.IsNil)
}
func (s *fslockSuite) TestLockBlocks(c *gc.C) {
path := filepath.Join(c.MkDir(), "testing")
lock := fslock.New(path)
kill := make(chan struct{})
// this will block until the other process has the lock.
procDone := LockFromAnotherProc(c, path, kill)
defer func() {
close(kill)
// now wait for the other process to exit so the file will be unlocked.
select {
case <-procDone:
case <-time.After(time.Second):
}
}()
started := make(chan struct{})
acquired := make(chan struct{})
go func() {
close(started)
err := lock.Lock()
close(acquired)
lock.Unlock()
c.Assert(err, gc.IsNil)
}()
select {
case <-started:
// good, goroutine started.
case <-time.After(shortWait * 2):
c.Fatalf("timeout waiting for goroutine to start")
}
// Waiting for something not to happen is inherently hard...
select {
case <-acquired:
c.Fatalf("Unexpected lock acquisition")
case <-time.After(shortWait * 2):
// all good.
}
}
func (s *fslockSuite) TestTryLock(c *gc.C) {
lock := fslock.New(filepath.Join(c.MkDir(), "testing"))
err := lock.TryLock()
c.Assert(err, gc.IsNil)
lock.Unlock()
}
func (s *fslockSuite) TestTryLockNoBlock(c *gc.C) {
path := filepath.Join(c.MkDir(), "testing")
lock := fslock.New(path)
kill := make(chan struct{})
// this will block until the other process has the lock.
procDone := LockFromAnotherProc(c, path, kill)
defer func() {
close(kill)
// now wait for the other process to exit so the file will be unlocked.
select {
case <-procDone:
case <-time.After(time.Second):
}
}()
started := make(chan struct{})
result := make(chan error)
go func() {
close(started)
result <- lock.TryLock()
}()
select {
case <-started:
// good, goroutine started.
case <-time.After(shortWait):
c.Fatalf("timeout waiting for goroutine to start")
}
// Wait for trylock to fail.
select {
case err := <-result:
// yes, I know this is redundant with the assert below, but it makes the
// failed test message clearer.
if err == nil {
c.Fatalf("lock succeeded, but should have errored out")
}
// This should be the error from trylock failing.
c.Assert(err, gc.Equals, fslock.ErrLocked)
case <-time.After(shortWait):
c.Fatalf("took too long to fail trylock")
}
}
func (s *fslockSuite) TestUnlockedWithTimeout(c *gc.C) {
lock := fslock.New(filepath.Join(c.MkDir(), "testing"))
err := lock.LockWithTimeout(shortWait)
c.Assert(err, gc.IsNil)
lock.Unlock()
}
func (s *fslockSuite) TestLockWithTimeout(c *gc.C) {
path := filepath.Join(c.MkDir(), "testing")
lock := fslock.New(path)
defer lock.Unlock()
kill := make(chan struct{})
// this will block until the other process has the lock.
procDone := LockFromAnotherProc(c, path, kill)
defer func() {
close(kill)
// now wait for the other process to exit so the file will be unlocked.
select {
case <-procDone:
case <-time.After(time.Second):
}
}()
started := make(chan struct{})
result := make(chan error)
go func() {
close(started)
result <- lock.LockWithTimeout(shortWait)
}()
select {
case <-started:
// good, goroutine started.
case <-time.After(shortWait * 2):
c.Fatalf("timeout waiting for goroutine to start")
}
// Wait for timeout.
select {
case err := <-result:
// yes, I know this is redundant with the assert below, but it makes the
// failed test message clearer.
if err == nil {
c.Fatalf("lock succeeded, but should have timed out")
}
// This should be the error from the lock timing out.
c.Assert(err, gc.Equals, fslock.ErrTimeout)
case <-time.After(shortWait * 2):
c.Fatalf("lock took too long to timeout")
}
}
func (s *fslockSuite) TestStress(c *gc.C) {
const lockAttempts = 200
const concurrentLocks = 10
var counter = new(int64)
// Use atomics to update lockState to make sure the lock isn't held by
// someone else. A value of 1 means locked, 0 means unlocked.
var lockState = new(int32)
var wg sync.WaitGroup
dir := c.MkDir()
var stress = func(name string) {
defer wg.Done()
lock := fslock.New(filepath.Join(dir, "testing"))
for i := 0; i < lockAttempts; i++ {
err := lock.Lock()
c.Assert(err, gc.IsNil)
state := atomic.AddInt32(lockState, 1)
c.Assert(state, gc.Equals, int32(1))
// Tell the go routine scheduler to give a slice to someone else
// while we have this locked.
runtime.Gosched()
// need to decrement prior to unlock to avoid the race of someone
// else grabbing the lock before we decrement the state.
atomic.AddInt32(lockState, -1)
err = lock.Unlock()
c.Assert(err, gc.IsNil)
// increment the general counter
atomic.AddInt64(counter, 1)
}
}
for i := 0; i < concurrentLocks; i++ {
wg.Add(1)
go stress(fmt.Sprintf("Lock %d", i))
}
wg.Wait()
c.Assert(*counter, gc.Equals, int64(lockAttempts*concurrentLocks))
}
// LockFromAnotherProc will launch a process and block until that process has
// created the lock file. If we time out waiting for the other process to take
// the lock, this function will fail the current test.
func LockFromAnotherProc(c *gc.C, path string, kill chan struct{}) (done chan struct{}) {
cmd := exec.Command(os.Args[0], "-test.run", "TestLockFromOtherProcess")
cmd.Env = append(
// We must preserve os.Environ() on Windows,
// or the subprocess will fail in weird and
// wonderful ways.
os.Environ(),
"FSLOCK_TEST_HELPER_WANTED=1",
"FSLOCK_TEST_HELPER_PATH="+path,
)
if err := cmd.Start(); err != nil {
c.Fatalf("error starting other proc: %v", err)
}
done = make(chan struct{})
go func() {
cmd.Wait()
close(done)
}()
go func() {
select {
case <-kill:
// this may fail, but there's not much we can do about it
_ = cmd.Process.Kill()
case <-done:
}
}()
for x := 0; x < 10; x++ {
time.Sleep(shortWait)
if _, err := os.Stat(path); err == nil {
// file created by other process, let's continue
break
}
if x == 9 {
c.Fatalf("timed out waiting for other process to start")
}
}
return done
}
func TestLockFromOtherProcess(t *testing.T) {
if os.Getenv("FSLOCK_TEST_HELPER_WANTED") == "" {
return
}
filename := os.Getenv("FSLOCK_TEST_HELPER_PATH")
lock := fslock.New(filename)
err := lock.Lock()
if err != nil {
fmt.Fprintf(os.Stderr, "error locking %q: %v", filename, err)
os.Exit(1)
}
time.Sleep(longWait)
err = lock.Unlock()
if err != nil {
fmt.Fprintf(os.Stderr, "error unlocking %q: %v", filename, err)
os.Exit(1)
}
os.Exit(0)
}