-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathchecker.go
91 lines (74 loc) · 1.81 KB
/
checker.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
package health
import (
"sync"
)
// Checker is a interface used to provide an indication of application health.
type Checker interface {
Check() Health
}
// CheckerFunc is an adapter to allow the use of
// ordinary go functions as Checkers.
type CheckerFunc func() Health
func (f CheckerFunc) Check() Health {
return f()
}
type checkerItem struct {
name string
checker Checker
}
// CompositeChecker aggregate a list of Checkers
type CompositeChecker struct {
checkers []checkerItem
info map[string]interface{}
}
// NewCompositeChecker creates a new CompositeChecker
func NewCompositeChecker() CompositeChecker {
return CompositeChecker{}
}
// AddInfo adds a info value to the Info map
func (c *CompositeChecker) AddInfo(key string, value interface{}) *CompositeChecker {
if c.info == nil {
c.info = make(map[string]interface{})
}
c.info[key] = value
return c
}
// AddChecker add a Checker to the aggregator
func (c *CompositeChecker) AddChecker(name string, checker Checker) {
c.checkers = append(c.checkers, checkerItem{name: name, checker: checker})
}
// Check returns the combination of all checkers added
// if some check is not up, the combined is marked as down
func (c CompositeChecker) Check() Health {
health := NewHealth()
health.Up()
healths := make(map[string]interface{})
type state struct {
h Health
name string
}
ch := make(chan state, len(c.checkers))
var wg sync.WaitGroup
for _, item := range c.checkers {
wg.Add(1)
item := item
go func() {
ch <- state{h: item.checker.Check(), name: item.name}
wg.Done()
}()
}
wg.Wait()
close(ch)
for s := range ch {
if !s.h.IsUp() && !health.IsDown() {
health.Down()
}
healths[s.name] = s.h
}
health.info = healths
// Extra Info
for key, value := range c.info {
health.AddInfo(key, value)
}
return health
}