-
Notifications
You must be signed in to change notification settings - Fork 1
/
service_health.go
76 lines (61 loc) · 1.46 KB
/
service_health.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
package health
import (
"sync"
"github.com/sirupsen/logrus"
)
type ServiceHealth struct {
components map[string]componentHealth
logger *logrus.Logger
mux sync.RWMutex
}
func newServiceHealth(logger *logrus.Logger) *ServiceHealth {
return &ServiceHealth{
components: make(map[string]componentHealth),
logger: logger,
}
}
func (s *ServiceHealth) isHealthy() (bool, string) {
for _, component := range s.components {
if !component.healthy {
return false, component.reason
}
}
return true, ""
}
func (s *ServiceHealth) IsHealthy(component ...string) (bool, string) {
s.mux.RLock()
defer s.mux.RUnlock()
if len(component) == 0 {
return s.isHealthy()
}
for _, c := range component {
if ch, ok := s.components[c]; ok && !ch.healthy {
return false, s.components[c].reason
}
}
return true, ""
}
func (s *ServiceHealth) SetHealthy(component string) {
s.mux.Lock()
defer s.mux.Unlock()
componentHealth := componentHealth{
healthy: true,
}
s.components[component] = componentHealth
s.logger.WithFields(logrus.Fields{
"component": component,
}).Warn("Component is healthy (again)")
}
func (s *ServiceHealth) SetUnhealthy(component string, reason string) {
s.mux.Lock()
defer s.mux.Unlock()
componentHealth := componentHealth{
healthy: false,
reason: reason,
}
s.components[component] = componentHealth
s.logger.WithFields(logrus.Fields{
"component": component,
"reason": reason,
}).Warn("Component became unhealthy")
}