Skip to content

Commit

Permalink
etcd3: only create lock when lock is called (#3893)
Browse files Browse the repository at this point in the history
  • Loading branch information
xiang90 authored and jefferai committed Feb 2, 2018
1 parent 91dffed commit 74a3b5a
Showing 1 changed file with 21 additions and 15 deletions.
36 changes: 21 additions & 15 deletions physical/etcd/etcd3.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,25 +249,24 @@ type EtcdLock struct {

// Lock is used for mutual exclusion based on the given key.
func (c *EtcdBackend) LockWith(key, value string) (physical.Lock, error) {
session, err := concurrency.NewSession(c.etcd, concurrency.WithTTL(etcd3LockTimeoutInSeconds))
if err != nil {
return nil, err
}

p := path.Join(c.path, key)
return &EtcdLock{
etcdSession: session,
etcdMu: concurrency.NewMutex(session, p),
prefix: p,
value: value,
etcd: c.etcd,
prefix: p,
value: value,
etcd: c.etcd,
}, nil
}

func (c *EtcdLock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) {
c.lock.Lock()
defer c.lock.Unlock()

if c.etcdMu == nil {
if err := c.initMu(); err != nil {
return nil, err
}
}

if c.held {
return nil, EtcdLockHeldError
}
Expand All @@ -276,13 +275,10 @@ func (c *EtcdLock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) {
case _, ok := <-c.etcdSession.Done():
if !ok {
// The session's done channel is closed, so the session is over,
// and we need a new one
session, err := concurrency.NewSession(c.etcd, concurrency.WithTTL(etcd3LockTimeoutInSeconds))
if err != nil {
// and we need a new lock with a new session.
if err := c.initMu(); err != nil {
return nil, err
}
c.etcdSession = session
c.etcdMu = concurrency.NewMutex(session, c.prefix)
}
default:
}
Expand Down Expand Up @@ -340,3 +336,13 @@ func (c *EtcdLock) Value() (bool, string, error) {

return true, string(resp.Kvs[0].Value), nil
}

func (c *EtcdLock) initMu() error {
session, err := concurrency.NewSession(c.etcd, concurrency.WithTTL(etcd3LockTimeoutInSeconds))
if err != nil {
return err
}
c.etcdSession = session
c.etcdMu = concurrency.NewMutex(session, c.prefix)
return nil
}

0 comments on commit 74a3b5a

Please sign in to comment.