forked from pulcy/kube-lock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlock.go
184 lines (164 loc) · 4.9 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
package lock
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"fmt"
"time"
)
// KubeLock is used to provide a distributed lock using Kubernetes annotation data.
// It works by writing data into a specific annotation key.
// Other instance trying to write into the same annotation key will be refused because a resource version is used.
type KubeLock interface {
// Acquire tries to acquire the lock.
// If the lock is already held by us, the lock will be updated.
// If successfull it returns nil, otherwise it returns an error.
// Note that Acquire will not renew the lock. To do that, call Acquire every ttl/2.
Acquire() error
// Release tries to release the lock.
// If the lock is already held by us, the lock will be released.
// If successfull it returns nil, otherwise it returns an error.
Release() error
// CurrentOwner fetches the current owner ID of the lock.
// If the lock is not owner, "" is returned.
CurrentOwner() (string, error)
}
// NewKubeLock creates a new KubeLock.
// The lock will not be aquired.
func NewKubeLock(annotationKey, ownerID string, ttl time.Duration, metaGet MetaGetter, metaUpdate MetaUpdater) (KubeLock, error) {
if annotationKey == "" {
annotationKey = defaultAnnotationKey
}
if ownerID == "" {
id := make([]byte, 16)
if _, err := rand.Read(id); err != nil {
return nil, err
}
ownerID = base64.StdEncoding.EncodeToString(id)
}
if ttl == 0 {
ttl = defaultTTL
}
if metaGet == nil {
return nil, fmt.Errorf("metaGet cannot be nil")
}
if metaUpdate == nil {
return nil, fmt.Errorf("metaUpdate cannot be nil")
}
return &kubeLock{
annotationKey: annotationKey,
ownerID: ownerID,
ttl: ttl,
getMeta: metaGet,
updateMeta: metaUpdate,
}, nil
}
const (
defaultAnnotationKey = "pulcy.com/kube-lock"
defaultTTL = time.Minute
)
type kubeLock struct {
annotationKey string
ownerID string
ttl time.Duration
getMeta MetaGetter
updateMeta MetaUpdater
}
type LockData struct {
Owner string `json:"owner"`
ExpiresAt time.Time `json:"expires_at"`
}
type MetaGetter func() (annotations map[string]string, resourceVersion string, item interface{}, err error)
type MetaUpdater func(annotations map[string]string, resourceVersion string, item interface{}) error
// Acquire tries to acquire the lock.
// If the lock is already held by us, the lock will be updated.
// If successfull it returns nil, otherwise it returns an error.
func (l *kubeLock) Acquire() error {
// Get current state
ann, rv, extra, err := l.getMeta()
if err != nil {
return err
}
// Get lock data
if ann == nil {
ann = make(map[string]string)
}
if lockDataRaw, ok := ann[l.annotationKey]; ok && lockDataRaw != "" {
var lockData LockData
if err := json.Unmarshal([]byte(lockDataRaw), &lockData); err != nil {
return err
}
if lockData.Owner != l.ownerID {
// Lock is owned by someone else
if time.Now().Before(lockData.ExpiresAt) {
// Lock is held and not expired
return fmt.Errorf( "locked by %s", lockData.Owner, AlreadyLockedError)
}
}
}
// Try to lock it now
expiredAt := time.Now().Add(l.ttl)
lockDataRaw, err := json.Marshal(LockData{Owner: l.ownerID, ExpiresAt: expiredAt})
if err != nil {
return err
}
ann[l.annotationKey] = string(lockDataRaw)
if err := l.updateMeta(ann, rv, extra); err != nil {
return err
}
// Update successfull, we've acquired the lock
return nil
}
// Release tries to release the lock.
// If the lock is already held by us, the lock will be released.
// If successfull it returns nil, otherwise it returns an error.
func (l *kubeLock) Release() error {
// Get current state
ann, rv, extra, err := l.getMeta()
if err != nil {
return err
}
// Get lock data
if ann == nil {
ann = make(map[string]string)
}
if lockDataRaw, ok := ann[l.annotationKey]; ok && lockDataRaw != "" {
var lockData LockData
if err := json.Unmarshal([]byte(lockDataRaw), &lockData); err != nil {
return err
}
if lockData.Owner != l.ownerID {
// Lock is owned by someone else
return fmt.Errorf("locked by %s", lockData.Owner, NotLockedByMeError)
}
} else if ok && lockDataRaw == "" {
// Lock is not locked, we consider that a successfull release also.
return nil
}
// Try to release lock it now
ann[l.annotationKey] = ""
if err := l.updateMeta(ann, rv, extra); err != nil {
return err
}
// Update successfull, we've released the lock
return nil
}
// CurrentOwner fetches the current owner ID of the lock.
// If the lock is not owner, "" is returned.
func (l *kubeLock) CurrentOwner() (string, error) {
// Get current state
ann, _, _, err := l.getMeta()
if err != nil {
return "", err
}
// Get lock data
if lockDataRaw, ok := ann[l.annotationKey]; ok && lockDataRaw != "" {
var lockData LockData
if err := json.Unmarshal([]byte(lockDataRaw), &lockData); err != nil {
return "", err
}
return lockData.Owner, nil
}
// No owner found
return "", nil
}