Skip to content

Commit

Permalink
Add HTTP health check handler for server health monitoring (#952)
Browse files Browse the repository at this point in the history
Added the handler to allow health checks to be performed with plain HTTP GET
requests needed for traditional uptime checker or load balancer, along with
existing gRPC health check.
  • Loading branch information
taeng0204 authored and hackerwins committed Aug 8, 2024
1 parent e1fbcf3 commit 1c88649
Show file tree
Hide file tree
Showing 3 changed files with 164 additions and 12 deletions.
69 changes: 69 additions & 0 deletions server/rpc/httphealth/httphealth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* Copyright 2024 The Yorkie Authors. All rights reserved.
*
* 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.
*/

// Package httphealth uses http GET to provide a health check for the server.
package httphealth

import (
"encoding/json"
"net/http"

"connectrpc.com/grpchealth"
)

// serviceName is the path for the health check endpoint.
const serviceName = "/healthz/"

// CheckResponse represents the response structure for health checks.
type CheckResponse struct {
Status string `json:"status"`
}

// NewHandler creates a new HTTP handler for health checks.
func NewHandler(checker grpchealth.Checker) (string, http.Handler) {
check := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}

var checkRequest grpchealth.CheckRequest
if service := r.URL.Query().Get("service"); service != "" {
checkRequest.Service = service
}

checkResponse, err := checker.Check(r.Context(), &checkRequest)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}

resp, err := json.Marshal(CheckResponse{checkResponse.Status.String()})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)

if _, err := w.Write(resp); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})

return serviceName, check
}
15 changes: 9 additions & 6 deletions server/rpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import (
"github.com/yorkie-team/yorkie/server/backend"
"github.com/yorkie-team/yorkie/server/logging"
"github.com/yorkie-team/yorkie/server/rpc/auth"
"github.com/yorkie-team/yorkie/server/rpc/httphealth"
"github.com/yorkie-team/yorkie/server/rpc/interceptors"
)

Expand All @@ -62,16 +63,18 @@ func NewServer(conf *Config, be *backend.Backend) (*Server, error) {
),
}

yorkieServiceCtx, yorkieServiceCancel := context.WithCancel(context.Background())
mux := http.NewServeMux()
mux.Handle(v1connect.NewYorkieServiceHandler(newYorkieServer(yorkieServiceCtx, be), opts...))
mux.Handle(v1connect.NewAdminServiceHandler(newAdminServer(be, tokenManager), opts...))
mux.Handle(grpchealth.NewHandler(grpchealth.NewStaticChecker(
healthChecker := grpchealth.NewStaticChecker(
grpchealth.HealthV1ServiceName,
v1connect.YorkieServiceName,
v1connect.AdminServiceName,
)))
)

yorkieServiceCtx, yorkieServiceCancel := context.WithCancel(context.Background())
mux := http.NewServeMux()
mux.Handle(v1connect.NewYorkieServiceHandler(newYorkieServer(yorkieServiceCtx, be), opts...))
mux.Handle(v1connect.NewAdminServiceHandler(newAdminServer(be, tokenManager), opts...))
mux.Handle(grpchealth.NewHandler(healthChecker))
mux.Handle(httphealth.NewHandler(healthChecker))
// TODO(hackerwins): We need to provide proper http server configuration.
return &Server{
conf: conf,
Expand Down
92 changes: 86 additions & 6 deletions test/integration/health_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,27 @@ package integration

import (
"context"
"encoding/json"
"net/http"
"testing"

"connectrpc.com/grpchealth"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
healthpb "google.golang.org/grpc/health/grpc_health_v1"

"github.com/yorkie-team/yorkie/api/yorkie/v1/v1connect"
"github.com/yorkie-team/yorkie/server/rpc/httphealth"
)

func TestHealthCheck(t *testing.T) {
// use gRPC health check
var services = []string{
grpchealth.HealthV1ServiceName,
v1connect.YorkieServiceName,
v1connect.AdminServiceName,
}

func TestRPCHealthCheck(t *testing.T) {
conn, err := grpc.Dial(
defaultServer.RPCAddr(),
grpc.WithTransportCredentials(insecure.NewCredentials()),
Expand All @@ -38,9 +49,78 @@ func TestHealthCheck(t *testing.T) {
defer func() {
assert.NoError(t, conn.Close())
}()

cli := healthpb.NewHealthClient(conn)
resp, err := cli.Check(context.Background(), &healthpb.HealthCheckRequest{})
assert.NoError(t, err)
assert.Equal(t, resp.Status, healthpb.HealthCheckResponse_SERVING)

// check default service
t.Run("Service: default", func(t *testing.T) {
resp, err := cli.Check(context.Background(), &healthpb.HealthCheckRequest{})
assert.NoError(t, err)
assert.Equal(t, resp.Status, healthpb.HealthCheckResponse_SERVING)
})

// check all services
for _, s := range services {
service := s
t.Run("Service: "+service, func(t *testing.T) {
resp, err := cli.Check(context.Background(), &healthpb.HealthCheckRequest{
Service: service,
})
assert.NoError(t, err)
assert.Equal(t, resp.Status, healthpb.HealthCheckResponse_SERVING)
})
}

// check unknown service
t.Run("Service: unknown", func(t *testing.T) {
_, err := cli.Check(context.Background(), &healthpb.HealthCheckRequest{
Service: "unknown",
})
assert.Error(t, err)
})
}

func TestHTTPHealthCheck(t *testing.T) {
// check default service
t.Run("Service: default", func(t *testing.T) {
resp, err := http.Get("http://" + defaultServer.RPCAddr() + "/healthz/")
assert.NoError(t, err)
defer func() {
assert.NoError(t, resp.Body.Close())
}()
assert.Equal(t, resp.StatusCode, http.StatusOK)

var healthResp httphealth.CheckResponse
err = json.NewDecoder(resp.Body).Decode(&healthResp)
assert.NoError(t, err)
assert.Equal(t, healthResp.Status, grpchealth.StatusServing.String())
})

// check all services
for _, s := range services {
service := s
t.Run("Service: "+service, func(t *testing.T) {
url := "http://" + defaultServer.RPCAddr() + "/healthz/?service=" + service
resp, err := http.Get(url)
assert.NoError(t, err)
defer func() {
assert.NoError(t, resp.Body.Close())
}()
assert.Equal(t, resp.StatusCode, http.StatusOK)

var healthResp httphealth.CheckResponse
err = json.NewDecoder(resp.Body).Decode(&healthResp)
assert.NoError(t, err)
assert.Equal(t, healthResp.Status, grpchealth.StatusServing.String())
})
}

// check unknown service
t.Run("Service: unknown", func(t *testing.T) {
resp, err := http.Get("http://" + defaultServer.RPCAddr() + "/healthz/?service=unknown")
assert.NoError(t, err)
defer func() {
assert.NoError(t, resp.Body.Close())
}()
assert.Equal(t, resp.StatusCode, http.StatusNotFound)
})
}

0 comments on commit 1c88649

Please sign in to comment.