2015-01-10 01:35:17 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// DefaultLockSessionName is the Session Name we assign if none is provided
|
|
|
|
DefaultLockSessionName = "Consul API Lock"
|
|
|
|
|
|
|
|
// DefaultLockSessionTTL is the default session TTL if no Session is provided
|
|
|
|
// when creating a new Lock. This is used because we do not have another
|
|
|
|
// other check to depend upon.
|
|
|
|
DefaultLockSessionTTL = "15s"
|
|
|
|
|
|
|
|
// DefaultLockWaitTime is how long we block for at a time to check if lock
|
|
|
|
// acquisition is possible. This affects the minimum time it takes to cancel
|
|
|
|
// a Lock acquisition.
|
|
|
|
DefaultLockWaitTime = 15 * time.Second
|
|
|
|
|
2015-01-10 01:42:24 +00:00
|
|
|
// DefaultLockRetryTime is how long we wait after a failed lock acquisition
|
2015-01-10 01:35:17 +00:00
|
|
|
// before attempting to do the lock again. This is so that once a lock-delay
|
2015-12-01 01:09:41 +00:00
|
|
|
// is in effect, we do not hot loop retrying the acquisition.
|
2015-01-10 01:42:24 +00:00
|
|
|
DefaultLockRetryTime = 5 * time.Second
|
2015-01-20 01:32:19 +00:00
|
|
|
|
2015-12-01 01:09:41 +00:00
|
|
|
// DefaultMonitorRetryTime is how long we wait after a failed monitor check
|
|
|
|
// of a lock (500 response code). This allows the monitor to ride out brief
|
|
|
|
// periods of unavailability, subject to the MonitorRetries setting in the
|
2016-01-06 01:09:03 +00:00
|
|
|
// lock options which is by default set to 0, disabling this feature. This
|
|
|
|
// affects locks and semaphores.
|
2015-12-01 01:09:41 +00:00
|
|
|
DefaultMonitorRetryTime = 2 * time.Second
|
|
|
|
|
2015-01-20 01:32:19 +00:00
|
|
|
// LockFlagValue is a magic flag we set to indicate a key
|
2015-01-20 20:58:09 +00:00
|
|
|
// is being used for a lock. It is used to detect a potential
|
|
|
|
// conflict with a semaphore.
|
2015-01-20 01:32:19 +00:00
|
|
|
LockFlagValue = 0x2ddccbc058a50c18
|
2015-01-10 01:35:17 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// ErrLockHeld is returned if we attempt to double lock
|
|
|
|
ErrLockHeld = fmt.Errorf("Lock already held")
|
|
|
|
|
|
|
|
// ErrLockNotHeld is returned if we attempt to unlock a lock
|
|
|
|
// that we do not hold.
|
|
|
|
ErrLockNotHeld = fmt.Errorf("Lock not held")
|
2015-01-13 22:01:50 +00:00
|
|
|
|
|
|
|
// ErrLockInUse is returned if we attempt to destroy a lock
|
|
|
|
// that is in use.
|
|
|
|
ErrLockInUse = fmt.Errorf("Lock in use")
|
2015-01-20 01:32:19 +00:00
|
|
|
|
|
|
|
// ErrLockConflict is returned if the flags on a key
|
|
|
|
// used for a lock do not match expectation
|
|
|
|
ErrLockConflict = fmt.Errorf("Existing key does not match lock use")
|
2015-01-10 01:35:17 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Lock is used to implement client-side leader election. It is follows the
|
2016-01-13 22:44:01 +00:00
|
|
|
// algorithm as described here: https://www.consul.io/docs/guides/leader-election.html.
|
2015-01-10 01:35:17 +00:00
|
|
|
type Lock struct {
|
|
|
|
c *Client
|
|
|
|
opts *LockOptions
|
|
|
|
|
|
|
|
isHeld bool
|
|
|
|
sessionRenew chan struct{}
|
|
|
|
lockSession string
|
|
|
|
l sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
// LockOptions is used to parameterize the Lock behavior.
|
|
|
|
type LockOptions struct {
|
2015-12-01 04:16:22 +00:00
|
|
|
Key string // Must be set and have write permissions
|
|
|
|
Value []byte // Optional, value to associate with the lock
|
|
|
|
Session string // Optional, created if not specified
|
2016-09-29 13:07:54 +00:00
|
|
|
SessionOpts *SessionEntry // Optional, options to use when creating a session
|
2016-10-06 00:53:27 +00:00
|
|
|
SessionName string // Optional, defaults to DefaultLockSessionName (ignored if SessionOpts is given)
|
|
|
|
SessionTTL string // Optional, defaults to DefaultLockSessionTTL (ignored if SessionOpts is given)
|
2015-12-01 04:16:22 +00:00
|
|
|
MonitorRetries int // Optional, defaults to 0 which means no retries
|
|
|
|
MonitorRetryTime time.Duration // Optional, defaults to DefaultMonitorRetryTime
|
2016-01-06 00:40:35 +00:00
|
|
|
LockWaitTime time.Duration // Optional, defaults to DefaultLockWaitTime
|
|
|
|
LockTryOnce bool // Optional, defaults to false which means try forever
|
2019-12-10 02:26:41 +00:00
|
|
|
Namespace string `json:",omitempty"` // Optional, defaults to API client config, namespace of ACL token, or "default" namespace
|
2015-01-10 01:35:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// LockKey returns a handle to a lock struct which can be used
|
|
|
|
// to acquire and release the mutex. The key used must have
|
|
|
|
// write permissions.
|
|
|
|
func (c *Client) LockKey(key string) (*Lock, error) {
|
|
|
|
opts := &LockOptions{
|
|
|
|
Key: key,
|
|
|
|
}
|
|
|
|
return c.LockOpts(opts)
|
|
|
|
}
|
|
|
|
|
|
|
|
// LockOpts returns a handle to a lock struct which can be used
|
|
|
|
// to acquire and release the mutex. The key used must have
|
|
|
|
// write permissions.
|
|
|
|
func (c *Client) LockOpts(opts *LockOptions) (*Lock, error) {
|
2015-01-13 01:43:00 +00:00
|
|
|
if opts.Key == "" {
|
|
|
|
return nil, fmt.Errorf("missing key")
|
|
|
|
}
|
2015-01-10 01:35:17 +00:00
|
|
|
if opts.SessionName == "" {
|
|
|
|
opts.SessionName = DefaultLockSessionName
|
|
|
|
}
|
|
|
|
if opts.SessionTTL == "" {
|
|
|
|
opts.SessionTTL = DefaultLockSessionTTL
|
|
|
|
} else {
|
|
|
|
if _, err := time.ParseDuration(opts.SessionTTL); err != nil {
|
|
|
|
return nil, fmt.Errorf("invalid SessionTTL: %v", err)
|
|
|
|
}
|
|
|
|
}
|
2015-12-01 04:16:22 +00:00
|
|
|
if opts.MonitorRetryTime == 0 {
|
|
|
|
opts.MonitorRetryTime = DefaultMonitorRetryTime
|
|
|
|
}
|
2016-01-06 00:40:35 +00:00
|
|
|
if opts.LockWaitTime == 0 {
|
|
|
|
opts.LockWaitTime = DefaultLockWaitTime
|
|
|
|
}
|
2015-01-10 01:35:17 +00:00
|
|
|
l := &Lock{
|
|
|
|
c: c,
|
|
|
|
opts: opts,
|
|
|
|
}
|
|
|
|
return l, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Lock attempts to acquire the lock and blocks while doing so.
|
|
|
|
// Providing a non-nil stopCh can be used to abort the lock attempt.
|
|
|
|
// Returns a channel that is closed if our lock is lost or an error.
|
|
|
|
// This channel could be closed at any time due to session invalidation,
|
|
|
|
// communication errors, operator intervention, etc. It is NOT safe to
|
|
|
|
// assume that the lock is held until Unlock() unless the Session is specifically
|
|
|
|
// created without any associated health checks. By default Consul sessions
|
|
|
|
// prefer liveness over safety and an application must be able to handle
|
|
|
|
// the lock being lost.
|
2015-01-20 00:37:36 +00:00
|
|
|
func (l *Lock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) {
|
2015-01-10 01:35:17 +00:00
|
|
|
// Hold the lock as we try to acquire
|
|
|
|
l.l.Lock()
|
|
|
|
defer l.l.Unlock()
|
|
|
|
|
|
|
|
// Check if we already hold the lock
|
|
|
|
if l.isHeld {
|
|
|
|
return nil, ErrLockHeld
|
|
|
|
}
|
|
|
|
|
2019-11-25 17:57:35 +00:00
|
|
|
wOpts := WriteOptions{
|
|
|
|
Namespace: l.opts.Namespace,
|
|
|
|
}
|
|
|
|
|
2015-01-10 01:35:17 +00:00
|
|
|
// Check if we need to create a session first
|
|
|
|
l.lockSession = l.opts.Session
|
|
|
|
if l.lockSession == "" {
|
2017-04-21 01:59:42 +00:00
|
|
|
s, err := l.createSession()
|
|
|
|
if err != nil {
|
2015-01-10 01:35:17 +00:00
|
|
|
return nil, fmt.Errorf("failed to create session: %v", err)
|
|
|
|
}
|
2017-04-21 01:59:42 +00:00
|
|
|
|
|
|
|
l.sessionRenew = make(chan struct{})
|
|
|
|
l.lockSession = s
|
2019-11-25 17:57:35 +00:00
|
|
|
|
2017-04-21 01:59:42 +00:00
|
|
|
session := l.c.Session()
|
2019-11-25 17:57:35 +00:00
|
|
|
go session.RenewPeriodic(l.opts.SessionTTL, s, &wOpts, l.sessionRenew)
|
2017-04-21 01:59:42 +00:00
|
|
|
|
|
|
|
// If we fail to acquire the lock, cleanup the session
|
|
|
|
defer func() {
|
|
|
|
if !l.isHeld {
|
|
|
|
close(l.sessionRenew)
|
|
|
|
l.sessionRenew = nil
|
|
|
|
}
|
|
|
|
}()
|
2015-01-10 01:35:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Setup the query options
|
|
|
|
kv := l.c.KV()
|
2019-11-25 17:57:35 +00:00
|
|
|
qOpts := QueryOptions{
|
2019-12-10 02:26:41 +00:00
|
|
|
WaitTime: l.opts.LockWaitTime,
|
2019-11-25 17:57:35 +00:00
|
|
|
Namespace: l.opts.Namespace,
|
2015-01-10 01:35:17 +00:00
|
|
|
}
|
|
|
|
|
2016-01-06 17:40:20 +00:00
|
|
|
start := time.Now()
|
2016-01-06 00:40:35 +00:00
|
|
|
attempts := 0
|
2015-01-10 01:35:17 +00:00
|
|
|
WAIT:
|
|
|
|
// Check if we should quit
|
|
|
|
select {
|
|
|
|
case <-stopCh:
|
|
|
|
return nil, nil
|
|
|
|
default:
|
|
|
|
}
|
|
|
|
|
2016-01-06 17:40:20 +00:00
|
|
|
// Handle the one-shot mode.
|
|
|
|
if l.opts.LockTryOnce && attempts > 0 {
|
2017-10-17 18:38:24 +00:00
|
|
|
elapsed := time.Since(start)
|
2018-07-06 09:55:25 +00:00
|
|
|
if elapsed > l.opts.LockWaitTime {
|
2016-01-06 17:40:20 +00:00
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2018-07-06 09:55:25 +00:00
|
|
|
// Query wait time should not exceed the lock wait time
|
|
|
|
qOpts.WaitTime = l.opts.LockWaitTime - elapsed
|
2016-01-06 00:40:35 +00:00
|
|
|
}
|
|
|
|
attempts++
|
|
|
|
|
2015-01-10 01:35:17 +00:00
|
|
|
// Look for an existing lock, blocking until not taken
|
2019-11-25 17:57:35 +00:00
|
|
|
pair, meta, err := kv.Get(l.opts.Key, &qOpts)
|
2015-01-10 01:35:17 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to read lock: %v", err)
|
|
|
|
}
|
2015-01-20 01:32:19 +00:00
|
|
|
if pair != nil && pair.Flags != LockFlagValue {
|
|
|
|
return nil, ErrLockConflict
|
|
|
|
}
|
2015-04-12 21:48:11 +00:00
|
|
|
locked := false
|
|
|
|
if pair != nil && pair.Session == l.lockSession {
|
|
|
|
goto HELD
|
|
|
|
}
|
2015-01-10 01:35:17 +00:00
|
|
|
if pair != nil && pair.Session != "" {
|
|
|
|
qOpts.WaitIndex = meta.LastIndex
|
|
|
|
goto WAIT
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try to acquire the lock
|
2015-04-12 21:48:11 +00:00
|
|
|
pair = l.lockEntry(l.lockSession)
|
2019-11-25 17:57:35 +00:00
|
|
|
|
|
|
|
locked, _, err = kv.Acquire(pair, &wOpts)
|
2015-01-10 01:35:17 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to acquire lock: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handle the case of not getting the lock
|
|
|
|
if !locked {
|
2015-06-05 20:23:23 +00:00
|
|
|
// Determine why the lock failed
|
|
|
|
qOpts.WaitIndex = 0
|
2019-11-25 17:57:35 +00:00
|
|
|
pair, meta, err = kv.Get(l.opts.Key, &qOpts)
|
2020-06-17 16:16:02 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2015-06-05 20:23:23 +00:00
|
|
|
if pair != nil && pair.Session != "" {
|
|
|
|
//If the session is not null, this means that a wait can safely happen
|
|
|
|
//using a long poll
|
|
|
|
qOpts.WaitIndex = meta.LastIndex
|
2015-01-10 01:35:17 +00:00
|
|
|
goto WAIT
|
2015-06-05 20:23:23 +00:00
|
|
|
} else {
|
|
|
|
// If the session is empty and the lock failed to acquire, then it means
|
|
|
|
// a lock-delay is in effect and a timed wait must be used
|
|
|
|
select {
|
|
|
|
case <-time.After(DefaultLockRetryTime):
|
|
|
|
goto WAIT
|
|
|
|
case <-stopCh:
|
|
|
|
return nil, nil
|
|
|
|
}
|
2015-01-10 01:35:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-12 21:48:11 +00:00
|
|
|
HELD:
|
2015-01-10 01:35:17 +00:00
|
|
|
// Watch to ensure we maintain leadership
|
|
|
|
leaderCh := make(chan struct{})
|
|
|
|
go l.monitorLock(l.lockSession, leaderCh)
|
|
|
|
|
|
|
|
// Set that we own the lock
|
|
|
|
l.isHeld = true
|
|
|
|
|
|
|
|
// Locked! All done
|
|
|
|
return leaderCh, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Unlock released the lock. It is an error to call this
|
|
|
|
// if the lock is not currently held.
|
|
|
|
func (l *Lock) Unlock() error {
|
|
|
|
// Hold the lock as we try to release
|
|
|
|
l.l.Lock()
|
|
|
|
defer l.l.Unlock()
|
|
|
|
|
|
|
|
// Ensure the lock is actually held
|
|
|
|
if !l.isHeld {
|
|
|
|
return ErrLockNotHeld
|
|
|
|
}
|
|
|
|
|
2015-01-12 23:46:40 +00:00
|
|
|
// Set that we no longer own the lock
|
2015-01-10 01:35:17 +00:00
|
|
|
l.isHeld = false
|
|
|
|
|
|
|
|
// Stop the session renew
|
|
|
|
if l.sessionRenew != nil {
|
|
|
|
defer func() {
|
|
|
|
close(l.sessionRenew)
|
|
|
|
l.sessionRenew = nil
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the lock entry, and clear the lock session
|
|
|
|
lockEnt := l.lockEntry(l.lockSession)
|
|
|
|
l.lockSession = ""
|
|
|
|
|
|
|
|
// Release the lock explicitly
|
|
|
|
kv := l.c.KV()
|
2019-11-25 17:57:35 +00:00
|
|
|
w := WriteOptions{Namespace: l.opts.Namespace}
|
|
|
|
|
|
|
|
_, _, err := kv.Release(lockEnt, &w)
|
2015-01-10 01:35:17 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to release lock: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-01-13 22:01:50 +00:00
|
|
|
// Destroy is used to cleanup the lock entry. It is not necessary
|
|
|
|
// to invoke. It will fail if the lock is in use.
|
|
|
|
func (l *Lock) Destroy() error {
|
|
|
|
// Hold the lock as we try to release
|
|
|
|
l.l.Lock()
|
|
|
|
defer l.l.Unlock()
|
|
|
|
|
|
|
|
// Check if we already hold the lock
|
|
|
|
if l.isHeld {
|
|
|
|
return ErrLockHeld
|
|
|
|
}
|
|
|
|
|
|
|
|
// Look for an existing lock
|
|
|
|
kv := l.c.KV()
|
2019-11-25 17:57:35 +00:00
|
|
|
q := QueryOptions{Namespace: l.opts.Namespace}
|
|
|
|
|
|
|
|
pair, _, err := kv.Get(l.opts.Key, &q)
|
2015-01-13 22:01:50 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to read lock: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Nothing to do if the lock does not exist
|
|
|
|
if pair == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-01-20 01:32:19 +00:00
|
|
|
// Check for possible flag conflict
|
|
|
|
if pair.Flags != LockFlagValue {
|
|
|
|
return ErrLockConflict
|
|
|
|
}
|
|
|
|
|
2015-01-13 22:01:50 +00:00
|
|
|
// Check if it is in use
|
|
|
|
if pair.Session != "" {
|
|
|
|
return ErrLockInUse
|
|
|
|
}
|
|
|
|
|
|
|
|
// Attempt the delete
|
2019-11-25 17:57:35 +00:00
|
|
|
w := WriteOptions{Namespace: l.opts.Namespace}
|
|
|
|
didRemove, _, err := kv.DeleteCAS(pair, &w)
|
2015-01-13 22:01:50 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to remove lock: %v", err)
|
|
|
|
}
|
|
|
|
if !didRemove {
|
|
|
|
return ErrLockInUse
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-01-10 01:35:17 +00:00
|
|
|
// createSession is used to create a new managed session
|
|
|
|
func (l *Lock) createSession() (string, error) {
|
|
|
|
session := l.c.Session()
|
2016-09-29 13:07:54 +00:00
|
|
|
se := l.opts.SessionOpts
|
|
|
|
if se == nil {
|
|
|
|
se = &SessionEntry{
|
|
|
|
Name: l.opts.SessionName,
|
|
|
|
TTL: l.opts.SessionTTL,
|
|
|
|
}
|
2015-01-10 01:35:17 +00:00
|
|
|
}
|
2019-11-25 17:57:35 +00:00
|
|
|
w := WriteOptions{Namespace: l.opts.Namespace}
|
|
|
|
id, _, err := session.Create(se, &w)
|
2015-01-10 01:35:17 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return id, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// lockEntry returns a formatted KVPair for the lock
|
|
|
|
func (l *Lock) lockEntry(session string) *KVPair {
|
|
|
|
return &KVPair{
|
|
|
|
Key: l.opts.Key,
|
|
|
|
Value: l.opts.Value,
|
|
|
|
Session: session,
|
2015-01-20 01:32:19 +00:00
|
|
|
Flags: LockFlagValue,
|
2015-01-10 01:35:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// monitorLock is a long running routine to monitor a lock ownership
|
|
|
|
// It closes the stopCh if we lose our leadership.
|
|
|
|
func (l *Lock) monitorLock(session string, stopCh chan struct{}) {
|
2015-01-13 01:43:00 +00:00
|
|
|
defer close(stopCh)
|
2015-01-10 01:35:17 +00:00
|
|
|
kv := l.c.KV()
|
2019-11-25 17:57:35 +00:00
|
|
|
opts := QueryOptions{
|
|
|
|
RequireConsistent: true,
|
2019-12-10 02:26:41 +00:00
|
|
|
Namespace: l.opts.Namespace,
|
2019-11-25 17:57:35 +00:00
|
|
|
}
|
2015-01-10 01:35:17 +00:00
|
|
|
WAIT:
|
2015-12-01 01:09:41 +00:00
|
|
|
retries := l.opts.MonitorRetries
|
|
|
|
RETRY:
|
2019-11-25 17:57:35 +00:00
|
|
|
pair, meta, err := kv.Get(l.opts.Key, &opts)
|
2015-01-10 01:35:17 +00:00
|
|
|
if err != nil {
|
2015-12-01 01:09:41 +00:00
|
|
|
// If configured we can try to ride out a brief Consul unavailability
|
|
|
|
// by doing retries. Note that we have to attempt the retry in a non-
|
|
|
|
// blocking fashion so that we have a clean place to reset the retry
|
|
|
|
// counter if service is restored.
|
2017-10-11 14:42:10 +00:00
|
|
|
if retries > 0 && IsRetryableError(err) {
|
2015-12-01 04:16:22 +00:00
|
|
|
time.Sleep(l.opts.MonitorRetryTime)
|
2015-12-01 01:09:41 +00:00
|
|
|
retries--
|
|
|
|
opts.WaitIndex = 0
|
|
|
|
goto RETRY
|
|
|
|
}
|
2015-01-10 01:35:17 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
if pair != nil && pair.Session == session {
|
|
|
|
opts.WaitIndex = meta.LastIndex
|
|
|
|
goto WAIT
|
|
|
|
}
|
|
|
|
}
|