-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
179 lines (149 loc) · 4.23 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
package main
import (
"fmt"
"log"
"net"
"os"
"os/signal"
"regexp"
"strings"
"sync"
"syscall"
"time"
)
var appIsHealthy = true
var startDelay = 0 * time.Second
var drainDelay = 0 * time.Second
var stopDelay = 0 * time.Second
func main() {
port, ok := os.LookupEnv("PORT")
if !ok {
port = "8080"
}
initialHealth, ok := os.LookupEnv("INITIAL_HEALTH")
if ok {
appIsHealthy = strings.ToLower(initialHealth) == "true"
}
durationFromEnv("START_DELAY", &startDelay)
durationFromEnv("DRAIN_DELAY", &drainDelay)
durationFromEnv("STOP_DELAY", &stopDelay)
log.Printf("waiting %s for startup\n", startDelay)
time.Sleep(startDelay)
log.Printf("done waiting")
log.Printf("Listening on :%s | app-health: %t", port, appIsHealthy)
setupTcpServer(port)
}
func setupTcpServer(port string) {
// Listen for incoming connections on port 8080
ln, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Println(err)
return
}
waitGroup := &sync.WaitGroup{}
waitGroup.Add(1)
go setupDelayedShutdown(ln, waitGroup)
// Infinite loop to handle incoming connections
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
break
}
// Handle incoming connection in a separate goroutine
go handleConnection(conn)
}
//wait for delayed shutdown
log.Println("connection loop done, waiting for waitgroup")
waitGroup.Wait()
}
func durationFromEnv(envVar string, duration *time.Duration) {
var err error
durationString, ok := os.LookupEnv(envVar)
if ok {
*duration, err = time.ParseDuration(durationString)
if err != nil {
log.Fatalf("invalid %s: %s", envVar, durationString)
}
} // else keep default
}
func setupDelayedShutdown(ln net.Listener, group *sync.WaitGroup) {
defer group.Done()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
for {
select {
case sig := <-sigChan:
log.Printf("Received signal %v...", sig)
log.Printf("draining for %v", drainDelay)
time.Sleep(drainDelay)
log.Printf("done drainig. closing listener.")
err := ln.Close()
if err != nil {
log.Print(err)
}
log.Printf("sleeping for %v before stop.", stopDelay)
time.Sleep(stopDelay)
log.Printf("done sleeping. exiting.")
syscall.Exit(0) // we need to syscall exit here in case the incoming connection loop doesn't receive any more connections and doesn't break
default:
time.Sleep(100 * time.Millisecond)
}
}
}
func getHttpPathAndMethod(requestBody []byte) (string, string, error) {
//requestLine:= strings.Split(string(requestBody), "\n")
re := regexp.MustCompile(`^(\S+)\s+(\S+)\s+HTTP/\d\.\d`)
matches := re.FindStringSubmatch(string(requestBody))
if len(matches) < 3 {
return "", "", fmt.Errorf("could not parse HTTP request %s", string(requestBody))
}
method := matches[1]
path := matches[2]
return path, method, nil
}
func handleConnection(conn net.Conn) {
// Close the connection when this function exits
defer conn.Close()
// Create a buffer to read incoming data
buf := make([]byte, 1024)
_, err := conn.Read(buf)
if err != nil {
log.Println(err)
return
}
path, method, err := getHttpPathAndMethod(buf)
if err != nil {
log.Println(err)
}
switch path {
case "/health":
log.Printf("received health check request. Healthy: %t", appIsHealthy)
if appIsHealthy {
response := "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nApp is healthy!"
conn.Write([]byte(response))
} else {
conn.Close()
}
case "/togglehealth":
appIsHealthy = !appIsHealthy
log.Printf("received toggle-health request. New health: %t", appIsHealthy)
response := fmt.Sprintf("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\napp healthy: %t", appIsHealthy)
conn.Write([]byte(response))
case "/drop":
log.Printf("received drop request. New health: %t", appIsHealthy)
conn.Close()
case "/always_up":
log.Printf("received always_up request: %t", appIsHealthy)
response := "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello World!\r\n"
conn.Write([]byte(response))
default:
log.Printf("received request: method: %s, path: %s | app-health: %t", method, path, appIsHealthy)
if appIsHealthy {
response := "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello World!\r\n"
conn.Write([]byte(response))
} else {
conn.Close()
}
}
}