Skip to content

Commit

Permalink
Merge pull request #66 from getamis/proxy-health
Browse files Browse the repository at this point in the history
Proxy health
  • Loading branch information
markya0616 authored Feb 15, 2019
2 parents 90abfb0 + 1c4df11 commit 7741ea7
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 14 deletions.
17 changes: 3 additions & 14 deletions health/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,20 +58,9 @@ func (s *server) Liveness(ctx context.Context, req *EmptyRequest) (*EmptyRespons

// Readiness is represented that whether application is ready to start accepting traffic or not.
func (s *server) Readiness(ctx context.Context, req *EmptyRequest) (*EmptyResponse, error) {
if len(s.checkFns) == 0 {
return nil, nil
}
errCh := make(chan error, len(s.checkFns))
for _, checker := range s.checkFns {
go func(checker CheckFn) {
errCh <- checker(ctx)
}(checker)
}
for range s.checkFns {
if err := <-errCh; err != nil {
log.Error("Failed to check readiness", "err", err)
return nil, status.Error(codes.Unavailable, err.Error())
}
if err := CheckHealth(ctx, s.checkFns); err != nil {
log.Error("Failed to check readiness", "err", err)
return nil, status.Error(codes.Unavailable, err.Error())
}
return nil, nil
}
35 changes: 35 additions & 0 deletions health/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package health

import (
"context"
"net/http"
"time"

"github.com/getamis/sirius/log"
Expand All @@ -41,3 +42,37 @@ func GRPCServerHealthChecker(addr, serviceName string) CheckFn {
return nil
}
}

func CheckHealth(ctx context.Context, checkFns []CheckFn) error {
if len(checkFns) == 0 {
return nil
}
errCh := make(chan error, len(checkFns))
for _, checker := range checkFns {
go func(checker CheckFn) {
errCh <- checker(ctx)
}(checker)
}
for range checkFns {
if err := <-errCh; err != nil {
log.Error("Failed to check readiness", "err", err)
return err
}
}
return nil
}

// SetLivenessAndReadiness sets the liveness and readiness route in http server mux
func SetLivenessAndReadiness(mux *http.ServeMux, checkFns ...CheckFn) {
mux.HandleFunc("/readiness", func(rw http.ResponseWriter, r *http.Request) {
if err := CheckHealth(r.Context(), checkFns); err != nil {
log.Error("Failed to check readiness", "err", err)
rw.WriteHeader(http.StatusServiceUnavailable)
return
}
rw.WriteHeader(http.StatusOK)
})
mux.HandleFunc("/liveness", func(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(http.StatusOK)
})
}

0 comments on commit 7741ea7

Please sign in to comment.