zrok/controller/metrics/agent.go

81 lines
1.7 KiB
Go
Raw Normal View History

2023-03-03 19:31:57 +01:00
package metrics
import (
"github.com/openziti/zrok/controller/store"
2023-03-03 19:31:57 +01:00
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
2023-03-15 21:14:06 +01:00
type Agent struct {
2023-05-01 20:45:45 +02:00
events chan ZitiEventMsg
2023-03-15 21:14:06 +01:00
src ZitiEventJsonSource
srcJoin chan struct{}
cache *cache
snks []UsageSink
}
2023-03-15 21:14:06 +01:00
func NewAgent(cfg *AgentConfig, str *store.Store, ifxCfg *InfluxConfig) (*Agent, error) {
a := &Agent{}
if v, ok := cfg.Source.(ZitiEventJsonSource); ok {
a.src = v
} else {
return nil, errors.New("invalid event json source")
2023-03-07 22:29:39 +01:00
}
2023-03-15 21:14:06 +01:00
a.cache = newShareCache(str)
a.snks = append(a.snks, newInfluxWriter(ifxCfg))
2023-03-15 21:14:06 +01:00
return a, nil
}
2023-03-07 22:29:39 +01:00
func (a *Agent) AddUsageSink(snk UsageSink) {
a.snks = append(a.snks, snk)
}
2023-03-15 21:14:06 +01:00
func (a *Agent) Start() error {
2023-05-01 20:45:45 +02:00
a.events = make(chan ZitiEventMsg)
2023-03-15 21:14:06 +01:00
srcJoin, err := a.src.Start(a.events)
2023-03-03 19:31:57 +01:00
if err != nil {
2023-03-15 21:14:06 +01:00
return err
2023-03-03 19:31:57 +01:00
}
2023-03-15 21:14:06 +01:00
a.srcJoin = srcJoin
2023-03-03 19:31:57 +01:00
go func() {
2023-03-15 21:14:06 +01:00
logrus.Info("started")
defer logrus.Info("stopped")
for {
select {
2023-03-15 21:14:06 +01:00
case event := <-a.events:
2023-05-01 20:45:45 +02:00
if usage, err := Ingest(event.Data()); err == nil {
if usage.ZitiServiceId != "" {
2023-06-16 19:28:00 +02:00
if err := a.cache.addZrokDetail(usage); err != nil {
logrus.Errorf("unable to add zrok detail for: %v: %v", usage.String(), err)
}
2023-03-15 21:14:06 +01:00
}
2023-05-01 20:45:45 +02:00
shouldAck := true
for _, snk := range a.snks {
if err := snk.Handle(usage); err != nil {
2023-06-16 19:18:46 +02:00
logrus.Errorf("error handling usage: %v", err)
2023-05-01 20:45:45 +02:00
if shouldAck {
shouldAck = false
}
}
2023-03-07 22:29:39 +01:00
}
2023-05-01 20:45:45 +02:00
if shouldAck {
2023-05-22 22:23:55 +02:00
if err := event.Ack(); err != nil {
2023-06-16 19:18:46 +02:00
logrus.Errorf("unable to ack handled message: %v", err)
2023-05-22 22:23:55 +02:00
}
2023-05-01 20:45:45 +02:00
}
} else {
2023-06-16 19:18:46 +02:00
logrus.Errorf("unable to ingest '%v': %v", event.Data(), err)
}
}
}
}()
2023-03-15 21:14:06 +01:00
return nil
}
2023-03-03 19:31:57 +01:00
2023-03-15 21:14:06 +01:00
func (a *Agent) Stop() {
a.src.Stop()
close(a.events)
2023-03-03 19:31:57 +01:00
}