/
main.go
181 lines (144 loc) · 3.5 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
package lb
import (
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"sync"
"time"
"golang.org/x/exp/slices"
)
var config *Config
const (
HTTPConnTypeTCP string = "tcp"
ReverseProxyTypeRoundRobin ReverseProxyType = "RoundRobin"
ReverseProxyTypePathPrefix ReverseProxyType = "PathPrefix"
)
type (
Path string // Path represents a URL path
ReverseProxyType string
)
type Config struct {
ReverseProxy ReverseProxy
Workers []*Worker
Type ReverseProxyType
}
type ReverseProxy struct {
Port string
}
type Worker struct {
URL string
Alive bool
mu sync.RWMutex
Paths []Path
}
type SetReverseProxyAndServeOpts struct {
*Config
}
func SetReverseProxyAndServe(opts *SetReverseProxyAndServeOpts) {
// TODO: refactor this to receive them in form of flags
// e.g. go run main.go --proxy 8080 --workers 8081,8082,8083
config = opts.Config
go healthCheck()
server := http.Server{
Addr: ":" + config.ReverseProxy.Port,
Handler: http.HandlerFunc(ReverseProxyHandler),
}
if err := server.ListenAndServe(); err != nil {
log.Fatal(err.Error())
}
}
var mu sync.Mutex
var requestCounter int = 0
func ReverseProxyHandler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
currentWorker := config.FindCurrentWorker(w, r)
targetURL, err := url.Parse(currentWorker.URL)
if err != nil {
log.Fatal(err.Error())
}
requestCounter++
mu.Unlock()
rp := httputil.NewSingleHostReverseProxy(targetURL)
rp.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("%v is dead.", targetURL)
currentWorker.SetAlive(false)
ReverseProxyHandler(w, r)
}
rp.ServeHTTP(w, r)
}
func (config *Config) FindCurrentWorker(w http.ResponseWriter, r *http.Request) *Worker {
if config.Type == ReverseProxyTypePathPrefix {
workerFoundByPath := config.FindWorkerByPath(w, r)
if workerFoundByPath != nil && workerFoundByPath.IsAlive() {
return workerFoundByPath
}
}
// defaults to RR
workerFoundByRR := config.FindWorkerByRoundRobin(w, r)
if workerFoundByRR != nil && workerFoundByRR.IsAlive() {
return workerFoundByRR
}
return nil
}
func (config *Config) FindWorkerByPath(w http.ResponseWriter, r *http.Request) *Worker {
for _, worker := range config.Workers {
if slices.Contains(worker.Paths, Path(r.URL.Path)) {
return worker
}
}
return nil
}
func (config *Config) FindWorkerByRoundRobin(w http.ResponseWriter, r *http.Request) *Worker {
if requestCounter >= len(config.Workers) {
requestCounter = 0
}
currentWorker := config.Workers[requestCounter]
if !currentWorker.IsAlive() {
requestCounter++
return nil
}
return currentWorker
}
func (worker *Worker) SetAlive(b bool) {
worker.mu.Lock()
worker.Alive = b
worker.mu.Unlock()
}
func (worker *Worker) IsAlive() bool {
worker.mu.RLock()
isAlive := worker.Alive
worker.mu.RUnlock()
return isAlive
}
func isWorkerAlive(url *url.URL) bool {
conn, err := net.DialTimeout(HTTPConnTypeTCP, url.Host, time.Minute*1)
if err != nil {
log.Printf("Cannot reach %v, error: %v", url.Host, err.Error())
return false
}
defer conn.Close()
return true
}
func healthCheck() {
countdown := time.NewTicker(time.Second * 10)
for {
select {
case <-countdown.C:
for _, worker := range config.Workers {
pingURL, err := url.Parse(worker.URL)
if err != nil {
log.Fatal(err.Error())
}
a := isWorkerAlive(pingURL)
worker.SetAlive(a)
msg := "Alive"
if !a {
msg = "Dead"
}
log.Printf("%v is %v", worker.URL, msg)
}
}
}
}