-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher-tcp.go
208 lines (162 loc) · 4.4 KB
/
watcher-tcp.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package main
import (
"bufio"
"context"
"flag"
"fmt"
"log"
"os/exec"
"strings"
"time"
)
var (
port string
timeout int64
eventsEnabled bool
eventsTopic string
eventActive string
eventInactive string
eventEmitTimeout int64
)
func init() {
flag.StringVar(&port, "port", "443", "The TCP port to watch")
flag.Int64Var(&timeout, "timeout", 300, "The timeout when watching")
flag.BoolVar(&eventsEnabled, "events", true, "Should events be emitted or not")
flag.StringVar(&eventsTopic, "events-topic", "", "ARN of the SNS Topic")
flag.StringVar(&eventActive, "event-type-active", "active", "The event type to emit when 'active'")
flag.StringVar(&eventInactive, "event-type-inactive", "inactive", "The event type to emit when 'inactive'")
flag.Int64Var(&eventEmitTimeout, "event-emit-timeout", 10, "Timeout in seconds when emitting an event")
}
func monitorUnconn() (<-chan interface{}, error) {
notify := make(chan interface{})
// ss needs a fake tty so wrap it in script
cmd := exec.Command("script", "--quiet", "--flush", "--return", "--command",
fmt.Sprintf("ss --no-header --numeric --oneline --events sport = %s", port))
// Redirect stderr to stdout
cmd.Stderr = cmd.Stdout
outReader, err := cmd.StdoutPipe()
if err != nil {
return nil, fmt.Errorf("monitorUnconn: StdoutPipe(): %w", err)
}
// Start the command
err = cmd.Start()
if err != nil {
return nil, fmt.Errorf("monitorUnconn: Start(): %w", err)
}
// Build the scanner
scanner := bufio.NewScanner(outReader)
scanner.Split(bufio.ScanLines)
// Go and watch the output
go func() {
for scanner.Scan() {
log.Printf("DEBUG monitorUnconn: text: %s\n", scanner.Text())
notify <- struct{}{}
}
err = cmd.Wait()
if err != nil {
log.Fatalf("FATAL monitorUnconn: Wait(): %s\n", err)
}
log.Println("WARN monitorUnconn: done")
}()
return notify, nil
}
func countEstab() (int, error) {
// ss needs a fake tty so wrap it in script
cmd := exec.Command("script", "--quiet", "--flush", "--return", "--command",
fmt.Sprintf("ss --no-header --numeric --oneline sport = %s", port))
// Run the command
output, err := cmd.CombinedOutput()
if err != nil {
return -1, fmt.Errorf("countEstab: CombinedOutput(): %w", err)
}
count := strings.Count(string(output), "\n")
if count > 0 {
for _, l := range strings.Split(string(output), "\n") {
log.Printf("DEBUG countEstab: text: %s\n", l)
}
}
return count, nil
}
func emitEvent(eventType string) {
if !eventsEnabled {
return
}
ctx, cancel := context.WithTimeout(context.TODO(),
time.Duration(eventEmitTimeout)*time.Second)
defer cancel()
command := exec.CommandContext(ctx, "./event-emitter",
"--type", eventType, "--topic", eventsTopic)
command.Stderr = command.Stdout
stdout, err := command.StdoutPipe()
if err != nil {
log.Printf("ERROR emitEvent: StdoutPipe(): %s\n", err)
return
}
err = command.Start()
if err != nil {
log.Printf("ERROR emitEvent: Start(): %s\n", err)
return
}
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
// Propagate the 'event-emitter' output without decoration
fmt.Println(scanner.Text())
}
err = command.Wait()
if err != nil {
log.Printf("ERROR emitEvent: Wait(): %s\n", err)
return
}
}
func monitor() {
// Start monitoring disconnects
unconn, err := monitorUnconn()
if err != nil {
log.Fatalf("ERROR main: monitorUnconn(): %s\n", err)
}
// Start the main loop
active := false
waiting := true
log.Println("INFO main: watching")
for waiting {
timer := time.NewTimer(time.Duration(timeout) * time.Second)
select {
case <-timer.C:
log.Printf("INFO main: timeout, active=%t\n", active)
count, err := countEstab()
if err != nil {
log.Fatalf("ERROR main: countEstab(): %s\n", err)
}
log.Printf("INFO main: established connections=%d\n", count)
if count < 1 {
if active {
emitEvent("inactive")
} else {
waiting = false
}
active = false
}
case <-unconn:
log.Printf("INFO main: unconn, active=%t\n", active)
if !active {
emitEvent("active")
}
active = true
}
log.Printf("INFO main: active=%t, waiting=%t\n", active, waiting)
// Stop the timer
timer.Stop()
// Make sure the channel was read from, so it can be gc'd
select {
case <-timer.C:
default:
}
}
log.Println("WARN main: done watching")
}
func main() {
log.SetPrefix("[watcher-tcp] ")
log.SetFlags(0)
flag.Parse()
monitor()
}