You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/health/checker.go

107 lines
1.7 KiB

package health
import (
"context"
"sync"
"time"
)
type Checker interface {
Check(ctx context.Context) (interface{}, error)
}
2 years ago
type Notifier interface {
notify(string)
2 years ago
}
2 years ago
type CheckerHandler interface {
setNotifier(w Notifier)
run(ctx context.Context)
getStatus() CheckerStatus
getName() string
}
type checkerHandler struct {
Name string
intervalTime time.Duration
timeout time.Duration
Checker
CheckerStatus
2 years ago
*sync.RWMutex
2 years ago
Notifier
}
2 years ago
func NewChecker(name string, ch Checker, interval, timeout time.Duration) CheckerHandler {
return &checkerHandler{
2 years ago
Name: name,
intervalTime: interval,
timeout: timeout,
Checker: ch,
CheckerStatus: CheckerStatus{},
RWMutex: &sync.RWMutex{},
2 years ago
Notifier: nil,
2 years ago
}
}
2 years ago
func (c *checkerHandler) setNotifier(w Notifier) {
c.Notifier = w
}
func (c *checkerHandler) getName() string {
return c.Name
}
2 years ago
func (c *checkerHandler) check(ctx context.Context) bool {
defer func() {
recover()
}()
2 years ago
var cancel func()
if c.timeout > 0 {
ctx, cancel = context.WithTimeout(ctx, c.timeout)
defer cancel()
}
detail, err := c.Check(ctx)
status := StatusUp
if err != nil {
status = StatusDown
}
2 years ago
c.Lock()
defer c.Unlock()
old := c.CheckerStatus
c.CheckerStatus = CheckerStatus{
Status: status,
Detail: detail,
Err: err,
}
if c.CheckerStatus == old {
return false
}
return true
}
2 years ago
func (c *checkerHandler) run(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
}
if c.check(ctx) {
2 years ago
//notify
2 years ago
if c.Notifier != nil {
c.Notifier.notify(c.Name)
2 years ago
}
}
time.Sleep(c.intervalTime)
}
}
2 years ago
func (c *checkerHandler) getStatus() CheckerStatus {
c.RLock()
defer c.RUnlock()
return c.CheckerStatus
}