-
Notifications
You must be signed in to change notification settings - Fork 0
/
fifo.go
106 lines (93 loc) · 2.56 KB
/
fifo.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
103
104
105
106
package main
import (
"bufio"
"context"
"fmt"
"io"
"github.com/fsnotify/fsnotify"
"github.com/sirupsen/logrus"
)
type FifoHandler struct {
pipe io.Reader
events <-chan fsnotify.Event
running map[string]context.CancelFunc
handleNotification notificationHandlerFunc
}
type notificationHandlerFunc func(ctx context.Context, notification Notification)
func NewFifoHandler(cfg notifyConfig, pipe io.Reader, events <-chan fsnotify.Event) (*FifoHandler, error) {
p, err := cfg.NewProvider()
if err != nil {
return nil, err
}
fh := &FifoHandler{
pipe: pipe,
events: events,
running: map[string]context.CancelFunc{},
handleNotification: defaultNotificatonHandler(p, cfg),
}
return fh, nil
}
func (h FifoHandler) HandleFifo(ctx context.Context) error {
err := h.handleFifoEvents(ctx)
if err != nil {
logrus.Errorf("Failed to read from named pipe: %s", err)
}
for {
select {
case e := <-h.events:
logrus.Debugf("got event: %q", e.Op.String())
switch e.Op {
case fsnotify.Write:
err := h.handleFifoEvents(ctx)
if err != nil {
logrus.Errorf("Failed to read from named pipe: %s", err)
}
case fsnotify.Remove, fsnotify.Rename:
return fmt.Errorf("Named pipe was removed. Quitting")
}
case <-ctx.Done():
return nil
}
}
}
func (h FifoHandler) handleFifoEvents(ctx context.Context) error {
s := bufio.NewScanner(h.pipe)
for s.Scan() {
line := s.Text()
logrus.Debugf("Got line: %q", s.Text())
n, err := parseNotificationLine(line)
if err != nil {
logrus.Errorf("Failed to parse fifo event from keepalived, keepalived might be incompatible with the floaty version: %s", err)
continue
}
err = h.handleNotifyEvent(ctx, n)
if err != nil {
logrus.Errorf("Failed to handle notify event: %s", err)
continue
}
}
// Only returns non EOF errors
return s.Err()
}
func (h FifoHandler) handleNotifyEvent(ctx context.Context, n Notification) error {
stopRunning, ok := h.running[n.Instance]
if ok {
stopRunning()
}
delete(h.running, n.Instance)
runCtx, stop := context.WithCancel(ctx)
h.running[n.Instance] = stop
h.handleNotification(runCtx, n)
return nil
}
func defaultNotificatonHandler(provider elasticIPProvider, cfg notifyConfig) notificationHandlerFunc {
return func(ctx context.Context, notification Notification) {
go func() {
logrus.WithField("notification", notification).Infof("Handle Notification")
err := handleNotification(ctx, provider, cfg, notification)
if err != nil {
logrus.Errorf("Failed to handle notification: %s", err)
}
}()
}
}