File: lock_test.go

package info (click to toggle)
consul 1.5.2+dfsg1-12
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 41,656 kB
  • sloc: sh: 2,887; makefile: 127; ruby: 75; cpp: 58; xml: 36
file content (582 lines) | stat: -rw-r--r-- 12,206 bytes parent folder | download | duplicates (4)
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
package api

import (
	"log"
	"net/http"
	"net/http/httptest"
	"net/http/httputil"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/hashicorp/consul/sdk/testutil/retry"
)

func createTestLock(t *testing.T, c *Client, key string) (*Lock, *Session) {
	t.Helper()
	session := c.Session()

	se := &SessionEntry{
		Name:     DefaultLockSessionName,
		TTL:      DefaultLockSessionTTL,
		Behavior: SessionBehaviorDelete,
	}
	id, _, err := session.CreateNoChecks(se, nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	opts := &LockOptions{
		Key:         key,
		Session:     id,
		SessionName: se.Name,
		SessionTTL:  se.TTL,
	}
	lock, err := c.LockOpts(opts)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	return lock, session
}

func TestAPI_LockLockUnlock(t *testing.T) {
	t.Parallel()
	c, s := makeClientWithoutConnect(t)
	defer s.Stop()

	lock, session := createTestLock(t, c, "test/lock")
	defer session.Destroy(lock.opts.Session, nil)

	// Initial unlock should fail
	err := lock.Unlock()
	if err != ErrLockNotHeld {
		t.Fatalf("err: %v", err)
	}

	// Should work
	leaderCh, err := lock.Lock(nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if leaderCh == nil {
		t.Fatalf("not leader")
	}

	// Double lock should fail
	_, err = lock.Lock(nil)
	if err != ErrLockHeld {
		t.Fatalf("err: %v", err)
	}

	// Should be leader
	select {
	case <-leaderCh:
		t.Fatalf("should be leader")
	default:
	}

	// Initial unlock should work
	err = lock.Unlock()
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	// Double unlock should fail
	err = lock.Unlock()
	if err != ErrLockNotHeld {
		t.Fatalf("err: %v", err)
	}

	// Should lose leadership
	select {
	case <-leaderCh:
	case <-time.After(time.Second):
		t.Fatalf("should not be leader")
	}
}

func TestAPI_LockForceInvalidate(t *testing.T) {
	t.Parallel()
	c, s := makeClientWithoutConnect(t)
	defer s.Stop()

	retry.Run(t, func(r *retry.R) {
		lock, session := createTestLock(t, c, "test/lock")
		defer session.Destroy(lock.opts.Session, nil)

		// Should work
		leaderCh, err := lock.Lock(nil)
		if err != nil {
			t.Fatalf("err: %v", err)
		}
		if leaderCh == nil {
			t.Fatalf("not leader")
		}
		defer lock.Unlock()

		go func() {
			// Nuke the session, simulator an operator invalidation
			// or a health check failure
			session := c.Session()
			session.Destroy(lock.lockSession, nil)
		}()

		// Should loose leadership
		select {
		case <-leaderCh:
		case <-time.After(time.Second):
			t.Fatalf("should not be leader")
		}
	})
}

func TestAPI_LockDeleteKey(t *testing.T) {
	t.Parallel()
	c, s := makeClientWithoutConnect(t)
	defer s.Stop()

	// This uncovered some issues around special-case handling of low index
	// numbers where it would work with a low number but fail for higher
	// ones, so we loop this a bit to sweep the index up out of that
	// territory.
	for i := 0; i < 10; i++ {
		func() {
			lock, session := createTestLock(t, c, "test/lock")
			defer session.Destroy(lock.opts.Session, nil)

			// Should work
			leaderCh, err := lock.Lock(nil)
			if err != nil {
				t.Fatalf("err: %v", err)
			}
			if leaderCh == nil {
				t.Fatalf("not leader")
			}
			defer lock.Unlock()

			go func() {
				// Nuke the key, simulate an operator intervention
				kv := c.KV()
				kv.Delete("test/lock", nil)
			}()

			// Should loose leadership
			select {
			case <-leaderCh:
			case <-time.After(10 * time.Second):
				t.Fatalf("should not be leader")
			}
		}()
	}
}

func TestAPI_LockContend(t *testing.T) {
	t.Parallel()
	c, s := makeClientWithoutConnect(t)
	defer s.Stop()

	wg := &sync.WaitGroup{}
	acquired := make([]bool, 3)
	for idx := range acquired {
		wg.Add(1)
		go func(idx int) {
			defer wg.Done()
			lock, session := createTestLock(t, c, "test/lock")
			defer session.Destroy(lock.opts.Session, nil)

			// Should work eventually, will contend
			leaderCh, err := lock.Lock(nil)
			if err != nil {
				t.Fatalf("err: %v", err)
			}
			if leaderCh == nil {
				t.Fatalf("not leader")
			}
			defer lock.Unlock()
			log.Printf("Contender %d acquired", idx)

			// Set acquired and then leave
			acquired[idx] = true
		}(idx)
	}

	// Wait for termination
	doneCh := make(chan struct{})
	go func() {
		wg.Wait()
		close(doneCh)
	}()

	// Wait for everybody to get a turn
	select {
	case <-doneCh:
	case <-time.After(3 * DefaultLockRetryTime):
		t.Fatalf("timeout")
	}

	for idx, did := range acquired {
		if !did {
			t.Fatalf("contender %d never acquired", idx)
		}
	}
}

func TestAPI_LockDestroy(t *testing.T) {
	t.Parallel()
	c, s := makeClientWithoutConnect(t)
	defer s.Stop()

	lock, session := createTestLock(t, c, "test/lock")
	defer session.Destroy(lock.opts.Session, nil)

	// Should work
	leaderCh, err := lock.Lock(nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if leaderCh == nil {
		t.Fatalf("not leader")
	}

	// Destroy should fail
	if err := lock.Destroy(); err != ErrLockHeld {
		t.Fatalf("err: %v", err)
	}

	// Should be able to release
	err = lock.Unlock()
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	// Acquire with a different lock
	l2, session := createTestLock(t, c, "test/lock")
	defer session.Destroy(lock.opts.Session, nil)

	// Should work
	leaderCh, err = l2.Lock(nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if leaderCh == nil {
		t.Fatalf("not leader")
	}

	// Destroy should still fail
	if err := lock.Destroy(); err != ErrLockInUse {
		t.Fatalf("err: %v", err)
	}

	// Should release
	err = l2.Unlock()
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	// Destroy should work
	err = lock.Destroy()
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	// Double destroy should work
	err = l2.Destroy()
	if err != nil {
		t.Fatalf("err: %v", err)
	}
}

func TestAPI_LockConflict(t *testing.T) {
	t.Parallel()
	c, s := makeClientWithoutConnect(t)
	defer s.Stop()

	sema, session := createTestSemaphore(t, c, "test/lock/", 2)
	defer session.Destroy(sema.opts.Session, nil)

	// Should work
	lockCh, err := sema.Acquire(nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if lockCh == nil {
		t.Fatalf("not hold")
	}
	defer sema.Release()

	lock, session := createTestLock(t, c, "test/lock/.lock")
	defer session.Destroy(lock.opts.Session, nil)

	// Should conflict with semaphore
	_, err = lock.Lock(nil)
	if err != ErrLockConflict {
		t.Fatalf("err: %v", err)
	}

	// Should conflict with semaphore
	err = lock.Destroy()
	if err != ErrLockConflict {
		t.Fatalf("err: %v", err)
	}
}

func TestAPI_LockReclaimLock(t *testing.T) {
	t.Parallel()
	c, s := makeClientWithoutConnect(t)
	defer s.Stop()

	s.WaitForSerfCheck(t)

	session, _, err := c.Session().Create(&SessionEntry{}, nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	lock, err := c.LockOpts(&LockOptions{Key: "test/lock", Session: session})
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	// Should work
	leaderCh, err := lock.Lock(nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if leaderCh == nil {
		t.Fatalf("not leader")
	}
	defer lock.Unlock()

	l2, err := c.LockOpts(&LockOptions{Key: "test/lock", Session: session})
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	reclaimed := make(chan (<-chan struct{}), 1)
	go func() {
		l2Ch, err := l2.Lock(nil)
		if err != nil {
			t.Fatalf("not locked: %v", err)
		}
		reclaimed <- l2Ch
	}()

	// Should reclaim the lock
	var leader2Ch <-chan struct{}

	select {
	case leader2Ch = <-reclaimed:
	case <-time.After(time.Second):
		t.Fatalf("should have locked")
	}

	// unlock should work
	err = l2.Unlock()
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	//Both locks should see the unlock
	select {
	case <-leader2Ch:
	case <-time.After(time.Second):
		t.Fatalf("should not be leader")
	}

	select {
	case <-leaderCh:
	case <-time.After(time.Second):
		t.Fatalf("should not be leader")
	}
}

func TestAPI_LockMonitorRetry(t *testing.T) {
	t.Parallel()
	raw, s := makeClientWithoutConnect(t)
	defer s.Stop()

	s.WaitForSerfCheck(t)

	// Set up a server that always responds with 500 errors.
	failer := func(w http.ResponseWriter, req *http.Request) {
		w.WriteHeader(500)
	}
	outage := httptest.NewServer(http.HandlerFunc(failer))
	defer outage.Close()

	// Set up a reverse proxy that will send some requests to the
	// 500 server and pass everything else through to the real Consul
	// server.
	var mutex sync.Mutex
	errors := 0
	director := func(req *http.Request) {
		mutex.Lock()
		defer mutex.Unlock()

		req.URL.Scheme = "http"
		if errors > 0 && req.Method == "GET" && strings.Contains(req.URL.Path, "/v1/kv/test/lock") {
			req.URL.Host = outage.URL[7:] // Strip off "http://".
			errors--
		} else {
			req.URL.Host = raw.config.Address
		}
	}
	proxy := httptest.NewServer(&httputil.ReverseProxy{Director: director})
	defer proxy.Close()

	// Make another client that points at the proxy instead of the real
	// Consul server.
	config := raw.config
	config.Address = proxy.URL[7:] // Strip off "http://".
	c, err := NewClient(&config)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	// Set up a lock with retries enabled.
	opts := &LockOptions{
		Key:            "test/lock",
		SessionTTL:     "60s",
		MonitorRetries: 3,
	}
	lock, err := c.LockOpts(opts)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	// Make sure the default got set.
	if lock.opts.MonitorRetryTime != DefaultMonitorRetryTime {
		t.Fatalf("bad: %d", lock.opts.MonitorRetryTime)
	}

	// Now set a custom time for the test.
	opts.MonitorRetryTime = 250 * time.Millisecond
	lock, err = c.LockOpts(opts)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if lock.opts.MonitorRetryTime != 250*time.Millisecond {
		t.Fatalf("bad: %d", lock.opts.MonitorRetryTime)
	}

	// Should get the lock.
	leaderCh, err := lock.Lock(nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if leaderCh == nil {
		t.Fatalf("not leader")
	}

	// Poke the key using the raw client to force the monitor to wake up
	// and check the lock again. This time we will return errors for some
	// of the responses.
	mutex.Lock()
	errors = 2
	mutex.Unlock()
	pair, _, err := raw.KV().Get("test/lock", &QueryOptions{})
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if _, err := raw.KV().Put(pair, &WriteOptions{}); err != nil {
		t.Fatalf("err: %v", err)
	}
	time.Sleep(5 * opts.MonitorRetryTime)

	// Should still be the leader.
	select {
	case <-leaderCh:
		t.Fatalf("should be leader")
	default:
	}

	// Now return an overwhelming number of errors.
	mutex.Lock()
	errors = 10
	mutex.Unlock()
	if _, err := raw.KV().Put(pair, &WriteOptions{}); err != nil {
		t.Fatalf("err: %v", err)
	}
	time.Sleep(5 * opts.MonitorRetryTime)

	// Should lose leadership.
	select {
	case <-leaderCh:
	case <-time.After(time.Second):
		t.Fatalf("should not be leader")
	}
}

func TestAPI_LockOneShot(t *testing.T) {
	t.Parallel()
	c, s := makeClientWithoutConnect(t)
	defer s.Stop()

	s.WaitForSerfCheck(t)

	// Set up a lock as a one-shot.
	opts := &LockOptions{
		Key:         "test/lock",
		LockTryOnce: true,
	}
	lock, err := c.LockOpts(opts)
	if err != nil {
		t.Fatalf("err: %v", err)
	}

	// Make sure the default got set.
	if lock.opts.LockWaitTime != DefaultLockWaitTime {
		t.Fatalf("bad: %d", lock.opts.LockWaitTime)
	}

	// Now set a custom time for the test.
	opts.LockWaitTime = 250 * time.Millisecond
	lock, err = c.LockOpts(opts)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if lock.opts.LockWaitTime != 250*time.Millisecond {
		t.Fatalf("bad: %d", lock.opts.LockWaitTime)
	}

	// Should get the lock.
	ch, err := lock.Lock(nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if ch == nil {
		t.Fatalf("not leader")
	}

	// Now try with another session.
	contender, err := c.LockOpts(opts)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	start := time.Now()
	ch, err = contender.Lock(nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if ch != nil {
		t.Fatalf("should not be leader")
	}
	diff := time.Since(start)
	if diff < contender.opts.LockWaitTime || diff > 2*contender.opts.LockWaitTime {
		t.Fatalf("time out of bounds: %9.6f", diff.Seconds())
	}

	// Unlock and then make sure the contender can get it.
	if err := lock.Unlock(); err != nil {
		t.Fatalf("err: %v", err)
	}
	ch, err = contender.Lock(nil)
	if err != nil {
		t.Fatalf("err: %v", err)
	}
	if ch == nil {
		t.Fatalf("should be leader")
	}
}