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

Add health check for gameserver-sidecar. #44

Merged
merged 1 commit into from
Jan 8, 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
11 changes: 11 additions & 0 deletions gameservers/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import (
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
Expand Down Expand Up @@ -360,6 +361,16 @@ func (c *Controller) syncGameServerCreatingState(gs *stablev1alpha1.GameServer)
},
},
},
LivenessProbe: &corev1.Probe{
Handler: corev1.Handler{
HTTPGet: &corev1.HTTPGetAction{
Path: "/healthz",
Port: intstr.FromInt(8080),
},
},
InitialDelaySeconds: 3,
PeriodSeconds: 3,
},
}
if c.alwaysPullSidecarImage {
sidecar.ImagePullPolicy = corev1.PullAlways
Expand Down
2 changes: 0 additions & 2 deletions gameservers/controller/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,8 +382,6 @@ func TestSyncGameServerBlankState(t *testing.T) {
}

func TestSyncGameServerCreatingState(t *testing.T) {
t.Parallel()

newFixture := func() *v1alpha1.GameServer {
fixture := &v1alpha1.GameServer{ObjectMeta: metav1.ObjectMeta{Name: "test", Namespace: "default"},
Spec: newSingeContainerSpec(), Status: v1alpha1.GameServerStatus{State: v1alpha1.Creating}}
Expand Down
15 changes: 14 additions & 1 deletion gameservers/sidecar/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ import (

"github.com/agonio/agon/gameservers/sidecar/sdk"
"github.com/agonio/agon/pkg"
"github.com/agonio/agon/pkg/client/clientset/versioned"
"github.com/agonio/agon/pkg/util/runtime"
"github.com/sirupsen/logrus"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"golang.org/x/net/context"
"google.golang.org/grpc"
"k8s.io/client-go/rest"
)

const (
Expand Down Expand Up @@ -68,13 +70,24 @@ func main() {
if isLocal {
sdk.RegisterSDKServer(grpcServer, &Local{})
} else {
config, err := rest.InClusterConfig()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This error is never checked. A great tool to check these type of things, which is also baked into the build image, and can be invoked in the shell is gometalinter

For example:

root@fd84b110807c:/go/src/github.com/agonio/agon# gometalinter ./gameservers/sidecar/ --deadline=1h
gameservers/sidecar/main.go:73:11:warning: ineffectual assignment to err (ineffassign)
gameservers/sidecar/main.go:73:11:warning: this value of err is never used (SA4006) (megacheck)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, in case I wasn't clear on this one - we should check the error, and Fatalfif it fails.

It would be bad canonical Go not to process an error 😢

if err != nil {
logrus.WithError(err).Fatal("Could not create in cluster config")
}

agonClient, err := versioned.NewForConfig(config)
if err != nil {
logrus.WithError(err).Fatalf("Could not create the agon api clientset")
}

var s *Sidecar
s, err = NewSidecar(viper.GetString(gameServerNameEnv), viper.GetString(podNamespaceEnv))
s, err = NewSidecar(viper.GetString(gameServerNameEnv), viper.GetString(podNamespaceEnv), agonClient)
if err != nil {
logrus.WithError(err).Fatalf("Could not start sidecar")
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go s.Run(ctx.Done())
sdk.RegisterSDKServer(grpcServer, s)
}
Expand Down
40 changes: 29 additions & 11 deletions gameservers/sidecar/sidecar.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package main

import (
"fmt"
"net/http"
"time"

"github.com/agonio/agon/gameservers/sidecar/sdk"
Expand All @@ -29,7 +30,6 @@ import (
"golang.org/x/net/context"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/rest"
"k8s.io/client-go/util/workqueue"
)

Expand All @@ -42,25 +42,29 @@ type Sidecar struct {
namespace string
gameServerGetter typedv1alpha1.GameServersGetter
queue workqueue.RateLimitingInterface
server *http.Server
}

// NewSidecar creates a Sidecar that sets up an
// InClusterConfig for Kubernetes
func NewSidecar(gameServerName, namespace string) (*Sidecar, error) {
config, err := rest.InClusterConfig()
if err != nil {
return nil, errors.Wrap(err, "Could not create Kubernetes in cluster config")
}

agonClient, err := versioned.NewForConfig(config)
if err != nil {
return nil, errors.Wrap(err, "Could not create the agon api clientset")
}
func NewSidecar(gameServerName, namespace string, agonClient versioned.Interface) (*Sidecar, error) {
mux := http.NewServeMux()
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
_, err := w.Write([]byte("ok"))
if err != nil {
logrus.WithError(err).Error("could not send ok response on healthz")
w.WriteHeader(http.StatusInternalServerError)
}
})

s := &Sidecar{
gameServerName: gameServerName,
namespace: namespace,
gameServerGetter: agonClient.StableV1alpha1(),
server: &http.Server{
Addr: ":8080",
Handler: mux,
},
}

s.queue = s.newWorkQueue()
Expand All @@ -79,6 +83,20 @@ func (s *Sidecar) newWorkQueue() workqueue.RateLimitingInterface {
// Will block until stop is closed
func (s *Sidecar) Run(stop <-chan struct{}) {
defer s.queue.ShutDown()

logrus.Info("Starting health check...")
go func() {
if err := s.server.ListenAndServe(); err != nil {
if err == http.ErrServerClosed {
logrus.WithError(err).Info("health check: http server closed")
} else {
err := errors.Wrap(err, "Could not listen on :8080")
runtime.HandleError(logrus.WithError(err), err)
}
}
}()
defer s.server.Close() // nolint: errcheck

logrus.Info("Starting worker")
wait.Until(s.runWorker, time.Second, stop)
<-stop
Expand Down
33 changes: 25 additions & 8 deletions gameservers/sidecar/sidecar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package main

import (
"io/ioutil"
"net/http"
"testing"
"time"

Expand All @@ -28,8 +30,6 @@ import (
)

func TestSidecarRun(t *testing.T) {
t.Parallel()

fixtures := map[string]struct {
state v1alpha1.State
f func(*Sidecar, context.Context)
Expand Down Expand Up @@ -71,12 +71,8 @@ func TestSidecarRun(t *testing.T) {
return true, gs, nil
})

sc := &Sidecar{
gameServerName: "test",
namespace: "default",
gameServerGetter: agonClient.StableV1alpha1(),
}
sc.queue = sc.newWorkQueue()
sc, err := NewSidecar("test", "default", agonClient)
assert.Nil(t, err)

ctx, cancel := context.WithCancel(context.Background())
defer cancel()
Expand All @@ -93,3 +89,24 @@ func TestSidecarRun(t *testing.T) {
})
}
}

func TestHealthCheck(t *testing.T) {
agonClient := &fake.Clientset{}

sc, err := NewSidecar("test", "default", agonClient)
assert.Nil(t, err)

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go sc.Run(ctx.Done())
resp, err := http.Get("http://localhost:8080/healthz")
assert.Nil(t, err, "health check error should be nil: %s", err)
assert.NotNil(t, resp)
if resp != nil {
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
assert.Nil(t, err, "read response error should be nil")
assert.Equal(t, []byte("ok"), body, "response body should be 'ok'")
}
}