-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmain.go
More file actions
244 lines (205 loc) · 6.01 KB
/
main.go
File metadata and controls
244 lines (205 loc) · 6.01 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
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
package main
import (
"bytes"
"context"
"fmt"
"io"
"loadbalancer/lib"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"syscall"
"time"
)
type RetryType int
type AttemptsType int
const (
Attempts AttemptsType = iota
Retry
)
var serverPool lib.ServerPool
// this function creates a log file if it does not already exist
func InitLogger() (*os.File, error) {
logFile, err := os.OpenFile("loadbalancer.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return nil, err
}
log.SetOutput(logFile)
log.SetFlags(log.LstdFlags | log.Lshortfile)
return logFile, nil
}
// this function logs details about incoming requests
func LogRequest(r *http.Request) {
clientIp := r.RemoteAddr
method := r.Method
url := r.URL.String()
log.Printf("Received request from %s : %s, %s ", clientIp, method, url)
}
// this function logs which backend is selected
func LogBackendSelection(backendURL string) {
log.Printf("Routing request to backend: %s", backendURL)
}
// this function measures the time taken to process a request
func TrackresponseTime(start time.Time, backendURL string) {
duration := time.Since(start)
log.Printf("Request to backend %s took %v", backendURL, duration)
}
// this functions returns the retry count from the context
func GetRetryFromContext(r *http.Request) int {
if retry, ok := r.Context().Value(Retry).(int); ok {
return retry
}
return 0
}
// this function returns the attempts from the context
func GetAttemptsFromContext(r *http.Request) int {
if attempts, ok := r.Context().Value(Attempts).(int); ok {
return attempts
}
return 1
}
func lb(w http.ResponseWriter, r *http.Request) {
//log the request
LogRequest(r)
peer := serverPool.GetNextPeer()
attempts := GetAttemptsFromContext(r)
if attempts > 3 {
http.Error(w, "Service not available, max attempts reached", http.StatusServiceUnavailable)
return
}
if peer != nil {
LogBackendSelection(peer.URL.String())
startTime := time.Now()
peer.ReverseProxy.ServeHTTP(w, r)
// Log response time
TrackresponseTime(startTime, peer.URL.String())
peer.Mux.Lock()
if peer.Weight > 0 {
peer.Weight--
}
peer.Mux.Unlock()
return
}
http.Error(w, "Service not available", http.StatusServiceUnavailable)
}
func main() {
//Initialize logger
logfile, err := InitLogger()
if err != nil {
log.Fatalf("Error initializing logger: %v", err)
}
defer logfile.Close()
// get file name from argument
arg := os.Args
if len(arg) != 2 {
log.Fatal("usage go run main.go <config-file>'")
}
// declare slice for backend server
backendservers := []string{}
// read the config file and get the host and url.
var config lib.Config
config, err = lib.ReadConfig(arg[1])
if err != nil {
log.Fatal(err)
}
for _, node := range config.BackendConfig {
backendservers = append(backendservers, node.Url)
}
if len(backendservers) == 0 {
log.Println("No backend servers found")
return
}
for _, backend := range backendservers {
log.Println("Load balancing to the backend server: ", backend)
be, err := url.Parse(backend)
log.Println(be)
if err != nil {
log.Println("Error parsing URL")
}
proxy := httputil.NewSingleHostReverseProxy(be)
proxy.Director = func(r *http.Request) {
if r.Body != nil {
bodyBytes, _ := io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
}
r.Header.Set("User-Agent", "Your-User-Agent")
r.Header.Set("Accept", "application/json")
r.Header.Set("X-Custom-Header", "CustomValue")
r.URL.Scheme = be.Scheme
r.URL.Host = be.Host
r.Host = be.Host
}
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) {
log.Printf("[%s] Request Canceled: %v\n", be.Host, r.Context().Err() == context.Canceled)
log.Printf("[%s] %s\n", be.Host, e.Error())
retries := GetRetryFromContext(r)
log.Println("This is the retry count", retries, "of the server")
if retries < 3 {
time.Sleep(10 * time.Millisecond)
ctx := context.WithValue(r.Context(), Retry, retries+1)
log.Println("check")
proxy.ServeHTTP(w, r.WithContext(ctx))
return
}
ctx := context.WithValue(r.Context(), Retry, 0)
log.Printf("[%s] Marking server as down\n", be.Host)
serverPool.MarkDownTheServer(be, false)
lb(w, r.WithContext(ctx))
}
serverPool.Backends = append(serverPool.Backends, &lib.ServerNode{
URL: be,
Alive: true,
ReverseProxy: proxy,
})
}
// creating routers for frontend and loadbalancer
mux := http.NewServeMux()
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
//for laodbalancer
mux.HandleFunc("/", lb)
//for frontend
mux.HandleFunc("/info-loaddistrix", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "templates/index.html")
})
mux.HandleFunc("/status-loadDistrix", func(w http.ResponseWriter, r *http.Request) {
// Generate HTML dynamically
for _, server := range serverPool.Backends {
w.Write([]byte(`
<tr>
<td>` + server.URL.Host + `</td>
<td>` + "Server Status" + fmt.Sprint(server.Alive) + `</td>
<td class="` + "Server Load" + `">` + fmt.Sprint(server.Weight) + `</td>
</tr>`))
}
})
server := &http.Server{
Addr: ":8000",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
Handler: mux,
}
// Channel to listen for interrupt or termination signals
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
// Start the server in a goroutine
go func() {
log.Println("Server is starting on port 8000")
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Server failed: %v", err)
}
}()
// Wait for termination signal
<-shutdown
// Graceful shutdown with timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
log.Println("Shutting down gracefully...")
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
}
log.Println("Server exited properly")
}