zrok/endpoints/frontend/metrics.go

75 lines
1.8 KiB
Go
Raw Normal View History

package frontend
import (
2022-10-14 19:45:55 +02:00
"encoding/json"
"github.com/openziti-test-kitchen/zrok/zrokdir"
"github.com/openziti/sdk-golang/ziti"
"github.com/openziti/sdk-golang/ziti/config"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"time"
)
2022-10-10 22:56:01 +02:00
type metricsAgent struct {
metrics map[string]sessionMetrics
updates chan metricsUpdate
zCtx ziti.Context
}
2022-10-10 22:56:01 +02:00
type sessionMetrics struct {
2022-10-14 19:45:55 +02:00
BytesRead int64
BytesWritten int64
LastUpdate time.Time
}
2022-10-10 22:56:01 +02:00
type metricsUpdate struct {
id string
bytesRead int64
bytesWritten int64
}
func newMetricsAgent(identityName string) (*metricsAgent, error) {
zif, err := zrokdir.ZitiIdentityFile(identityName)
if err != nil {
return nil, errors.Wrapf(err, "error getting '%v' identity file", identityName)
}
zCfg, err := config.NewFromFile(zif)
if err != nil {
return nil, errors.Wrapf(err, "error loading '%v' identity", identityName)
}
logrus.Infof("loaded '%v' identity", identityName)
2022-10-10 22:56:01 +02:00
return &metricsAgent{
metrics: make(map[string]sessionMetrics),
updates: make(chan metricsUpdate, 10240),
zCtx: ziti.NewContextWithConfig(zCfg),
}, nil
}
2022-10-10 22:56:01 +02:00
func (ma *metricsAgent) run() {
for {
select {
case update := <-ma.updates:
if sm, found := ma.metrics[update.id]; found {
2022-10-14 19:45:55 +02:00
sm.BytesRead += update.bytesRead
sm.BytesWritten += update.bytesWritten
sm.LastUpdate = time.Now()
ma.metrics[update.id] = sm
} else {
sm := sessionMetrics{
2022-10-14 19:45:55 +02:00
BytesRead: update.bytesRead,
BytesWritten: update.bytesWritten,
LastUpdate: time.Now(),
}
ma.metrics[update.id] = sm
}
case <-time.After(5 * time.Second):
2022-10-14 19:45:55 +02:00
if metricsJson, err := json.MarshalIndent(ma.metrics, "", " "); err == nil {
logrus.Info(string(metricsJson))
} else {
logrus.Errorf("error marshaling metrics: %v", err)
}
2022-10-10 22:56:01 +02:00
}
}
}