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

feat: Include HealthCheck in server pkg #44

Merged
merged 7 commits into from
Dec 2, 2021
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
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ require (
github.com/prometheus/client_golang v1.11.0
github.com/prometheus/common v0.26.0
github.com/sirupsen/logrus v1.8.1
google.golang.org/grpc v1.41.0
google.golang.org/protobuf v1.27.1
k8s.io/api v0.22.2
k8s.io/apimachinery v0.22.2
k8s.io/utils v0.0.0-20210930125809-cb0fa318a74b
Expand Down Expand Up @@ -90,6 +88,8 @@ require (
gomodules.xyz/jsonpatch/v2 v2.2.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c // indirect
google.golang.org/grpc v1.41.0 // indirect
google.golang.org/protobuf v1.27.1 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/square/go-jose.v2 v2.5.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
Expand Down
6 changes: 3 additions & 3 deletions pkg/common/server/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ func (s Server) tracing() gin.HandlerFunc {
requestID = ctx.Request.Header.Get("X-Request-Id")
}

s.log.Infof("Path: %v", ctx.Request.URL.Path)
s.log.Infof("X-Request-Id: %v", requestID)
s.logger.Infof("Path: %v", ctx.Request.URL.Path)
s.logger.Infof("X-Request-Id: %v", requestID)
ctx.Set("X-Request-Id", requestID)
ctx.Next()
}
Expand All @@ -28,7 +28,7 @@ func (s Server) NamespaceValidation() gin.HandlerFunc {

if namespace == "" {
errM := "missing namespace as query param."
s.log.Error(errM)
s.logger.Error(errM)
c.JSON(http.StatusBadRequest, errM)
c.Abort()
return
Expand Down
40 changes: 29 additions & 11 deletions pkg/common/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,19 @@ import (

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

// NewServer initializes a server
func NewServer(log logging.Logger, configuration HTTPServerConfiguration) *Server {
func NewServer(logger logging.Logger, configuration HTTPServerConfiguration) *Server {
router := gin.Default()

s := &Server{
log: log,
logger: logger,
configuration: configuration,
}

Expand All @@ -48,40 +49,57 @@ func NewServer(log logging.Logger, configuration HTTPServerConfiguration) *Serve
func (s *Server) Run(ctx context.Context) {
go func() {
if err := s.httpServer.ListenAndServe(); err != http.ErrServerClosed {
s.log.Errorf("unexpected error while running server %v", err)
s.logger.Errorf("unexpected error while running server %v", err)
}

c := make(chan os.Signal, 3)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c

s.log.Infof("Shutdown Server ...")
s.logger.Infof("Shutdown Server ...")

if err := s.httpServer.Shutdown(ctx); err != nil {
s.log.Fatal("Server forced to shutdown: ", err)
s.logger.Fatal("Server forced to shutdown: ", err)
}

s.log.Infof("Server exiting")
s.logger.Infof("Server exiting")
}()
}

// RunSecurely when called starts the https server
func (s *Server) RunSecurely(ctx context.Context) {
go func() {
if err := s.httpServer.ListenAndServeTLS(s.configuration.CertificateFile, s.configuration.CertificateKeyFile); err != http.ErrServerClosed {
s.log.Errorf("unexpected error while running server %v", err.Error())
s.logger.Errorf("unexpected error while running server %v", err.Error())
}

c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c

s.log.Infof("Shutdown Server ...")
s.logger.Infof("Shutdown Server ...")

if err := s.httpServer.Shutdown(ctx); err != nil {
s.log.Fatalf("Server forced to shutdown: %v", err)
s.logger.Fatalf("Server forced to shutdown: %v", err)
}

s.log.Infof("Server exiting")
s.logger.Infof("Server exiting")
}()
}

// AddHealthz creates a route to LivenessProbe
func (s *Server) AddHealthz(urls ...string) {
url := firstStringOfArrayWithFallback(urls, s.configuration.HealthzEndpoint)

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

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

url := firstStringOfArrayWithFallback(urls, s.configuration.ReadyzEndpoint)

s.Router.GET(url, s.readyz())
}
4 changes: 3 additions & 1 deletion pkg/common/server/server_configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ type HTTPServerConfiguration struct {
Host string `envconfig:"HTTP_HOST" default:""`
Port int `envconfig:"HTTP_PORT" default:"80"`
RequestTimeout time.Duration `envconfig:"HTTP_REQUEST_TIMEOUT" default:"30s"`
UserID string `envconfig:"USER_ID" required:"true"`
UserID string `envconfig:"USER_ID" default:""`
CertificateFile string `envconfig:"CERTIFICATE_FILE" default:"/etc/tls/tls.crt"`
CertificateKeyFile string `envconfig:"CERTIFICATE_KEY_FILE" default:"/etc/tls/tls.key"`
HealthzEndpoint string `envconfig:"HEALTHZ_ENDPOINT" default:"/healthz"`
ReadyzEndpoint string `envconfig:"READYZ_ENDPOINT" default:"/readyz"`
}

// LoadFromEnvVars reads all env vars required for the server package
Expand Down
33 changes: 33 additions & 0 deletions pkg/common/server/server_handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package server

import (
"net/http"

"github.com/gin-gonic/gin"
)

// healthz is a liveness probe
func (s *Server) healthz() gin.HandlerFunc {
return func(ctx *gin.Context) {
ctx.Status(http.StatusNoContent)
}
}

// readyz is a readiness probe
func (s *Server) readyz() gin.HandlerFunc {
return func(ctx *gin.Context) {
if !s.readyzFunc() {
http.Error(ctx.Writer, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
ctx.Status(http.StatusNoContent)
}
}

// firstStringOfArrayWithFallback is a handle to get the first position of the array with fallback
func firstStringOfArrayWithFallback(list []string, fallback string) string {
if len(list) > 0 {
return list[0]
}
return fallback
}