Skip to content

Commit 71d7b0f

Browse files
committed
Prevent possible deadlock in Unlock function
1 parent c94fa7b commit 71d7b0f

File tree

1 file changed

+7
-7
lines changed

1 file changed

+7
-7
lines changed

storage.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -54,14 +54,14 @@ func (cs *ConsulStorage) prefixKey(key string) string {
5454

5555
// Lock acquires a distributed lock for the given key or blocks until it gets one
5656
func (cs *ConsulStorage) Lock(ctx context.Context, key string) error {
57-
cs.logger.Debugf("trying lock for %s", key)
57+
cs.logger.Infof("trying lock for %s", key)
5858

5959
if _, isLocked := cs.GetLock(key); isLocked {
6060
return nil
6161
}
6262

6363
// prepare the distributed lock
64-
cs.logger.Debugf("creating Consul lock for %s", key)
64+
cs.logger.Infof("creating Consul lock for %s", key)
6565
lock, err := cs.ConsulClient.LockOpts(&consul.LockOptions{
6666
Key: cs.prefixKey(key),
6767
LockWaitTime: time.Duration(cs.Timeout) * time.Second,
@@ -105,9 +105,6 @@ func (cs *ConsulStorage) GetLock(key string) (*consul.Lock, bool) {
105105

106106
// Unlock releases a specific lock
107107
func (cs *ConsulStorage) Unlock(key string) error {
108-
cs.muLocks.Lock()
109-
defer cs.muLocks.Unlock()
110-
111108
// check if we own it and unlock
112109
lock, exists := cs.GetLock(key)
113110
if !exists {
@@ -119,7 +116,10 @@ func (cs *ConsulStorage) Unlock(key string) error {
119116
return errors.Wrapf(err, "unable to unlock %s", cs.prefixKey(key))
120117
}
121118

119+
cs.muLocks.Lock()
122120
delete(cs.locks, key)
121+
cs.muLocks.Unlock()
122+
123123
return nil
124124
}
125125

@@ -149,7 +149,7 @@ func (cs ConsulStorage) Store(key string, value []byte) error {
149149

150150
// Load retrieves the value for a key from Consul KV
151151
func (cs ConsulStorage) Load(key string) ([]byte, error) {
152-
cs.logger.Debugf("loading data from Consul for %s", key)
152+
cs.logger.Infof("loading data from Consul for %s", key)
153153

154154
kv, _, err := cs.ConsulClient.KV().Get(cs.prefixKey(key), &consul.QueryOptions{RequireConsistent: true})
155155
if err != nil {
@@ -168,7 +168,7 @@ func (cs ConsulStorage) Load(key string) ([]byte, error) {
168168

169169
// Delete a key from Consul KV
170170
func (cs ConsulStorage) Delete(key string) error {
171-
cs.logger.Debugf("deleting key %s from Consul", key)
171+
cs.logger.Infof("deleting key %s from Consul", key)
172172

173173
// first obtain existing keypair
174174
kv, _, err := cs.ConsulClient.KV().Get(cs.prefixKey(key), &consul.QueryOptions{RequireConsistent: true})

0 commit comments

Comments
 (0)