Skip to content

Commit

Permalink
healthcheck is highly configurable
Browse files Browse the repository at this point in the history
  • Loading branch information
wsalles committed Dec 2, 2021
1 parent 2c13be2 commit 68844f0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 15 deletions.
44 changes: 30 additions & 14 deletions pkg/common/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,20 @@ import (
"net/http"
"os"
"os/signal"
"sync/atomic"
"syscall"

"github.com/gin-gonic/gin"
"github.com/ydataai/go-core/pkg/common/helpers"
"github.com/ydataai/go-core/pkg/common/logging"
)

// Server defines a struct for server
type Server struct {
logger logging.Logger
Router *gin.Engine
httpServer *http.Server
configuration HTTPServerConfiguration
readyzAvailable atomic.Value
logger logging.Logger
Router *gin.Engine
httpServer *http.Server
configuration HTTPServerConfiguration
readyzFunc func() bool
}

// NewServer initializes a server
Expand Down Expand Up @@ -89,19 +89,35 @@ func (s *Server) RunSecurely(ctx context.Context) {
}

// AddHealthz creates a route to LivenessProbe
func (s *Server) AddHealthz() {
s.Router.GET(s.configuration.HealthzEndpoint, s.healthz())
func (s *Server) AddHealthz(urls ...string) {
url := getURLAddress(urls, s.configuration.HealthzEndpoint, "/healthz")

s.Router.GET(url, s.healthz())
}

// AddReadyz creates a route to ReadinessProbe
func (s *Server) AddReadyz() {
func (s *Server) AddReadyz(status func() bool, urls ...string) {
// Readyz probe is negative by default
s.readyzAvailable.Store(false)
s.readyzFunc = status

url := getURLAddress(urls, s.configuration.ReadyzEndpoint, "/readyz")

s.Router.GET(s.configuration.ReadyzEndpoint, s.readyz())
s.Router.GET(url, s.readyz())
}

// SetReadyzState enables/disables readyz
func (s *Server) SetReadyzState(state bool) {
s.readyzAvailable.Store(state)
// getURLAddress requests a url address in order: parameter > env var > default
func getURLAddress(urls []string, environ, _default string) string {
param := helpers.FirstStringOfArray(urls)

var url string
switch {
case param != "":
url = param
case environ != "`":
url = environ
default:
url = "/readyz"
}

return url
}
2 changes: 1 addition & 1 deletion pkg/common/server/server_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func (s *Server) healthz() gin.HandlerFunc {
// readyz is a readiness probe
func (s *Server) readyz() gin.HandlerFunc {
return func(ctx *gin.Context) {
if !s.readyzAvailable.Load().(bool) {
if !s.readyzFunc() {
http.Error(ctx.Writer, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
Expand Down

0 comments on commit 68844f0

Please sign in to comment.