2024-10-23 08:55:19 -04:00
|
|
|
package alerting
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-10-31 00:10:53 -04:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2024-10-23 08:55:19 -04:00
|
|
|
"sort"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
2024-11-07 23:17:16 -05:00
|
|
|
"dynatron.me/x/stillbox/pkg/alerting/alert"
|
2024-11-03 08:09:49 -05:00
|
|
|
"dynatron.me/x/stillbox/pkg/calls"
|
2024-11-03 07:19:03 -05:00
|
|
|
"dynatron.me/x/stillbox/pkg/config"
|
|
|
|
"dynatron.me/x/stillbox/pkg/database"
|
|
|
|
"dynatron.me/x/stillbox/pkg/notify"
|
|
|
|
"dynatron.me/x/stillbox/pkg/sinks"
|
2024-11-03 08:09:49 -05:00
|
|
|
talkgroups "dynatron.me/x/stillbox/pkg/talkgroups"
|
2024-10-23 08:55:19 -04:00
|
|
|
|
|
|
|
"dynatron.me/x/stillbox/internal/timeseries"
|
|
|
|
"dynatron.me/x/stillbox/internal/trending"
|
|
|
|
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
ScoreThreshold = -1
|
|
|
|
CountThreshold = 1.0
|
2024-10-31 00:10:53 -04:00
|
|
|
NotificationSubject = "Stillbox Alert"
|
|
|
|
DefaultRenotify = 30 * time.Minute
|
2024-10-25 15:34:59 -04:00
|
|
|
alerterTickInterval = time.Minute
|
2024-10-23 08:55:19 -04:00
|
|
|
)
|
|
|
|
|
2024-10-25 15:34:59 -04:00
|
|
|
type Alerter interface {
|
|
|
|
sinks.Sink
|
|
|
|
|
|
|
|
Enabled() bool
|
|
|
|
Go(context.Context)
|
|
|
|
|
|
|
|
stats
|
|
|
|
}
|
|
|
|
|
|
|
|
type alerter struct {
|
2024-10-23 08:55:19 -04:00
|
|
|
sync.RWMutex
|
2024-11-01 09:15:39 -04:00
|
|
|
clock timeseries.Clock
|
|
|
|
cfg config.Alerting
|
2024-11-03 08:09:49 -05:00
|
|
|
scorer trending.Scorer[talkgroups.ID]
|
|
|
|
scores trending.Scores[talkgroups.ID]
|
2024-11-01 09:15:39 -04:00
|
|
|
lastScore time.Time
|
|
|
|
sim *Simulation
|
2024-11-07 23:17:16 -05:00
|
|
|
alertCache map[talkgroups.ID]alert.Alert
|
2024-11-01 09:15:39 -04:00
|
|
|
renotify time.Duration
|
|
|
|
notifier notify.Notifier
|
2024-11-03 08:09:49 -05:00
|
|
|
tgCache talkgroups.Store
|
2024-10-23 08:55:19 -04:00
|
|
|
}
|
|
|
|
|
2024-10-25 15:34:59 -04:00
|
|
|
type offsetClock time.Duration
|
|
|
|
|
|
|
|
func (c *offsetClock) Now() time.Time {
|
|
|
|
return time.Now().Add(c.Duration())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *offsetClock) Duration() time.Duration {
|
|
|
|
return time.Duration(*c)
|
2024-10-23 08:55:19 -04:00
|
|
|
}
|
|
|
|
|
2024-10-30 09:49:45 -04:00
|
|
|
// OffsetClock returns a clock whose Now() method returns the specified offset from the current time.
|
2024-10-25 15:34:59 -04:00
|
|
|
func OffsetClock(d time.Duration) offsetClock {
|
|
|
|
return offsetClock(d)
|
2024-10-23 08:55:19 -04:00
|
|
|
}
|
|
|
|
|
2024-10-25 15:34:59 -04:00
|
|
|
type AlertOption func(*alerter)
|
|
|
|
|
2024-10-30 09:49:45 -04:00
|
|
|
// WithClock makes the alerter use a simulated clock.
|
2024-10-25 15:34:59 -04:00
|
|
|
func WithClock(clock timeseries.Clock) AlertOption {
|
|
|
|
return func(as *alerter) {
|
|
|
|
as.clock = clock
|
2024-10-23 08:55:19 -04:00
|
|
|
}
|
2024-10-25 15:34:59 -04:00
|
|
|
}
|
|
|
|
|
2024-10-31 00:10:53 -04:00
|
|
|
// WithNotifier sets the notifier
|
|
|
|
func WithNotifier(n notify.Notifier) AlertOption {
|
|
|
|
return func(as *alerter) {
|
|
|
|
as.notifier = n
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-30 09:49:45 -04:00
|
|
|
// New creates a new Alerter using the provided configuration.
|
2024-11-03 08:09:49 -05:00
|
|
|
func New(cfg config.Alerting, tgCache talkgroups.Store, opts ...AlertOption) Alerter {
|
2024-10-25 15:34:59 -04:00
|
|
|
if !cfg.Enable {
|
|
|
|
return &noopAlerter{}
|
|
|
|
}
|
|
|
|
|
|
|
|
as := &alerter{
|
2024-11-01 09:15:39 -04:00
|
|
|
cfg: cfg,
|
2024-11-07 23:17:16 -05:00
|
|
|
alertCache: make(map[talkgroups.ID]alert.Alert),
|
2024-11-01 09:15:39 -04:00
|
|
|
clock: timeseries.DefaultClock,
|
|
|
|
renotify: DefaultRenotify,
|
2024-11-02 11:39:02 -04:00
|
|
|
tgCache: tgCache,
|
2024-10-31 00:10:53 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if cfg.Renotify != nil {
|
|
|
|
as.renotify = cfg.Renotify.Duration()
|
2024-10-25 15:34:59 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, opt := range opts {
|
|
|
|
opt(as)
|
|
|
|
}
|
|
|
|
|
2024-11-02 09:41:48 -04:00
|
|
|
as.scorer = trending.NewScorer(
|
2024-10-25 15:34:59 -04:00
|
|
|
trending.WithTimeSeries(as.newTimeSeries),
|
2024-11-03 08:09:49 -05:00
|
|
|
trending.WithStorageDuration[talkgroups.ID](time.Hour*24*time.Duration(cfg.LookbackDays)),
|
|
|
|
trending.WithRecentDuration[talkgroups.ID](time.Duration(cfg.Recent)),
|
|
|
|
trending.WithHalfLife[talkgroups.ID](time.Duration(cfg.HalfLife)),
|
|
|
|
trending.WithScoreThreshold[talkgroups.ID](ScoreThreshold),
|
|
|
|
trending.WithCountThreshold[talkgroups.ID](CountThreshold),
|
|
|
|
trending.WithClock[talkgroups.ID](as.clock),
|
2024-10-25 15:34:59 -04:00
|
|
|
)
|
2024-10-23 08:55:19 -04:00
|
|
|
|
|
|
|
return as
|
|
|
|
}
|
|
|
|
|
2024-10-30 09:49:45 -04:00
|
|
|
// Go is the alerting loop. It does not start a goroutine.
|
2024-10-25 15:34:59 -04:00
|
|
|
func (as *alerter) Go(ctx context.Context) {
|
2024-10-31 16:50:08 -04:00
|
|
|
err := as.startBackfill(ctx)
|
|
|
|
if err != nil {
|
|
|
|
log.Error().Err(err).Msg("backfill")
|
|
|
|
}
|
2024-10-23 08:55:19 -04:00
|
|
|
|
2024-11-04 11:48:31 -05:00
|
|
|
as.score(time.Now())
|
2024-10-25 15:34:59 -04:00
|
|
|
ticker := time.NewTicker(alerterTickInterval)
|
2024-10-23 08:55:19 -04:00
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case now := <-ticker.C:
|
2024-11-04 11:48:31 -05:00
|
|
|
as.score(now)
|
2024-10-31 00:10:53 -04:00
|
|
|
err := as.notify(ctx)
|
|
|
|
if err != nil {
|
|
|
|
log.Error().Err(err).Msg("notify")
|
|
|
|
}
|
|
|
|
as.cleanCache()
|
2024-10-23 08:55:19 -04:00
|
|
|
case <-ctx.Done():
|
|
|
|
ticker.Stop()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2024-11-07 23:17:16 -05:00
|
|
|
func (as *alerter) eval(ctx context.Context, now time.Time, testMode bool) ([]alert.Alert, error) {
|
2024-11-02 11:39:02 -04:00
|
|
|
err := as.tgCache.Hint(ctx, as.scoredTGs())
|
2024-11-02 09:41:48 -04:00
|
|
|
if err != nil {
|
2024-11-02 11:39:02 -04:00
|
|
|
return nil, fmt.Errorf("prime TG cache: %w", err)
|
2024-11-02 09:41:48 -04:00
|
|
|
}
|
|
|
|
|
2024-11-07 23:17:16 -05:00
|
|
|
as.Lock()
|
|
|
|
defer as.Unlock()
|
|
|
|
|
2024-11-02 09:41:48 -04:00
|
|
|
db := database.FromCtx(ctx)
|
|
|
|
|
2024-11-07 23:17:16 -05:00
|
|
|
var notifications []alert.Alert
|
2024-11-02 09:41:48 -04:00
|
|
|
for _, s := range as.scores {
|
2024-11-02 11:39:02 -04:00
|
|
|
origScore := s.Score
|
2024-11-03 09:45:51 -05:00
|
|
|
tgr, err := as.tgCache.TG(ctx, s.ID)
|
2024-11-06 14:20:15 -05:00
|
|
|
if err == nil && !tgr.Talkgroup.Alert {
|
|
|
|
continue
|
2024-11-02 09:41:48 -04:00
|
|
|
}
|
|
|
|
|
2024-11-02 11:39:02 -04:00
|
|
|
if s.Score > as.cfg.AlertThreshold || testMode {
|
2024-11-02 09:41:48 -04:00
|
|
|
if old, inCache := as.alertCache[s.ID]; !inCache || now.Sub(old.Timestamp) > as.renotify {
|
2024-11-04 11:48:31 -05:00
|
|
|
s.Score *= as.tgCache.Weight(ctx, s.ID, now)
|
2024-11-07 23:17:16 -05:00
|
|
|
a, err := alert.Make(ctx, as.tgCache, s, origScore)
|
2024-11-02 09:41:48 -04:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("makeAlert: %w", err)
|
|
|
|
}
|
|
|
|
|
2024-11-02 14:26:58 -04:00
|
|
|
if s.Score < as.cfg.AlertThreshold {
|
|
|
|
a.Suppressed = true
|
|
|
|
}
|
|
|
|
|
2024-11-02 09:41:48 -04:00
|
|
|
as.alertCache[s.ID] = a
|
|
|
|
|
2024-11-02 11:39:02 -04:00
|
|
|
if !testMode {
|
2024-11-02 09:41:48 -04:00
|
|
|
err = db.AddAlert(ctx, a.ToAddAlertParams())
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("addAlert: %w", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-02 14:26:58 -04:00
|
|
|
if !a.Suppressed {
|
|
|
|
notifications = append(notifications, a)
|
|
|
|
}
|
2024-11-02 09:41:48 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-02 11:39:02 -04:00
|
|
|
return notifications, nil
|
2024-11-02 09:41:48 -04:00
|
|
|
|
|
|
|
}
|
|
|
|
|
2024-10-31 00:10:53 -04:00
|
|
|
func (as *alerter) testNotifyHandler(w http.ResponseWriter, r *http.Request) {
|
2024-11-07 23:17:16 -05:00
|
|
|
alerts := make([]alert.Alert, 0, len(as.scores))
|
2024-10-31 00:10:53 -04:00
|
|
|
ctx := r.Context()
|
|
|
|
|
2024-11-02 11:39:02 -04:00
|
|
|
alerts, err := as.eval(ctx, time.Now(), true)
|
2024-10-31 16:14:38 -04:00
|
|
|
if err != nil {
|
2024-11-02 11:39:02 -04:00
|
|
|
log.Error().Err(err).Msg("test notification eval")
|
2024-10-31 16:14:38 -04:00
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-11-07 23:17:16 -05:00
|
|
|
err = as.notifier.Send(ctx, alerts)
|
2024-10-31 00:10:53 -04:00
|
|
|
if err != nil {
|
|
|
|
log.Error().Err(err).Msg("test notification send")
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-10-31 16:50:08 -04:00
|
|
|
_, _ = w.Write([]byte("Sent"))
|
2024-10-31 00:10:53 -04:00
|
|
|
}
|
|
|
|
|
2024-11-02 11:39:02 -04:00
|
|
|
// scoredTGs gets a list of TGs.
|
2024-11-03 08:09:49 -05:00
|
|
|
func (as *alerter) scoredTGs() []talkgroups.ID {
|
|
|
|
tgs := make([]talkgroups.ID, 0, len(as.scores))
|
2024-11-02 11:39:02 -04:00
|
|
|
for _, s := range as.scores {
|
|
|
|
tgs = append(tgs, s.ID)
|
|
|
|
}
|
|
|
|
|
|
|
|
return tgs
|
|
|
|
}
|
|
|
|
|
2024-11-15 10:37:58 -05:00
|
|
|
// packedScoredTGs gets a list of TGID tuples.
|
|
|
|
func (as *alerter) scoredTGsTuple() (tgs database.TGTuples) {
|
|
|
|
tgs = database.MakeTGTuples(len(as.scores))
|
2024-10-31 16:14:38 -04:00
|
|
|
for _, s := range as.scores {
|
2024-11-15 10:37:58 -05:00
|
|
|
tgs.Append(s.ID.System, s.ID.Talkgroup)
|
2024-10-31 16:14:38 -04:00
|
|
|
}
|
|
|
|
|
2024-11-02 11:39:02 -04:00
|
|
|
return tgs
|
2024-10-31 16:14:38 -04:00
|
|
|
}
|
|
|
|
|
2024-10-31 00:10:53 -04:00
|
|
|
// notify iterates the scores and sends out any necessary notifications
|
|
|
|
func (as *alerter) notify(ctx context.Context) error {
|
|
|
|
if as.notifier == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-11-02 11:39:02 -04:00
|
|
|
notifications, err := as.eval(ctx, time.Now(), false)
|
2024-10-31 16:14:38 -04:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-10-31 00:10:53 -04:00
|
|
|
if len(notifications) > 0 {
|
2024-11-07 23:17:16 -05:00
|
|
|
return as.notifier.Send(ctx, notifications)
|
2024-10-31 00:10:53 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// cleanCache clears the cache of aged-out entries
|
|
|
|
func (as *alerter) cleanCache() {
|
|
|
|
if as.notifier == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
now := time.Now()
|
|
|
|
|
|
|
|
as.Lock()
|
|
|
|
defer as.Unlock()
|
|
|
|
|
2024-11-01 09:15:39 -04:00
|
|
|
for k, a := range as.alertCache {
|
|
|
|
if now.Sub(a.Timestamp) > as.renotify {
|
|
|
|
delete(as.alertCache, k)
|
2024-10-31 00:10:53 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-03 08:09:49 -05:00
|
|
|
func (as *alerter) newTimeSeries(id talkgroups.ID) trending.TimeSeries {
|
2024-10-23 08:55:19 -04:00
|
|
|
ts, _ := timeseries.NewTimeSeries(timeseries.WithGranularities(
|
|
|
|
[]timeseries.Granularity{
|
|
|
|
{Granularity: time.Second, Count: 60},
|
|
|
|
{Granularity: time.Minute, Count: 10},
|
|
|
|
{Granularity: time.Hour, Count: 24},
|
2024-10-25 15:34:59 -04:00
|
|
|
{Granularity: time.Hour * 24, Count: int(as.cfg.LookbackDays)},
|
2024-10-23 08:55:19 -04:00
|
|
|
},
|
2024-10-25 15:34:59 -04:00
|
|
|
), timeseries.WithClock(as.clock))
|
2024-10-23 08:55:19 -04:00
|
|
|
return ts
|
|
|
|
}
|
|
|
|
|
2024-10-31 00:10:53 -04:00
|
|
|
func (as *alerter) startBackfill(ctx context.Context) error {
|
2024-10-23 08:55:19 -04:00
|
|
|
now := time.Now()
|
2024-10-25 15:34:59 -04:00
|
|
|
since := now.Add(-24 * time.Hour * time.Duration(as.cfg.LookbackDays))
|
2024-10-23 08:55:19 -04:00
|
|
|
log.Debug().Time("since", since).Msg("starting stats backfill")
|
2024-10-30 09:49:45 -04:00
|
|
|
count, err := as.backfill(ctx, since, now)
|
2024-10-23 08:55:19 -04:00
|
|
|
if err != nil {
|
2024-10-31 16:50:08 -04:00
|
|
|
return err
|
2024-10-23 08:55:19 -04:00
|
|
|
}
|
2024-11-04 11:48:31 -05:00
|
|
|
log.Debug().Int("callsCount", count).Str("in", time.Since(now).String()).Int("tgCount", as.scorer.Score().Len()).Msg("backfill finished")
|
2024-10-31 00:10:53 -04:00
|
|
|
|
|
|
|
return nil
|
2024-10-23 08:55:19 -04:00
|
|
|
}
|
|
|
|
|
2024-11-04 11:48:31 -05:00
|
|
|
func (as *alerter) score(now time.Time) {
|
2024-10-23 08:55:19 -04:00
|
|
|
as.Lock()
|
|
|
|
defer as.Unlock()
|
|
|
|
|
2024-11-04 11:48:31 -05:00
|
|
|
as.scores = as.scorer.Score()
|
2024-10-23 08:55:19 -04:00
|
|
|
as.lastScore = now
|
|
|
|
sort.Sort(as.scores)
|
|
|
|
}
|
|
|
|
|
2024-10-30 09:49:45 -04:00
|
|
|
func (as *alerter) backfill(ctx context.Context, since time.Time, until time.Time) (count int, err error) {
|
2024-10-23 08:55:19 -04:00
|
|
|
db := database.FromCtx(ctx)
|
2024-10-30 09:49:45 -04:00
|
|
|
const backfillStatsQuery = `SELECT system, talkgroup, call_date FROM calls WHERE call_date > $1 AND call_date < $2 ORDER BY call_date ASC`
|
2024-10-23 08:55:19 -04:00
|
|
|
|
2024-11-15 12:18:32 -05:00
|
|
|
rows, err := db.DB().Query(ctx, backfillStatsQuery, since, until)
|
2024-10-23 08:55:19 -04:00
|
|
|
if err != nil {
|
|
|
|
return count, err
|
|
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
as.Lock()
|
|
|
|
defer as.Unlock()
|
|
|
|
|
|
|
|
for rows.Next() {
|
2024-11-03 08:09:49 -05:00
|
|
|
var tg talkgroups.ID
|
2024-10-23 08:55:19 -04:00
|
|
|
var callDate time.Time
|
|
|
|
if err := rows.Scan(&tg.System, &tg.Talkgroup, &callDate); err != nil {
|
|
|
|
return count, err
|
|
|
|
}
|
|
|
|
as.scorer.AddEvent(tg, callDate)
|
2024-10-30 09:49:45 -04:00
|
|
|
if as.sim != nil { // step the simulator if it is active
|
2024-11-04 11:48:31 -05:00
|
|
|
as.sim.stepClock(callDate)
|
2024-10-30 09:49:45 -04:00
|
|
|
}
|
2024-10-23 08:55:19 -04:00
|
|
|
count++
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := rows.Err(); err != nil {
|
|
|
|
return count, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return count, nil
|
|
|
|
}
|
|
|
|
|
2024-10-25 15:34:59 -04:00
|
|
|
func (as *alerter) SinkType() string {
|
2024-10-23 08:55:19 -04:00
|
|
|
return "alerting"
|
|
|
|
}
|
|
|
|
|
2024-11-03 08:09:49 -05:00
|
|
|
func (as *alerter) Call(ctx context.Context, call *calls.Call) error {
|
2024-10-23 08:55:19 -04:00
|
|
|
as.Lock()
|
|
|
|
defer as.Unlock()
|
|
|
|
as.scorer.AddEvent(call.TalkgroupTuple(), call.DateTime)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2024-10-25 15:34:59 -04:00
|
|
|
|
|
|
|
func (*alerter) Enabled() bool { return true }
|
|
|
|
|
2024-10-30 09:49:45 -04:00
|
|
|
// noopAlerter is used when alerting is disabled.
|
|
|
|
type noopAlerter struct{}
|
|
|
|
|
2024-11-03 08:09:49 -05:00
|
|
|
func (*noopAlerter) SinkType() string { return "noopAlerter" }
|
|
|
|
func (*noopAlerter) Call(_ context.Context, _ *calls.Call) error { return nil }
|
|
|
|
func (*noopAlerter) Go(_ context.Context) {}
|
|
|
|
func (*noopAlerter) Enabled() bool { return false }
|