diff --git a/agent/agent.go b/agent/agent.go index 6a908f4c01..201dc7aee6 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -48,6 +48,7 @@ import ( "github.com/hashicorp/consul/ipaddr" "github.com/hashicorp/consul/lib" "github.com/hashicorp/consul/lib/file" + "github.com/hashicorp/consul/lib/mutex" "github.com/hashicorp/consul/logging" "github.com/hashicorp/consul/tlsutil" "github.com/hashicorp/consul/types" @@ -222,7 +223,7 @@ type Agent struct { exposedPorts map[string]int // stateLock protects the agent state - stateLock sync.Mutex + stateLock *mutex.Mutex // dockerClient is the client for performing docker health checks. dockerClient *checks.DockerClient @@ -358,6 +359,7 @@ func New(bd BaseDeps) (*Agent, error) { retryJoinCh: make(chan error), shutdownCh: make(chan struct{}), endpoints: make(map[string]string), + stateLock: mutex.New(), baseDeps: bd, tokens: bd.Tokens, diff --git a/agent/service_manager.go b/agent/service_manager.go index 21addb0297..591c0981f8 100644 --- a/agent/service_manager.go +++ b/agent/service_manager.go @@ -292,11 +292,12 @@ func (w *serviceConfigWatch) handleUpdate(ctx context.Context, event cache.Updat persistServiceDefaults: serviceDefaults, } - w.agent.stateLock.Lock() + if err := w.agent.stateLock.TryLock(ctx); err != nil { + return nil + } defer w.agent.stateLock.Unlock() - // While we were waiting on the agent state lock we may have been shutdown. - // So avoid doing a registration in that case. + // The context may have been cancelled after the lock was acquired. if err := ctx.Err(); err != nil { return nil }