/
leadership.go
230 lines (190 loc) · 5.91 KB
/
leadership.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
// Package lock provides a distributed locking algorithm backed by Google Cloud Storage. See
// https://www.joyfulbikeshedding.com/blog/2021-05-19-robust-distributed-locking-algorithm-based-on-google-cloud-storage.html
// for more details on the general design.
package lock
import (
"context"
"errors"
"net/http"
"sync"
"time"
"cloud.google.com/go/storage"
"google.golang.org/api/googleapi"
)
var (
ErrLockAbandoned = errors.New("lock abandoned")
errLockOwnedBySomeoneElse = errors.New("unable to delete lock owned by someone else")
)
const (
maxRefreshFailures = 3
ownerMetadata = "owner"
expiresAtMetadata = "expires-at"
)
// Lock provides a lock based off of a Google Cloud Storage object, without requiring communication between clients.
type Lock struct {
bucket *storage.BucketHandle
path string
identity string
ttl time.Duration
logger func(ctx context.Context) Logger
mutex sync.Mutex
refreshMetadata bool
refreshFailures uint
latestMetadataGeneration int64
}
func NewLock(bucket *storage.BucketHandle, id, path string, ttl time.Duration, logContext func(context.Context) Logger) *Lock {
return &Lock{
bucket: bucket,
path: path,
identity: id,
ttl: ttl,
logger: logContext,
mutex: sync.Mutex{},
refreshMetadata: false,
latestMetadataGeneration: 0,
}
}
type Logger interface {
Info(msg string, keysAndValues ...any)
Error(err error, msg string, keysAndValues ...any)
}
// Lock will attempt to acquire the configured lock until the context has timed out. The caller is expected to
// frequently call RefreshLock while holding the lock and Unlock when the lock is no longer needed.
func (l *Lock) Lock(ctx context.Context, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var errs []error
for {
select {
case <-ctx.Done():
return errors.Join(append(errs, ctx.Err())...)
default:
err := l.createLock(ctx)
if err == nil {
return nil
}
var gErr *googleapi.Error
if errors.As(err, &gErr) && gErr.Code == http.StatusPreconditionFailed {
if err := l.deleteLockIfStale(ctx); err != nil {
return err
}
}
l.logger(ctx).Error(err, "Failed to acquire lock", "path", l.path)
errs = append(errs, err)
}
time.Sleep(100 * time.Millisecond)
}
}
// Unlock will attempt to release the acquired lock.
func (l *Lock) Unlock(ctx context.Context) error {
return l.deleteLock(ctx, nil, true)
}
// RefreshLock will update the information on the lock to ensure that the client still owns it. If ErrLockAbandoned is
// returned, then the client should assume the lock has been lost and stop immediately.
func (l *Lock) RefreshLock(ctx context.Context) error {
l.mutex.Lock()
defer l.mutex.Unlock()
if !l.refreshMetadata {
return nil
}
if l.refreshFailures > maxRefreshFailures {
return ErrLockAbandoned
}
l.logger(ctx).Info("Refreshing lock", "path", l.path)
attrs, err := l.bucket.Object(l.path).
If(storage.Conditions{MetagenerationMatch: l.latestMetadataGeneration}).
Update(ctx, storage.ObjectAttrsToUpdate{Metadata: l.metadata()})
if err != nil {
var gErr *googleapi.Error
if errors.Is(err, storage.ErrObjectNotExist) ||
(errors.As(err, &gErr) && gErr.Code == http.StatusPreconditionFailed) {
return ErrLockAbandoned
}
l.refreshFailures++
if l.refreshFailures > maxRefreshFailures {
return ErrLockAbandoned
}
return err
}
l.refreshFailures = 0
l.latestMetadataGeneration = attrs.Metageneration
return nil
}
func (l *Lock) deleteLockIfStale(ctx context.Context) error {
attrs, err := l.bucket.Object(l.path).Attrs(ctx)
if err != nil {
return err
}
if attrs.Metadata[ownerMetadata] == l.identity {
if err := l.deleteLock(ctx, &attrs.Metageneration, false); err != nil {
return err
}
}
expires, err := time.Parse(time.RFC3339Nano, attrs.Metadata[expiresAtMetadata])
if err != nil || time.Now().After(expires) {
values := []any{"path", l.path}
if err != nil {
values = append(values, "err", err)
}
l.logger(ctx).Info("Lock expired", values...)
return l.deleteLock(ctx, &attrs.Metageneration, false)
}
return nil
}
func (l *Lock) createLock(ctx context.Context) error {
l.mutex.Lock()
defer l.mutex.Unlock()
o := l.bucket.Object(l.path).If(storage.Conditions{DoesNotExist: true})
w := o.NewWriter(ctx)
w.CacheControl = "no-store"
w.Metadata = l.metadata()
if err := w.Close(); err != nil {
return err
}
attrs, err := l.bucket.Object(l.path).Attrs(ctx)
if err != nil {
return err
}
l.refreshMetadata = true
l.latestMetadataGeneration = attrs.Metageneration
return nil
}
func (l *Lock) deleteLock(ctx context.Context, metageneration *int64, confirmOwner bool) error {
l.mutex.Lock()
defer l.mutex.Unlock()
if confirmOwner {
// Check we still own the lock, on the off chance that the metageneration of the new lock matches what we think
// the old one is at.
attrs, err := l.bucket.Object(l.path).Attrs(ctx)
if err != nil {
if errors.Is(err, storage.ErrObjectNotExist) {
return nil
}
return err
}
if attrs.Metadata[ownerMetadata] != l.identity {
return errLockOwnedBySomeoneElse
}
}
l.refreshMetadata = false
m := l.latestMetadataGeneration
if metageneration != nil {
m = *metageneration
}
if err := l.bucket.Object(l.path).If(storage.Conditions{MetagenerationMatch: m}).Delete(ctx); err != nil {
var gErr *googleapi.Error
if errors.Is(err, storage.ErrObjectNotExist) || (errors.As(err, &gErr) && gErr.Code == http.StatusPreconditionFailed) {
// TODO what could a caller do if they get StatusPreconditionFailed?
return nil
}
return err
}
return nil
}
func (l *Lock) metadata() map[string]string {
ttl := time.Now().UTC().Add(l.ttl).Format(time.RFC3339Nano)
return map[string]string{
expiresAtMetadata: ttl,
ownerMetadata: l.identity,
}
}