This repository was archived by the owner on Mar 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgroup.go
80 lines (65 loc) · 1.67 KB
/
group.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
package healing
import (
"context"
"sync/atomic"
"time"
"github.com/moeryomenko/synx"
)
const defaultCheckTimeout = 2 * time.Second
// CheckGroup launch checker concurrently.
type CheckGroup struct {
checkers map[string]checkFunc
timeout time.Duration
status atomic.Bool
checkStatuses map[string]CheckResult
mu synx.Spinlock
}
// NewCheckGroup returns new instacnce CheckGroup.
func NewCheckGroup(timeout time.Duration) *CheckGroup {
group := &CheckGroup{
timeout: timeout,
checkers: make(map[string]checkFunc),
checkStatuses: make(map[string]CheckResult),
}
return group
}
// AddChecker adds checker to CheckGroup.
func (g *CheckGroup) AddChecker(subsystem string, checker checkFunc) {
g.checkers[subsystem] = checker
}
// Check runs checkers.
func (g *CheckGroup) Check(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, g.timeout)
defer cancel()
group := synx.NewCtxGroup(ctx)
// NOTE: flush status before checks.
g.status.Store(true)
for subsystem, checker := range g.checkers {
subsystem := subsystem
checker := checker
group.Go(func(ctx context.Context) error {
res := checker(ctx)
g.setStatus(subsystem, res)
return res.Error
})
}
err := group.Wait()
if err != nil {
g.status.Store(false)
}
}
// GetDetails returns result of checks.
func (g *CheckGroup) GetDetails() map[string]CheckResult {
g.mu.Lock()
defer g.mu.Unlock()
return g.checkStatuses
}
// IsOK returns true if all checks passed normal.
func (g *CheckGroup) IsOK() bool {
return g.status.Load()
}
func (g *CheckGroup) setStatus(subsystem string, status CheckResult) {
g.mu.Lock()
g.checkStatuses[subsystem] = status
g.mu.Unlock()
}