/
file.go
95 lines (80 loc) · 1.55 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
package inputs
import (
"errors"
"fmt"
"time"
"github.com/hpcloud/tail"
"github.com/lfkeitel/spartan/event"
"gopkg.in/tomb.v2"
)
func init() {
register("file", newFileInput)
}
type fileConfig struct {
path string
}
// A FileInput will read a file and optionally tail it. Each line is considered
// a separate event.
type FileInput struct {
config *fileConfig
t tomb.Tomb
out chan<- *event.Event
}
func newFileInput(options map[string]interface{}) (Input, error) {
i := &FileInput{
config: &fileConfig{},
}
return i, i.setConfig(options)
}
func (i *FileInput) setConfig(options map[string]interface{}) error {
if s, exists := options["path"]; exists {
i.config.path = s.(string)
} else {
return errors.New("Path option required")
}
return nil
}
// Start the FileInput reading/tailing.
func (i *FileInput) Start(out chan<- *event.Event) error {
i.out = out
i.t.Go(i.run)
return nil
}
// Close the FileInput
func (i *FileInput) Close() error {
i.t.Kill(nil)
return i.t.Wait()
}
func (i *FileInput) run() error {
for {
select {
case <-i.t.Dying():
return nil
default:
}
t, err := tail.TailFile(i.config.path, tail.Config{
Follow: true,
ReOpen: true,
})
if err != nil {
fmt.Println(err.Error())
time.Sleep(500 * time.Millisecond)
continue
}
var line *tail.Line
for {
select {
case line = <-t.Lines:
if line.Err != nil {
fmt.Println(line.Err.Error())
continue
}
i.out <- event.New(line.Text)
case <-i.t.Dying():
t.Stop()
t.Cleanup()
return nil
}
}
}
}