2023-03-03 19:31:57 +01:00
|
|
|
package metrics
|
|
|
|
|
|
|
|
import (
|
2023-03-13 19:19:38 +01:00
|
|
|
"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 {
|
|
|
|
events chan ZitiEventJson
|
|
|
|
src ZitiEventJsonSource
|
|
|
|
srcJoin chan struct{}
|
|
|
|
cache *cache
|
2023-03-16 20:05:39 +01:00
|
|
|
snks []UsageSink
|
2023-03-06 19:56:54 +01:00
|
|
|
}
|
|
|
|
|
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)
|
2023-03-16 20:05:39 +01:00
|
|
|
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
|
|
|
|
2023-03-16 20:05: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 {
|
|
|
|
a.events = make(chan ZitiEventJson)
|
|
|
|
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
|
|
|
|
2023-03-03 20:22:22 +01:00
|
|
|
go func() {
|
2023-03-15 21:14:06 +01:00
|
|
|
logrus.Info("started")
|
|
|
|
defer logrus.Info("stopped")
|
2023-03-03 20:22:22 +01:00
|
|
|
for {
|
|
|
|
select {
|
2023-03-15 21:14:06 +01:00
|
|
|
case event := <-a.events:
|
|
|
|
if usage, err := Ingest(event); err == nil {
|
|
|
|
if err := a.cache.addZrokDetail(usage); err != nil {
|
|
|
|
logrus.Error(err)
|
|
|
|
}
|
2023-03-16 20:05:39 +01:00
|
|
|
for _, snk := range a.snks {
|
|
|
|
if err := snk.Handle(usage); err != nil {
|
|
|
|
logrus.Error(err)
|
|
|
|
}
|
2023-03-07 22:29:39 +01:00
|
|
|
}
|
2023-03-07 21:27:39 +01:00
|
|
|
} else {
|
|
|
|
logrus.Error(err)
|
|
|
|
}
|
2023-03-03 20:22:22 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2023-03-15 21:14:06 +01:00
|
|
|
return nil
|
2023-03-06 19:56:54 +01:00
|
|
|
}
|
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
|
|
|
}
|