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 HTTP health check handler for server health monitoring #952

Merged
merged 7 commits into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
62 changes: 62 additions & 0 deletions server/rpc/health/health.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
* 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 health uses http GET to provide a health check for the server.
package health

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

"connectrpc.com/grpchealth"
)

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

// NewHTTPHandler creates a new HTTP handler for health checks.
func NewHTTPHandler(checker grpchealth.Checker) (string, http.Handler) {
const serviceName = "/healthz/"
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
service := r.URL.Query().Get("service")
if 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/health"
"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(health.NewHTTPHandler(healthChecker))
krapie marked this conversation as resolved.
Show resolved Hide resolved
// TODO(hackerwins): We need to provide proper http server configuration.
return &Server{
conf: conf,
Expand Down
91 changes: 85 additions & 6 deletions test/integration/health_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,26 @@ package integration

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

"connectrpc.com/grpchealth"
"github.com/stretchr/testify/assert"
"github.com/yorkie-team/yorkie/api/yorkie/v1/v1connect"
"github.com/yorkie-team/yorkie/server/rpc/health"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
)

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 +48,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 health.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 health.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)
})
}
Loading