Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved liveness detection #115

Merged
merged 1 commit into from
Apr 5, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,9 @@ run-unit-tests: $(GOBUILDDIR) $(SOURCES)
$(REPOPATH)/pkg/deployment/reconcile \
$(REPOPATH)/pkg/deployment/resources \
$(REPOPATH)/pkg/util/k8sutil \
$(REPOPATH)/pkg/util/k8sutil/test
$(REPOPATH)/pkg/util/k8sutil/test \
$(REPOPATH)/pkg/util/probe \
$(REPOPATH)/pkg/util/validation

$(TESTBIN): $(GOBUILDDIR) $(SOURCES)
@mkdir -p $(BINDIR)
Expand Down
8 changes: 5 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,9 @@ var (
chaosOptions struct {
allowed bool
}
deploymentProbe probe.Probe
storageProbe probe.Probe
livenessProbe probe.LivenessProbe
deploymentProbe probe.ReadyProbe
storageProbe probe.ReadyProbe
)

func init() {
Expand Down Expand Up @@ -154,7 +155,7 @@ func cmdMainRun(cmd *cobra.Command, args []string) {
}

mux := http.NewServeMux()
mux.HandleFunc("/health", probe.LivenessHandler)
mux.HandleFunc("/health", livenessProbe.LivenessHandler)
mux.HandleFunc("/ready/deployment", deploymentProbe.ReadyHandler)
mux.HandleFunc("/ready/storage", storageProbe.ReadyHandler)
mux.Handle("/metrics", prometheus.Handler())
Expand Down Expand Up @@ -222,6 +223,7 @@ func newOperatorConfigAndDeps(id, namespace, name string) (operator.Config, oper
KubeExtCli: kubeExtCli,
CRCli: crCli,
EventRecorder: eventRecorder,
LivenessProbe: &livenessProbe,
DeploymentProbe: &deploymentProbe,
StorageProbe: &storageProbe,
}
Expand Down
5 changes: 3 additions & 2 deletions pkg/operator/operator.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,9 @@ type Dependencies struct {
KubeExtCli apiextensionsclient.Interface
CRCli versioned.Interface
EventRecorder record.EventRecorder
DeploymentProbe *probe.Probe
StorageProbe *probe.Probe
LivenessProbe *probe.LivenessProbe
DeploymentProbe *probe.ReadyProbe
StorageProbe *probe.ReadyProbe
}

// NewOperator instantiates a new operator from given config & dependencies.
Expand Down
9 changes: 9 additions & 0 deletions pkg/operator/operator_deployment.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ func (o *Operator) runDeployments(stop <-chan struct{}) {

// onAddArangoDeployment deployment addition callback
func (o *Operator) onAddArangoDeployment(obj interface{}) {
o.Dependencies.LivenessProbe.Lock()
defer o.Dependencies.LivenessProbe.Unlock()

apiObject := obj.(*api.ArangoDeployment)
o.log.Debug().
Str("name", apiObject.GetObjectMeta().GetName()).
Expand All @@ -73,6 +76,9 @@ func (o *Operator) onAddArangoDeployment(obj interface{}) {

// onUpdateArangoDeployment deployment update callback
func (o *Operator) onUpdateArangoDeployment(oldObj, newObj interface{}) {
o.Dependencies.LivenessProbe.Lock()
defer o.Dependencies.LivenessProbe.Unlock()

apiObject := newObj.(*api.ArangoDeployment)
o.log.Debug().
Str("name", apiObject.GetObjectMeta().GetName()).
Expand All @@ -82,6 +88,9 @@ func (o *Operator) onUpdateArangoDeployment(oldObj, newObj interface{}) {

// onDeleteArangoDeployment deployment delete callback
func (o *Operator) onDeleteArangoDeployment(obj interface{}) {
o.Dependencies.LivenessProbe.Lock()
defer o.Dependencies.LivenessProbe.Unlock()

log := o.log
apiObject, ok := obj.(*api.ArangoDeployment)
if !ok {
Expand Down
9 changes: 9 additions & 0 deletions pkg/operator/operator_local_storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ func (o *Operator) runLocalStorages(stop <-chan struct{}) {

// onAddArangoLocalStorage local storage addition callback
func (o *Operator) onAddArangoLocalStorage(obj interface{}) {
o.Dependencies.LivenessProbe.Lock()
defer o.Dependencies.LivenessProbe.Unlock()

apiObject := obj.(*api.ArangoLocalStorage)
o.log.Debug().
Str("name", apiObject.GetObjectMeta().GetName()).
Expand All @@ -73,6 +76,9 @@ func (o *Operator) onAddArangoLocalStorage(obj interface{}) {

// onUpdateArangoLocalStorage local storage update callback
func (o *Operator) onUpdateArangoLocalStorage(oldObj, newObj interface{}) {
o.Dependencies.LivenessProbe.Lock()
defer o.Dependencies.LivenessProbe.Unlock()

apiObject := newObj.(*api.ArangoLocalStorage)
o.log.Debug().
Str("name", apiObject.GetObjectMeta().GetName()).
Expand All @@ -82,6 +88,9 @@ func (o *Operator) onUpdateArangoLocalStorage(oldObj, newObj interface{}) {

// onDeleteArangoLocalStorage local storage delete callback
func (o *Operator) onDeleteArangoLocalStorage(obj interface{}) {
o.Dependencies.LivenessProbe.Lock()
defer o.Dependencies.LivenessProbe.Unlock()

log := o.log
apiObject, ok := obj.(*api.ArangoLocalStorage)
if !ok {
Expand Down
32 changes: 0 additions & 32 deletions pkg/util/probe/health.go

This file was deleted.

102 changes: 102 additions & 0 deletions pkg/util/probe/liveness.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
//
// DISCLAIMER
//
// Copyright 2018 ArangoDB GmbH, Cologne, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// Author Ewout Prangsma
//

package probe

import (
"net/http"
"sync"
"time"
)

const (
livenessHandlerTimeout = time.Second * 5
)

// LivenessProbe wraps a liveness probe handler.
type LivenessProbe struct {
lock int32
mutex sync.Mutex
waitChan chan struct{}
}

// Lock the probe, preventing the LivenessHandler from responding to requests.
func (p *LivenessProbe) Lock() {
p.mutex.Lock()
defer p.mutex.Unlock()

p.lock++
}

// Unlock the probe, allowing the LivenessHandler to respond to requests.
func (p *LivenessProbe) Unlock() {
p.mutex.Lock()
defer p.mutex.Unlock()

p.lock--

if p.lock == 0 && p.waitChan != nil {
w := p.waitChan
p.waitChan = nil
close(w)
}
}

// waitUntilNotLocked blocks until the probe is no longer locked
// or a timeout occurs.
// Returns true if the probe is unlocked, false on timeout.
func (p *LivenessProbe) waitUntilNotLocked(timeout time.Duration) bool {
deadline := time.Now().Add(timeout)
for {
var w chan struct{}
p.mutex.Lock()
locked := p.lock != 0
if locked {
if p.waitChan == nil {
p.waitChan = make(chan struct{})
}
w = p.waitChan
}
p.mutex.Unlock()
if !locked {
// All good
return true
}
// We're locked, wait until w is closed
select {
case <-w:
// continue
case <-time.After(time.Until(deadline)):
// Timeout
return false
}
}
}

// LivenessHandler writes back the HTTP status code 200 if the operator is ready, and 500 otherwise.
func (p *LivenessProbe) LivenessHandler(w http.ResponseWriter, r *http.Request) {
if p.waitUntilNotLocked(livenessHandlerTimeout) {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusInternalServerError)
}
}
82 changes: 82 additions & 0 deletions pkg/util/probe/liveness_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//
// DISCLAIMER
//
// Copyright 2018 ArangoDB GmbH, Cologne, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// Author Ewout Prangsma
//

package probe

import (
"sync"
"testing"
"time"

"github.com/stretchr/testify/assert"
)

func TestLivenessLock(t *testing.T) {
p := &LivenessProbe{}
assert.True(t, p.waitUntilNotLocked(time.Millisecond))

// Test single lock
p.Lock()
assert.False(t, p.waitUntilNotLocked(time.Millisecond))
p.Unlock()
assert.True(t, p.waitUntilNotLocked(time.Millisecond))

// Test multiple locks
p.Lock()
assert.False(t, p.waitUntilNotLocked(time.Millisecond))
p.Lock()
assert.False(t, p.waitUntilNotLocked(time.Millisecond))
p.Unlock()
assert.False(t, p.waitUntilNotLocked(time.Millisecond))
p.Unlock()
assert.True(t, p.waitUntilNotLocked(time.Millisecond))

// Test concurrent waits
wg := sync.WaitGroup{}
p.Lock()
wg.Add(1)
go func() {
// Waiter 1
defer wg.Done()
assert.True(t, p.waitUntilNotLocked(time.Millisecond*200))
}()
wg.Add(1)
go func() {
// Waiter 2
defer wg.Done()
assert.True(t, p.waitUntilNotLocked(time.Millisecond*200))
}()
wg.Add(1)
go func() {
// Waiter 3
defer wg.Done()
assert.False(t, p.waitUntilNotLocked(time.Millisecond*5))
}()
wg.Add(1)
go func() {
// Unlocker
defer wg.Done()
time.Sleep(time.Millisecond * 50)
p.Unlock()
}()
wg.Wait()
}
8 changes: 4 additions & 4 deletions pkg/util/probe/ready.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,18 @@ import (
"sync/atomic"
)

// Probe wraps a readiness probe handler.
type Probe struct {
// ReadyProbe wraps a readiness probe handler.
type ReadyProbe struct {
ready int32
}

// SetReady marks the probe as ready.
func (p *Probe) SetReady() {
func (p *ReadyProbe) SetReady() {
atomic.StoreInt32(&p.ready, 1)
}

// ReadyHandler writes back the HTTP status code 200 if the operator is ready, and 500 otherwise.
func (p *Probe) ReadyHandler(w http.ResponseWriter, r *http.Request) {
func (p *ReadyProbe) ReadyHandler(w http.ResponseWriter, r *http.Request) {
isReady := atomic.LoadInt32(&p.ready) != 0
if isReady {
w.WriteHeader(http.StatusOK)
Expand Down