-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
171 lines (144 loc) · 3.12 KB
/
api.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
package gouse
import (
"context"
"fmt"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"sync"
"time"
)
type IBackend struct {
URL string `json:"url"`
IsDead bool
mutex sync.RWMutex
}
type ILbConfig struct {
ProxyPort string `json:"proxy"`
Backends []IBackend `json:"backends"`
}
func (backend *IBackend) SetDead(b bool) {
backend.mutex.Lock()
backend.IsDead = b
backend.mutex.Unlock()
}
func (backend *IBackend) GetIsDead() bool {
backend.mutex.RLock()
isAlive := backend.IsDead
backend.mutex.RUnlock()
return isAlive
}
var mutex sync.Mutex
var idx int = 0
var cfg ILbConfig
func lbHandler(w http.ResponseWriter, r *http.Request) {
maxLen := len(cfg.Backends)
// Round Robin
mutex.Lock()
currentBackend := &cfg.Backends[idx%maxLen]
if currentBackend.GetIsDead() {
idx++
}
targetURL, err := url.Parse(currentBackend.URL)
if err != nil {
log.Println(err.Error())
}
idx++
mutex.Unlock()
reverseProxy := httputil.NewSingleHostReverseProxy(targetURL)
reverseProxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) {
log.Printf("%v is dead", targetURL)
currentBackend.SetDead(true)
lbHandler(w, r)
}
reverseProxy.ServeHTTP(w, r)
}
func isAlive(url *url.URL) bool {
conn, err := net.DialTimeout("tcp", url.Host, time.Minute*1)
if err != nil {
log.Printf("Unreachable tp %v, error:%v", url.Host, err.Error())
return false
}
defer func() {
if conn != nil {
conn.Close()
}
}()
return true
}
func HealthCheck() {
t := time.NewTicker(time.Minute * 1)
for range t.C {
for i := range cfg.Backends {
backend := &cfg.Backends[i]
pingURL, err := url.Parse(backend.URL)
if err != nil {
log.Print(err.Error())
continue
}
isAlive := isAlive(pingURL)
backend.SetDead(!isAlive)
msg := "alive"
if !isAlive {
msg = "dead"
}
log.Printf("%v checked %v by healthcheck", backend.URL, msg)
}
}
}
func LoadBalancer(proxyPort string, backends []IBackend) {
cfg = ILbConfig{
ProxyPort: proxyPort,
Backends: backends,
}
go HealthCheck()
s := http.Server{
Addr: ":" + cfg.ProxyPort,
Handler: http.HandlerFunc(lbHandler),
ReadHeaderTimeout: 10 * time.Second,
}
if err := s.ListenAndServe(); err != nil {
log.Printf("Error starting server: %s", err.Error())
}
}
type IGracefulShutdown struct {
Port string
StartMsg string
ShutdownMsg string
SleepTimout time.Duration
HeaderTimeout time.Duration
}
func (igs *IGracefulShutdown) GracefulShutdown() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(igs.SleepTimout)
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
fmt.Println(igs.StartMsg)
srv := http.Server{
Addr: ":" + igs.Port,
ReadHeaderTimeout: igs.HeaderTimeout,
}
go func() {
<-c
fmt.Println(igs.ShutdownMsg)
go func() {
for {
fmt.Println("waiting for goroutines to finish...")
time.Sleep(1 * time.Second)
}
}()
wg.Wait()
if err := srv.Shutdown(context.Background()); err != nil {
fmt.Println("server shutdown error:", err)
}
}()
fmt.Println(srv.ListenAndServe())
}