-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.go
102 lines (92 loc) · 2.15 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
97
98
99
100
101
102
package file
import (
"os"
"github.com/go-logr/logr"
"github.com/nxadm/tail"
"gopkg.in/tomb.v1" // need tomb.ErrStillAlive
"github.com/LeKovr/mqbridge/types"
)
// EndPoint holds endpoint
type EndPoint struct {
types.EndPointAttr
}
// New creates endpoint
func New(epa types.EndPointAttr, dsn string) (types.EndPoint, error) {
epa.Log.Info("Endpoint", "dsn", dsn)
return &EndPoint{epa}, nil
}
// Listen starts all listening goroutines
func (ep EndPoint) Listen(id int, channel string, pipe chan string) error {
log := ep.Log.WithValues("is_in", true, "channel", channel, "id", id)
config := tail.Config{
Follow: true,
ReOpen: true,
MustExist: true,
}
tf, err := tail.TailFile(channel, config)
if err != nil {
return err
}
log.Info("Endpoint connected")
go ep.reader(log, tf, pipe)
return nil
}
// Notify starts all notify goroutines
func (ep EndPoint) Notify(id int, channel string, pipe chan string) error {
log := ep.Log.WithValues("is_in", false, "channel", channel, "id", id)
if channel == "-" {
// send to STDOUT
log.Info("Endpoint for stdout")
go ep.Printer(log, pipe)
} else {
f, err := os.Create(channel)
if err != nil {
return err
}
log.Info("Endpoint for file")
go ep.writer(log, f, pipe)
}
return nil
}
func (ep EndPoint) reader(log logr.Logger, tf *tail.Tail, pipe chan string) {
ep.WG.Add(1)
defer ep.WG.Done()
for {
select {
case line := <-tf.Lines:
if tf.Err().Error() != tomb.ErrStillAlive.Error() {
_ = tf.Stop()
log.Error(tf.Err(), "Reader")
ep.Abort <- tf.Err().Error()
return
}
log.V(1).Info("BRIN ", "line", line.Text)
pipe <- line.Text
case <-ep.Ctx.Done():
log.V(1).Info("Endpoint close")
_ = tf.Stop() // Cleanup()
return
}
}
}
func (ep EndPoint) writer(log logr.Logger, f *os.File, pipe chan string) {
ep.WG.Add(1)
defer ep.WG.Done()
for {
select {
case line := <-pipe:
_, err := f.WriteString(line + "\n")
if err != nil {
log.Error(err, "Writer")
f.Close()
ep.Abort <- "channel" // br.ID
return
}
log.V(1).Info("BROUT", "line", line)
case <-ep.Ctx.Done():
log.V(1).Info("Endpoint close")
f.Close()
return
}
}
}