-
Notifications
You must be signed in to change notification settings - Fork 459
/
periodic.go
100 lines (82 loc) · 2.11 KB
/
periodic.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
97
98
99
100
// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Gardener contributors
//
// SPDX-License-Identifier: Apache-2.0
package healthz
import (
"context"
"sync"
"time"
"k8s.io/utils/clock"
)
// PeriodicHealthManagerName is the name of the periodic health manager.
const PeriodicHealthManagerName = "periodic"
// NewPeriodicHealthz returns a health manager that automatically sets the health status to false after the given reset
// duration. The timer is reset again when the health status is true (i.e., a running timer is reset and starts again
// from the beginning).
func NewPeriodicHealthz(clock clock.Clock, resetDuration time.Duration) Manager {
return &periodicHealthz{clock: clock, resetDuration: resetDuration}
}
type periodicHealthz struct {
clock clock.Clock
mutex sync.RWMutex
health bool
timer clock.Timer
resetDuration time.Duration
started bool
stopCh chan struct{}
}
// Name returns the name of the health manager.
func (p *periodicHealthz) Name() string {
return PeriodicHealthManagerName
}
// Start starts the health manager.
func (p *periodicHealthz) Start(_ context.Context) error {
p.mutex.Lock()
defer p.mutex.Unlock()
if p.started {
return nil
}
p.health = true
p.timer = p.clock.NewTimer(p.resetDuration)
p.started = true
p.stopCh = make(chan struct{})
go func() {
for {
select {
case <-p.timer.C():
p.Set(false)
case <-p.stopCh:
p.timer.Stop()
return
}
}
}()
return nil
}
// Stop stops the health manager.
func (p *periodicHealthz) Stop() {
p.mutex.Lock()
defer p.mutex.Unlock()
p.health = false
if !p.started {
return
}
close(p.stopCh)
p.started = false
}
// Get returns the current health status.
func (p *periodicHealthz) Get() bool {
p.mutex.RLock()
defer p.mutex.RUnlock()
return p.health
}
// Set sets the current health status. When the health status is 'true' and the manager is started then the timer is
// reset.
func (p *periodicHealthz) Set(health bool) {
p.mutex.Lock()
defer p.mutex.Unlock()
p.health = health
if health && p.started {
p.timer.Reset(p.resetDuration)
}
}