diff --git a/endpoints/frontend/metrics.go b/endpoints/frontend/metrics.go index fae88b9a..4b8862cc 100644 --- a/endpoints/frontend/metrics.go +++ b/endpoints/frontend/metrics.go @@ -2,6 +2,7 @@ package frontend import ( "encoding/json" + "github.com/openziti-test-kitchen/zrok/model" "github.com/openziti-test-kitchen/zrok/zrokdir" "github.com/openziti/sdk-golang/ziti" "github.com/openziti/sdk-golang/ziti/config" @@ -11,17 +12,11 @@ import ( ) type metricsAgent struct { - metrics map[string]sessionMetrics + metrics *model.Metrics updates chan metricsUpdate zCtx ziti.Context } -type sessionMetrics struct { - BytesRead int64 - BytesWritten int64 - LastUpdate time.Time -} - type metricsUpdate struct { id string bytesRead int64 @@ -39,7 +34,7 @@ func newMetricsAgent(identityName string) (*metricsAgent, error) { } logrus.Infof("loaded '%v' identity", identityName) return &metricsAgent{ - metrics: make(map[string]sessionMetrics), + metrics: &model.Metrics{}, updates: make(chan metricsUpdate, 10240), zCtx: ziti.NewContextWithConfig(zCfg), }, nil @@ -49,19 +44,11 @@ func (ma *metricsAgent) run() { for { select { case update := <-ma.updates: - if sm, found := ma.metrics[update.id]; found { - sm.BytesRead += update.bytesRead - sm.BytesWritten += update.bytesWritten - sm.LastUpdate = time.Now() - ma.metrics[update.id] = sm - } else { - sm := sessionMetrics{ - BytesRead: update.bytesRead, - BytesWritten: update.bytesWritten, - LastUpdate: time.Now(), - } - ma.metrics[update.id] = sm - } + ma.metrics.PushSession(update.id, model.SessionMetrics{ + BytesRead: update.bytesRead, + BytesWritten: update.bytesWritten, + LastUpdate: time.Now().UnixMilli(), + }) case <-time.After(5 * time.Second): if metricsJson, err := json.MarshalIndent(ma.metrics, "", " "); err == nil { diff --git a/model/metrics.go b/model/metrics.go new file mode 100644 index 00000000..48716326 --- /dev/null +++ b/model/metrics.go @@ -0,0 +1,29 @@ +package model + +import "time" + +type Metrics struct { + LastUpdate int64 `json:"last_update"` + Sessions map[string]SessionMetrics +} + +func (m *Metrics) PushSession(svcName string, sm SessionMetrics) { + if m.Sessions == nil { + m.Sessions = make(map[string]SessionMetrics) + } + if prev, found := m.Sessions[svcName]; found { + prev.BytesRead += sm.BytesRead + prev.BytesWritten += sm.BytesWritten + prev.LastUpdate = sm.LastUpdate + m.Sessions[svcName] = prev + } else { + m.Sessions[svcName] = sm + } + m.LastUpdate = time.Now().UnixMilli() +} + +type SessionMetrics struct { + BytesRead int64 + BytesWritten int64 + LastUpdate int64 +}