-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
96 lines (81 loc) · 1.63 KB
/
file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package file
import (
"os"
"time"
"github.com/mitchellh/mapstructure"
"gitlab.com/mek_x/data-collector/pkg/collector"
"gitlab.com/mek_x/data-collector/pkg/parser"
)
type source struct {
path string
parser parser.Parser
}
type fileSource struct {
sources []source
interval int
end chan bool
}
/* Main config structure. Descibes `params` field from configuration yaml. */
type FileParams struct {
Interval int
}
var _ collector.Collector = (*fileSource)(nil)
/* In this module init function we register our collector in global collector registry */
func init() {
collector.Registry.Add("file", New)
}
func New(p any) collector.Collector {
var opt FileParams
if err := mapstructure.Decode(p, &opt); err != nil {
return nil
}
// Set defaults
if opt.Interval == 0 {
opt.Interval = 60
}
return &fileSource{
sources: make([]source, 0),
interval: opt.Interval,
end: make(chan bool),
}
}
func (f *fileSource) readAndParse() {
for _, i := range f.sources {
buf, err := os.ReadFile(i.path)
if err != nil {
continue
}
i.parser.Parse(buf)
}
}
func (f *fileSource) Start() error {
go func() {
for len(f.sources) == 0 {
time.Sleep(10 * time.Millisecond)
}
f.readAndParse()
loop:
for {
select {
case <-f.end:
f.end <- false
close(f.end)
break loop
case <-time.After(time.Duration(f.interval) * time.Second):
f.readAndParse()
}
}
}()
return nil
}
func (f *fileSource) AddDataSource(path string, parser parser.Parser) error {
f.sources = append(f.sources, source{
path: path,
parser: parser,
})
return nil
}
func (f *fileSource) End() {
f.end <- true
<-f.end
}