kubeprobes/probe.go

82 lines
1.4 KiB
Go
Raw Normal View History

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