2022-05-19 13:47:27 +00:00
|
|
|
package apiclient
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
tomb "gopkg.in/tomb.v2"
|
2023-05-23 08:52:47 +00:00
|
|
|
|
2023-07-28 14:35:08 +00:00
|
|
|
"github.com/crowdsecurity/go-cs-lib/trace"
|
2022-05-19 13:47:27 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type HeartBeatService service
|
|
|
|
|
|
|
|
func (h *HeartBeatService) Ping(ctx context.Context) (bool, *Response, error) {
|
|
|
|
|
|
|
|
u := fmt.Sprintf("%s/heartbeat", h.client.URLPrefix)
|
|
|
|
|
2022-08-16 07:46:10 +00:00
|
|
|
req, err := h.client.NewRequest(http.MethodGet, u, nil)
|
2022-05-19 13:47:27 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
resp, err := h.client.Do(ctx, req, nil)
|
|
|
|
if err != nil {
|
|
|
|
return false, resp, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return true, resp, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *HeartBeatService) StartHeartBeat(ctx context.Context, t *tomb.Tomb) {
|
|
|
|
t.Go(func() error {
|
2023-05-23 08:52:47 +00:00
|
|
|
defer trace.CatchPanic("crowdsec/apiClient/heartbeat")
|
2022-05-19 13:47:27 +00:00
|
|
|
hbTimer := time.NewTicker(1 * time.Minute)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-hbTimer.C:
|
|
|
|
log.Debug("heartbeat: sending heartbeat")
|
|
|
|
ok, resp, err := h.Ping(ctx)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("heartbeat error : %s", err)
|
|
|
|
continue
|
|
|
|
}
|
2022-07-06 12:50:54 +00:00
|
|
|
resp.Response.Body.Close()
|
2022-05-19 13:47:27 +00:00
|
|
|
if resp.Response.StatusCode != http.StatusOK {
|
|
|
|
log.Errorf("heartbeat unexpected return code : %d", resp.Response.StatusCode)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if !ok {
|
|
|
|
log.Errorf("heartbeat returned false")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
case <-t.Dying():
|
|
|
|
log.Debugf("heartbeat: stopping")
|
|
|
|
hbTimer.Stop()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|