-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathobserver.go
More file actions
112 lines (94 loc) · 2.17 KB
/
observer.go
File metadata and controls
112 lines (94 loc) · 2.17 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package health
import (
"context"
"fmt"
"strings"
"sync"
"time"
)
// CheckResult comprises a single result from a health check
type CheckResult struct {
Name string
Error error
}
func (c CheckResult) String() string {
status := "ok"
if c.Error != nil {
status = c.Error.Error()
}
return fmt.Sprintf("%s: %s", c.Name, status)
}
// CheckStatus comprises multiple check results as well as the overall successful value as arising from the component results
type CheckStatus struct {
Successful bool
Results []CheckResult
}
func (c CheckStatus) String() string {
b := strings.Builder{}
for _, result := range c.Results {
b.WriteString(fmt.Sprintf("%s\n", result.String())) //nolint:revive
}
return b.String()
}
type Observer struct {
checks []Check
checkLock sync.RWMutex
runInterval time.Duration
runLock sync.RWMutex
runStatus *CheckStatus
}
func NewObserver(interval time.Duration) *Observer {
return &Observer{
checks: []Check{},
runInterval: interval,
}
}
func (c *Observer) AddChecks(checks ...Check) {
c.checkLock.Lock()
c.checks = append(c.checks, checks...)
c.checkLock.Unlock()
}
func (c *Observer) Status() *CheckStatus {
c.runLock.RLock()
defer c.runLock.RUnlock()
return c.runStatus
}
func (c *Observer) Run(ctx context.Context) error {
t := time.NewTicker(c.runInterval)
defer t.Stop()
// collect initial checks before we start listening to the ticker
initialStatus := c.collectChecks(ctx)
c.runLock.Lock()
c.runStatus = initialStatus
c.runLock.Unlock()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-t.C:
lastStatus := c.collectChecks(ctx)
c.runLock.Lock()
c.runStatus = lastStatus
c.runLock.Unlock()
}
}
}
func (c *Observer) collectChecks(ctx context.Context) *CheckStatus {
c.checkLock.RLock()
defer c.checkLock.RUnlock()
runStatus := &CheckStatus{
Successful: true,
Results: []CheckResult{},
}
for _, check := range c.checks {
err := check.HealthCheck(ctx)
if runStatus.Successful && err != nil {
runStatus.Successful = false
}
runStatus.Results = append(runStatus.Results, CheckResult{
Name: check.HealthCheckName(),
Error: err,
})
}
return runStatus
}