-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
150 lines (132 loc) · 2.99 KB
/
server.go
File metadata and controls
150 lines (132 loc) · 2.99 KB
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
package goloadbalancer
import (
"encoding/json"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httputil"
"net/url"
"sync"
"time"
)
//reverse proxy
// func Serve() {
// director := func(request *http.Request) {
// request.URL.Scheme = "http"
// request.URL.Host = ":8081"
// }
// rp := &httputil.ReverseProxy{
// Director: director,
// }
// s := http.Server{
// Addr: ":8080",
// Handler: rp,
// }
// if err := s.ListenAndServe(); err != nil {
// log.Fatal(err.Error())
// }
// }
// Config
type Config struct {
Proxy Proxy `json:"proxy"`
Backends []Backend `json:"backends"`
}
// Proxy is a reverse proxy, and means load balancer.
type Proxy struct {
Port string `json:"port"`
}
// Backend is servers which load balancer is transferred.
type Backend struct {
URL string `json:"url"`
IsDead bool
mu *sync.RWMutex
}
// SetDead updates the value of IsDead in Backend.
func (backend *Backend) SetDead(b bool) {
backend.mu.Lock()
backend.IsDead = b
backend.mu.Unlock()
}
// GetIsDead returns the value of IsDead in Backend.
func (backend *Backend) GetIsDead() bool {
backend.mu.RLock()
isAlive := backend.IsDead
backend.mu.RUnlock()
return isAlive
}
var mu sync.Mutex
var idx int = 0
// lbHandler is a handler for loadbalancing
func lbHandler(w http.ResponseWriter, r *http.Request) {
maxLen := len(cfg.Backends)
// Round Robin
mu.Lock()
currentBackend := cfg.Backends[idx%maxLen]
if currentBackend.GetIsDead() {
idx++
}
targetURL, err := url.Parse(cfg.Backends[idx%maxLen].URL)
if err != nil {
log.Fatal(err.Error())
}
idx++
mu.Unlock()
reverseProxy := httputil.NewSingleHostReverseProxy(targetURL)
reverseProxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) {
// NOTE: It is better to implement retry.
log.Printf("%v is dead.", targetURL)
currentBackend.SetDead(true)
lbHandler(w, r)
}
reverseProxy.ServeHTTP(w, r)
}
// pingBackend checks if the backend is alive.
func isAlive(url *url.URL) bool {
conn, err := net.DialTimeout("tcp", url.Host, time.Minute*1)
if err != nil {
log.Printf("Unreachable to %v, error:%v", url.Host, err.Error())
return false
}
defer conn.Close()
return true
}
// healthCheck is a function for healthcheck
func healthCheck() {
t := time.NewTicker(time.Minute * 1)
for {
select {
case <-t.C:
for _, backend := range cfg.Backends {
pingURL, err := url.Parse(backend.URL)
if err != nil {
log.Fatal(err.Error())
}
isAlive := isAlive(pingURL)
backend.SetDead(!isAlive)
msg := "ok"
if !isAlive {
msg = "dead"
}
log.Printf("%v checked %v by healthcheck", backend.URL, msg)
}
}
}
}
var cfg Config
// Serve serves a loadbalancer.
func Serve() {
data, err := ioutil.ReadFile("./config.json")
if err != nil {
log.Fatal(err.Error())
}
json.Unmarshal(data, &cfg)
go healthCheck()
s := http.Server{
Addr: ":" + cfg.Proxy.Port,
Handler: http.HandlerFunc(lbHandler),
}
if err = s.ListenAndServe(); err != nil {
log.Fatal(err.Error())
}
}