Re-add the ticker periodically updating stats

This commit is contained in:
Torjus Håkestad 2021-11-03 21:45:40 +01:00
parent b2edb2b4bf
commit a19fb3086b
3 changed files with 27 additions and 4 deletions

View File

@ -96,7 +96,7 @@ func ActionServe(c *cli.Context) error {
defer serversCancel()
// Setup metrics collection
s = store.NewMetricsCollectingStore(s)
s = store.NewMetricsCollectingStore(rootCtx, s)
// Setup honeypot
hs, err := ssh.NewHoneypotServer(cfg.Honeypot, s)

View File

@ -1,20 +1,28 @@
package store
import (
"context"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.uio.no/torjus/apiary/models"
)
const tickDuration = 5 * time.Second
type MetricsCollectingStore struct {
store LoginAttemptStore
store LoginAttemptStore
attemptsCounter *prometheus.CounterVec
uniqueUsernamesCount prometheus.Gauge
uniquePasswordsCount prometheus.Gauge
uniqueIPsCount prometheus.Gauge
totalAttemptsCount prometheus.Gauge
statsTicker *time.Ticker
}
func NewMetricsCollectingStore(store LoginAttemptStore) *MetricsCollectingStore {
func NewMetricsCollectingStore(ctx context.Context, store LoginAttemptStore) *MetricsCollectingStore {
mcs := &MetricsCollectingStore{store: store}
mcs.attemptsCounter = prometheus.NewCounterVec(
@ -59,6 +67,19 @@ func NewMetricsCollectingStore(store LoginAttemptStore) *MetricsCollectingStore
prometheus.MustRegister(mcs.uniqueIPsCount)
prometheus.MustRegister(mcs.totalAttemptsCount)
mcs.statsTicker = time.NewTicker(tickDuration)
go func() {
defer mcs.statsTicker.Stop()
for {
select {
case <-ctx.Done():
return
case <-mcs.statsTicker.C:
mcs.Stats(LoginStatsTotals, 0)
}
}
}()
return mcs
}
@ -75,6 +96,8 @@ func (s *MetricsCollectingStore) All() ([]models.LoginAttempt, error) {
func (s *MetricsCollectingStore) Stats(statType LoginStats, limit int) ([]StatsResult, error) {
stats, err := s.store.Stats(statType, limit)
if statType == LoginStatsTotals {
// Reset ticker to avoid updating twice within the duration
s.statsTicker.Reset(tickDuration)
for _, element := range stats {
switch element.Name {
case "UniquePasswords":

View File

@ -5,7 +5,7 @@ import (
"runtime"
)
var Version = "v0.1.19"
var Version = "v0.1.20"
var Build string
func FullVersion() string {