zrok/controller/metrics/fileSource.go

78 lines
1.6 KiB
Go
Raw Normal View History

2023-03-03 19:31:57 +01:00
package metrics
2023-03-03 19:51:10 +01:00
import (
"encoding/json"
2023-03-03 19:51:10 +01:00
"github.com/michaelquigley/cf"
"github.com/nxadm/tail"
2023-03-03 19:51:10 +01:00
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
2023-03-03 19:51:10 +01:00
"os"
)
2023-03-03 19:31:57 +01:00
type FileSourceConfig struct {
Path string
}
func loadFileSourceConfig(v interface{}, opts *cf.Options) (interface{}, error) {
2023-03-03 19:51:10 +01:00
if submap, ok := v.(map[string]interface{}); ok {
cfg := &FileSourceConfig{}
if err := cf.Bind(cfg, submap, cf.DefaultOptions()); err != nil {
return nil, err
}
return &fileSource{cfg: cfg}, nil
2023-03-03 19:51:10 +01:00
}
return nil, errors.New("invalid config structure for 'file' source")
2023-03-03 19:31:57 +01:00
}
2023-03-03 19:51:10 +01:00
type fileSource struct {
cfg *FileSourceConfig
t *tail.Tail
2023-03-03 19:51:10 +01:00
}
2023-03-03 19:31:57 +01:00
func (s *fileSource) Start(events chan map[string]interface{}) (chan struct{}, error) {
2023-03-03 19:51:10 +01:00
f, err := os.Open(s.cfg.Path)
if err != nil {
return nil, errors.Wrapf(err, "error opening '%v'", s.cfg.Path)
}
_ = f.Close()
2023-03-03 19:51:10 +01:00
ch := make(chan struct{})
go func() {
s.tail(events)
2023-03-03 19:51:10 +01:00
close(ch)
}()
2023-03-03 19:51:10 +01:00
return ch, nil
}
func (s *fileSource) Stop() {
if err := s.t.Stop(); err != nil {
logrus.Error(err)
}
2023-03-03 19:31:57 +01:00
}
func (s *fileSource) tail(events chan map[string]interface{}) {
logrus.Infof("started")
defer logrus.Infof("stopped")
var err error
s.t, err = tail.TailFile(s.cfg.Path, tail.Config{
ReOpen: true,
Follow: true,
})
if err != nil {
logrus.Error(err)
return
}
for line := range s.t.Lines {
event := make(map[string]interface{})
if err := json.Unmarshal([]byte(line.Text), &event); err == nil {
logrus.Infof("seekinfo: offset: %d", line.SeekInfo.Offset)
events <- event
} else {
logrus.Errorf("error parsing line #%d: %v", line.Num, err)
}
}
}