-
Notifications
You must be signed in to change notification settings - Fork 2
/
locker.go
106 lines (93 loc) · 1.89 KB
/
locker.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
package azmutex
import (
"context"
"fmt"
"sync"
"time"
)
const (
acquireInterval = 10
leaseDurationSeconds = 60
renewIntervalSeconds = 10
)
type Locker struct {
key string
mutex *AzureMutex
cancelContext context.CancelFunc
cancelRequired chan *sync.WaitGroup
}
func (l *Locker) log(message string) {
if l.mutex.options.LogFunc != nil {
l.mutex.options.LogFunc(message)
}
}
func NewLocker(options MutexOptions, key string) *Locker {
ctx, cancel := context.WithCancel(context.Background())
locker := Locker{
key: key,
cancelContext: cancel,
mutex: NewMutexWithContext(options, ctx),
}
return &locker
}
func (l *Locker) Lock() error {
err := l.waitLock()
if err != nil {
return err
}
l.startRenew()
return nil
}
func (l *Locker) Unlock() error {
l.stopRenew()
err := l.mutex.Release(l.key)
if err == nil {
l.log("Lease released")
}
defer l.cancelContext()
l.log("Unlocked")
return err
}
func (l *Locker) waitLock() error {
for {
err := l.mutex.Acquire(l.key, leaseDurationSeconds)
if _, ok := err.(*LeaseAlreadyPresentError); ok {
l.log("Lock already acquired. Waiting . . .")
time.Sleep(acquireInterval * time.Second)
continue
}
if err == nil {
l.log("Locked it!")
}
return err
}
}
func (l *Locker) startRenew() {
l.cancelRequired = make(chan *sync.WaitGroup)
go func() {
var wg *sync.WaitGroup
for {
select {
case <-time.After(renewIntervalSeconds * time.Second):
err := l.mutex.Renew(l.key)
// TODO: Handle transient errors gently, don't just pass
if err != nil {
l.log(fmt.Sprintf("Could not renew: %v", err))
break
}
l.log("Lease renewed")
break
case wg = <-l.cancelRequired:
l.log("Stopping renewing . . .")
wg.Done()
return
}
}
}()
}
func (l *Locker) stopRenew() {
var wg sync.WaitGroup
wg.Add(1)
l.cancelRequired <- &wg
wg.Wait()
}