-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
294 lines (273 loc) · 8.91 KB
/
main.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
serverEnvKey = "EXT_SERVER_HOST"
portEnvKey = "EXT_SERVER_PORT"
egressIPsEnvKey = "EGRESS_IPS"
hostSubnetEnvKey = "HOST_SUBNET"
delayBetweenRequestEnvKey = "DELAY_BETWEEN_REQ_SEC"
reqTimeoutEnvKey = "REQ_TIMEOUT_SEC"
envKeyErrMsg = "define env key %q"
defaultDelayBetweenReqSec = 1
defaultRequestTimeoutSec = 1
)
func main() {
wg := &sync.WaitGroup{}
stop := registerSignalHandler()
extHost, extPort, egressIPsStr, hostSubnetStr, delayBetweenReq, timeout := processEnvVars()
egressIPs := make(map[string]struct{})
if egressIPsStr != "" {
egressIPs = buildEIPMap(egressIPsStr)
}
startupNonEIPTick, eipStartUpLatency, eipRecoveryLatency, eipTick, nonEIPTick, failure := buildAndRegisterMetrics(delayBetweenReq)
wg.Add(2)
startMetricsServer(stop, wg)
// begin requests until Egress IP found
wg.Add(1)
go checkEIPAndNonEIPUntilStop(stop, wg, egressIPs, hostSubnetStr, extHost, extPort, eipStartUpLatency, eipRecoveryLatency, startupNonEIPTick, eipTick, nonEIPTick, failure, delayBetweenReq, timeout)
wg.Wait()
}
// validate hostip or eip
func validateIPAddress(ipAddr string, egressIPs map[string]struct{}, subnet string) bool {
if len(egressIPs) > 0 {
if _, ok := egressIPs[ipAddr]; ok {
return true
}
} else {
ip := net.ParseIP(ipAddr)
if ip == nil {
log.Printf("Error: IP Address is nil")
return false
}
// Parse the subnet
_, ipNet, err := net.ParseCIDR(subnet)
if err != nil {
log.Printf("Error: Failed to parse subnet: %v", err)
return false
}
// Check if the IP address is within the subnet
return ipNet.Contains(ip)
}
return false
}
func checkEIPAndNonEIPUntilStop(stop <-chan struct{}, wg *sync.WaitGroup, egressIPs map[string]struct{}, hostSubnetStr string, extHost, extPort string,
eipStartUpLatency, eipRecoveryLatency *prometheus.Gauge, startupNonEIPTick, eipTick, nonEIPTick *prometheus.Gauge, failure *prometheus.Gauge, delayBetweenReq, timeout int) {
log.Print("## checkEIPAndNonEIPUntilStop: Polling source IP and increment metric counts for when Egress IP or another IP seen as source IP")
defer wg.Done()
var done bool
start := time.Now()
var eipCheckFailed bool
var startupLatencySet bool
var valid bool
client := getHTTPClient(timeout)
for !done {
select {
case <-stop:
done = true
default:
// Create a new request
url := buildDstURL(extHost, extPort)
res, err := client.Get(url)
if err != nil {
log.Printf("Error: Failed to talk to %q: %v", url, err)
} else {
if res.StatusCode == http.StatusOK {
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Printf("Error: %v , while calling ioutil.ReadAll", err)
} else {
valid = validateIPAddress(string(resBody), egressIPs, hostSubnetStr)
}
} else {
log.Printf("res.StatusCode %d", res.StatusCode)
err = errors.New(fmt.Sprintf("res.StatusCode %d", res.StatusCode))
}
res.Body.Close()
}
if err != nil {
if eipCheckFailed == false {
eipCheckFailed = true
start = time.Now()
}
(*failure).Inc()
} else {
if valid {
if startupLatencySet == false {
(*eipStartUpLatency).Set(time.Now().Sub(start).Seconds())
log.Printf("Startup Latency %v", time.Now().Sub(start).Seconds())
startupLatencySet = true
} else {
if eipCheckFailed == true {
eipCheckFailed = false
(*eipRecoveryLatency).Set(time.Now().Sub(start).Seconds())
log.Printf("Failover Latency %v", time.Now().Sub(start).Seconds())
start = time.Now()
}
}
} else {
if startupLatencySet == false {
(*startupNonEIPTick).Inc()
} else {
if eipCheckFailed == false {
eipCheckFailed = true
start = time.Now()
}
(*nonEIPTick).Inc()
}
}
}
if delayBetweenReq != 0 {
time.Sleep(time.Duration(delayBetweenReq) * time.Second)
}
}
}
log.Print("Finished polling source IP")
}
func isIP(s string) bool {
return net.ParseIP(s) != nil
}
func buildDstURL(host, port string) string {
return fmt.Sprintf("http://%s:%s", host, port)
}
func getHTTPClient(timeout int) http.Client {
return http.Client{
Timeout: time.Duration(timeout) * time.Second,
}
}
func buildEIPMap(egressIPsStr string) map[string]struct{} {
// build map of egress IPs
egressIPs := strings.Split(egressIPsStr, ",")
egressIPMap := make(map[string]struct{})
for _, egressIP := range egressIPs {
if ip := net.ParseIP(egressIP); ip == nil {
panic(fmt.Sprintf("invalid egress IPs - comma seperated list allowed: %q", egressIPsStr))
}
egressIPMap[egressIP] = struct{}{}
}
return egressIPMap
}
func processEnvVars() (string, string, string, string, int, int) {
var err error
extHost := os.Getenv(serverEnvKey)
if extHost == "" {
panic(fmt.Sprintf(envKeyErrMsg, serverEnvKey))
}
extPort := os.Getenv(portEnvKey)
if extPort == "" {
panic(fmt.Sprintf(envKeyErrMsg, portEnvKey))
}
hostSubnetStr := ""
egressIPsStr := os.Getenv(egressIPsEnvKey)
if egressIPsStr == "" {
hostSubnetStr = os.Getenv(hostSubnetEnvKey)
if hostSubnetStr == "" {
panic(fmt.Sprintf(envKeyErrMsg, egressIPsEnvKey))
}
}
delayBetweenReq := defaultDelayBetweenReqSec
delayBetweenRequestStr := os.Getenv(delayBetweenRequestEnvKey)
if delayBetweenRequestStr != "" {
delayBetweenReq, err = strconv.Atoi(delayBetweenRequestStr)
if err != nil {
panic(fmt.Sprintf("failed to parse delay between requests: %v", err))
}
}
requestTimeout := defaultRequestTimeoutSec
reqTimeoutStr := os.Getenv(reqTimeoutEnvKey)
if reqTimeoutStr != "" {
requestTimeout, err = strconv.Atoi(reqTimeoutStr)
if err != nil {
panic(fmt.Sprintf("failed to parse request timeout %q: %v", reqTimeoutStr, err))
}
}
return extHost, extPort, egressIPsStr, hostSubnetStr, delayBetweenReq, requestTimeout
}
func registerSignalHandler() chan struct{} {
stop := make(chan struct{})
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-c
close(stop)
}()
return stop
}
func startMetricsServer(stop <-chan struct{}, wg *sync.WaitGroup) {
// build metrics server
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
server := &http.Server{Addr: ":8080", Handler: mux}
// start metrics server
go func() {
defer wg.Done()
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
panic(err.Error())
}
}()
// stop server when done triggered
go func() {
defer wg.Done()
<-stop
if err := server.Close(); err != nil {
panic(err.Error())
}
}()
}
func buildAndRegisterMetrics(delayBetweenReq int) (*prometheus.Gauge, *prometheus.Gauge, *prometheus.Gauge, *prometheus.Gauge, *prometheus.Gauge, *prometheus.Gauge) {
var startupNonEIPTick = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "scale",
Name: "startup_non_eip_total",
Help: fmt.Sprintf("during startup, increments every time EgressIP not seen as source IP - increments every %d seconds if seen", delayBetweenReq),
})
var eipStartUpLatency = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "scale",
Name: "eip_startup_latency_total",
Help: fmt.Sprintf("time it takes in seconds for a connection to have a source IP of EgressIP at startup"+
" with polling interval of %d seconds", delayBetweenReq),
})
var eipRecoveryLatency = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "scale",
Name: "eip_recovery_latency",
Help: fmt.Sprintf("time it takes in seconds for an Egress IP connection to recover from failure"+
" with polling interval of %d seconds", delayBetweenReq),
})
var eipTick = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "scale",
Name: "eip_total",
Help: fmt.Sprintf("increments every time EgressIP seen as source IP - increments every %d seconds if seen", delayBetweenReq),
})
var nonEIPTick = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "scale",
Name: "non_eip_total",
Help: fmt.Sprintf("increments every time EgressIP not seen as source IP - increments every %d seconds if seen", delayBetweenReq),
})
var failure = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: "scale",
Name: "failure_total",
Help: fmt.Sprintf("increments every time there is a connection failure - increments every %d seconds if seen", delayBetweenReq),
})
// create metrics registry and register metrics
prometheus.MustRegister(startupNonEIPTick)
prometheus.MustRegister(eipStartUpLatency)
prometheus.MustRegister(eipRecoveryLatency)
prometheus.MustRegister(eipTick)
prometheus.MustRegister(nonEIPTick)
prometheus.MustRegister(failure)
return &startupNonEIPTick, &eipStartUpLatency, &eipRecoveryLatency, &eipTick, &nonEIPTick, &failure
}