-
Notifications
You must be signed in to change notification settings - Fork 1
/
health_server.go
96 lines (82 loc) · 2.49 KB
/
health_server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package server
import (
"context"
"encoding/json"
"github.com/jmoiron/sqlx"
"github.com/ozonva/ova-journey-api/internal/config"
"github.com/ozonva/ova-journey-api/internal/kafka"
"github.com/rs/zerolog/log"
"net/http"
"sync"
)
// HealthServer - represents simple http server for checking health
type HealthServer struct {
healthcheckConfiguration *config.HealthCheckConfiguration
httpServer *http.Server
wg *sync.WaitGroup
producer kafka.Producer
db *sqlx.DB
}
// NewHealthServer - creates new HealthServer with configuration parameters
func NewHealthServer(healthcheckConfiguration *config.HealthCheckConfiguration, producer kafka.Producer, db *sqlx.DB) *HealthServer {
return &HealthServer{
healthcheckConfiguration: healthcheckConfiguration,
producer: producer,
db: db,
}
}
// Start - start HealthServer
func (s *HealthServer) Start() {
mux := http.NewServeMux()
mux.HandleFunc(s.healthcheckConfiguration.Path, s.healthHandler())
s.httpServer = &http.Server{
Addr: s.healthcheckConfiguration.GetEndpointAddress(),
Handler: mux,
}
s.wg = &sync.WaitGroup{}
go func() {
log.Debug().Msg("HealthServer: starting")
s.wg.Add(1)
err := s.httpServer.ListenAndServe()
if err == http.ErrServerClosed {
s.wg.Done()
return
}
if err != nil {
log.Err(err).Msg("HealthServer: failed to serve")
}
}()
}
// Stop - graceful stop HealthServer with waiting of http server is stopped
func (s *HealthServer) Stop() {
if err := s.httpServer.Shutdown(context.Background()); err != nil {
log.Err(err).Msg("HealthServer: shutdown failed")
}
s.wg.Wait()
}
func (s *HealthServer) healthHandler() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
servicesState := make([]string, 0, 2)
servicesState = append(servicesState, s.checkDbHealth())
servicesState = append(servicesState, s.checkKafkaHealth())
err := json.NewEncoder(w).Encode(servicesState)
if err != nil {
log.Error().Err(err).Msg("Error in encoding internal services state")
w.WriteHeader(http.StatusInternalServerError)
}
}
}
func (s *HealthServer) checkDbHealth() string {
_, err := s.db.Query("SELECT 1")
if err != nil {
return "DB: Failed"
}
return "DB: OK"
}
func (s *HealthServer) checkKafkaHealth() string {
err := s.producer.Send(kafka.Message{MessageType: kafka.Ping, Value: "1"})
if err != nil {
return "Kafka: Failed"
}
return "Kafka: OK"
}