2024-03-02 23:55:28 +01:00
|
|
|
package kubeprobes
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2024-03-03 23:24:42 +01:00
|
|
|
// Probe is a wrapper for a function that determines whether
|
2024-03-02 23:55:28 +01:00
|
|
|
// the given metric may be marked as correctly functioning.
|
|
|
|
// It not, the error should be returned.
|
2024-03-03 23:24:42 +01:00
|
|
|
type Probe interface {
|
2024-03-02 23:55:28 +01:00
|
|
|
name() string
|
|
|
|
status() error
|
|
|
|
}
|
|
|
|
|
2024-03-03 23:24:42 +01:00
|
|
|
type probe struct {
|
2024-03-02 23:55:28 +01:00
|
|
|
probeName string
|
|
|
|
probeFunc func() error
|
|
|
|
refreshInterval time.Duration
|
|
|
|
|
|
|
|
mux sync.RWMutex
|
|
|
|
err error
|
|
|
|
}
|
|
|
|
|
2024-03-03 23:24:42 +01:00
|
|
|
// NewProbe returns new instance of [Probe].
|
2024-03-02 23:55:28 +01:00
|
|
|
//
|
|
|
|
// If update interval is less or equal zero then probe is updated only
|
|
|
|
// on its creation and remains in the same state forever.
|
2024-03-03 23:24:42 +01:00
|
|
|
func NewProbe(
|
2024-03-02 23:55:28 +01:00
|
|
|
name string,
|
|
|
|
fn func() error,
|
|
|
|
updateInterval time.Duration,
|
2024-03-03 23:24:42 +01:00
|
|
|
) (Probe, error) {
|
2024-03-02 23:55:28 +01:00
|
|
|
if name == "" {
|
|
|
|
return nil, errProbeNameEmpty
|
|
|
|
}
|
|
|
|
|
2024-03-03 23:24:42 +01:00
|
|
|
pf := &probe{
|
2024-03-02 23:55:28 +01:00
|
|
|
probeName: name,
|
|
|
|
probeFunc: fn,
|
|
|
|
refreshInterval: updateInterval,
|
|
|
|
mux: sync.RWMutex{},
|
|
|
|
}
|
|
|
|
|
|
|
|
defer pf.autoUpdate()
|
|
|
|
return pf, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// name implements ProbeFunction.
|
2024-03-03 23:24:42 +01:00
|
|
|
func (pf *probe) name() string {
|
2024-03-02 23:55:28 +01:00
|
|
|
return pf.probeName
|
|
|
|
}
|
|
|
|
|
|
|
|
// status implements ProbeFunction.
|
2024-03-03 23:24:42 +01:00
|
|
|
func (pf *probe) status() error {
|
2024-03-02 23:55:28 +01:00
|
|
|
pf.mux.RLock()
|
|
|
|
defer pf.mux.RUnlock()
|
|
|
|
return pf.err
|
|
|
|
}
|
|
|
|
|
2024-03-03 23:24:42 +01:00
|
|
|
func (pf *probe) update() {
|
2024-03-02 23:55:28 +01:00
|
|
|
err := pf.probeFunc()
|
|
|
|
pf.mux.Lock()
|
|
|
|
pf.err = err
|
|
|
|
pf.mux.Unlock()
|
|
|
|
}
|
|
|
|
|
2024-03-03 23:24:42 +01:00
|
|
|
func (pf *probe) autoUpdate() {
|
2024-03-02 23:55:28 +01:00
|
|
|
pf.update()
|
|
|
|
if pf.refreshInterval <= 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
ticker := time.NewTicker(pf.refreshInterval)
|
|
|
|
for {
|
|
|
|
<-ticker.C
|
|
|
|
pf.update()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|