/
webserver.go
437 lines (368 loc) · 13 KB
/
webserver.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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package core
import (
"crypto/tls"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"runtime"
"strings"
"time"
"golang.org/x/net/http2"
rice "github.com/GeertJohan/go.rice"
"github.com/schubergphilis/mercury/internal/config"
"github.com/schubergphilis/mercury/internal/web"
"github.com/schubergphilis/mercury/pkg/dns"
"github.com/schubergphilis/mercury/pkg/logging"
"github.com/schubergphilis/mercury/pkg/proxy"
"github.com/schubergphilis/mercury/pkg/tlsconfig"
)
// processInfo contains details about the mercury process
type processInfo struct {
Version string
VersionBuild string
VersionSha string
VersionGo string
StartTime string
Uptime string
ReloadTime string
FailedReloadTime string
FailedReloadError string
}
// FormattedDate date to readable time
func FormattedDate(t time.Time) string {
if t.IsZero() {
return "never"
}
return t.Format(time.RFC822)
}
const applicationJSONHeader = "application/json"
// WebBackendDetails Provides a detail page for backends
func WebBackendDetails(w http.ResponseWriter, r *http.Request) {
log := logging.For("core/backenddetails").WithField("func", "web")
w.Header().Add("Cache-Control", "max-age=0, no-cache, must-revalidate, proxy-revalidate")
r.URL.Query().Get("backend")
pool := r.URL.Query().Get("pool")
backend := r.URL.Query().Get("backend")
poolDetails := config.Get().Loadbalancer.Pools[pool]
backendDetails := config.Get().Loadbalancer.Pools[pool].Backends[backend]
clusternode := config.Get().Cluster.Binding.Name
title := fmt.Sprintf("Mercury %s - Backend Details %s", clusternode, backend)
_, username, err := authenticateUser(r)
if err != nil {
log.Warnf("Error authenticating user: %s", err)
}
page := newPage(title, r.RequestURI, username)
templateNames := []string{"backenddetails.tmpl", "header.tmpl", "footer.tmpl"}
backenddetailsTemplate, err := web.LoadTemplates("static", templateNames)
if err != nil {
log.WithField("error", err).Warn("Error loading templates")
}
data := struct {
Pool config.LoadbalancePool
Backend config.BackendPool
PoolName string
BackendName string
Page web.Page
}{poolDetails, backendDetails, pool, backend, *page}
err = backenddetailsTemplate.ExecuteTemplate(w, "backenddetails", data)
if err != nil {
log.WithField("error", err).Warn("Error executing template")
}
}
// WebClusterStatus Provides a status page for Cluster status
func WebClusterStatus(w http.ResponseWriter, r *http.Request) {
log := logging.For("core/clusterstatus").WithField("func", "web")
w.Header().Add("Cache-Control", "max-age=0, no-cache, must-revalidate, proxy-revalidate")
clusternode := config.Get().Cluster.Binding.Name
title := fmt.Sprintf("Mercury %s - Cluster Status", clusternode)
_, username, err := authenticateUser(r)
if err != nil {
log.Warnf("Error authenticating user: %s", err)
}
page := newPage(title, r.RequestURI, username)
templateNames := []string{"cluster.tmpl", "header.tmpl", "footer.tmpl"}
clusterTemplate, err := web.LoadTemplates("static", templateNames)
if err != nil {
log.Warnf("Error loading templates: %s", err)
}
data := struct {
ClusterAPIPath string
Page web.Page
}{"/api/v1/cluster/" + clusternode, *page}
err = clusterTemplate.ExecuteTemplate(w, "cluster", data)
if err != nil {
log.WithField("error", err).Warn("Error executing template")
}
}
// WebProxyStatus Provides a status page for Proxy service
func WebProxyStatus(w http.ResponseWriter, r *http.Request) {
if pusher, ok := w.(http.Pusher); ok {
// Push is supported.
if err := pusher.Push("/static/logo32.png", nil); err != nil {
log.Printf("Failed to push: %v", err)
}
if err := pusher.Push("/static/list.min.js", nil); err != nil {
log.Printf("Failed to push: %v", err)
}
if err := pusher.Push("/static/jquery.min.js", nil); err != nil {
log.Printf("Failed to push: %v", err)
}
}
log := logging.For("core/proxystatus").WithField("func", "web")
w.Header().Add("Cache-Control", "max-age=0, no-cache, must-revalidate, proxy-revalidate")
switch r.Header.Get("Content-type") {
case applicationJSONHeader:
data, err := json.Marshal(proxies.pool)
if err != nil {
fmt.Fprintf(w, "{ error:'%s' }", err)
}
fmt.Fprint(w, string(data))
default:
clusternode := config.Get().Cluster.Binding.Name
title := fmt.Sprintf("Mercury %s - Proxy Status", clusternode)
_, username, err := authenticateUser(r)
if err != nil {
log.Warnf("Error authenticating user: %s", err)
}
page := newPage(title, r.RequestURI, username)
templateNames := []string{"proxy.tmpl", "header.tmpl", "footer.tmpl"}
proxyTemplate, err := web.LoadTemplates("static", templateNames)
if err != nil {
log.Warnf("Error loading templates: %s", err)
}
data := struct {
Proxies map[string]*proxy.Listener
Page web.Page
}{proxies.pool, *page}
err = proxyTemplate.ExecuteTemplate(w, "proxy", data)
if err != nil {
log.WithField("error", err).Warn("Error executing template")
}
}
}
// WebBackendStatus Provides a status page for Backend Status
func WebBackendStatus(w http.ResponseWriter, r *http.Request) {
log := logging.For("core/backendstatus").WithField("func", "web")
w.Header().Add("Cache-Control", "max-age=0, no-cache, must-revalidate, proxy-revalidate")
loadbalancer := config.Get().Loadbalancer
switch r.Header.Get("Content-type") {
case applicationJSONHeader:
data, err := json.Marshal(loadbalancer)
if err != nil {
fmt.Fprintf(w, "{ error:'%s' }", err)
}
fmt.Fprint(w, string(data))
default:
clusternode := config.Get().Cluster.Binding.Name
title := fmt.Sprintf("Mercury %s - Backend Status", clusternode)
_, username, err := authenticateUser(r)
if err != nil {
log.Warnf("Error authenticating user: %s", err)
}
page := newPage(title, r.RequestURI, username)
templateNames := []string{"backend.tmpl", "header.tmpl", "footer.tmpl"}
backendTemplate, err := web.LoadTemplates("static", templateNames)
if err != nil {
log.Warnf("Error loading templates: %s", err)
}
data := struct {
Loadbalancer config.Loadbalancer
Page web.Page
ClusterNode string
}{loadbalancer, *page, config.Get().Cluster.Binding.Name}
err = backendTemplate.ExecuteTemplate(w, "backend", data)
if err != nil {
log.WithField("error", err).Warn("Error executing template")
}
}
}
// WebGLBStatus Provides a status page for GLB
func WebGLBStatus(w http.ResponseWriter, r *http.Request) {
log := logging.For("core/glbstatus").WithField("func", "web")
w.Header().Add("Cache-Control", "max-age=0, no-cache, must-revalidate, proxy-revalidate")
dnscache := dns.GetCache()
switch r.Header.Get("Content-type") {
case applicationJSONHeader:
data, err := json.Marshal(dnscache)
if err != nil {
fmt.Fprintf(w, "{ error:'%s' }", err)
}
fmt.Fprint(w, string(data))
default:
clusternode := config.Get().Cluster.Binding.Name
title := fmt.Sprintf("Mercury %s - GLB Status", clusternode)
_, username, err := authenticateUser(r)
if err != nil {
log.Warnf("Error authenticating user: %s", err)
}
page := newPage(title, r.RequestURI, username)
templateNames := []string{"glb.tmpl", "header.tmpl", "footer.tmpl"}
backendTemplate, err := web.LoadTemplates("static", templateNames)
if err != nil {
log.Warnf("Error loading templates: %s", err)
}
data := struct {
DNS map[string]dns.Domains
Page web.Page
}{dnscache, *page}
err = backendTemplate.ExecuteTemplate(w, "glb", data)
if err != nil {
log.WithField("error", err).Warn("Error executing template")
}
}
}
// WebLocalDNSStatus Provides a status page for GLB
func WebLocalDNSStatus(w http.ResponseWriter, r *http.Request) {
log := logging.For("core/localdnsstatus").WithField("func", "web")
w.Header().Add("Cache-Control", "max-age=0, no-cache, must-revalidate, proxy-revalidate")
dnscache := dns.GetCache()
switch r.Header.Get("Content-type") {
case applicationJSONHeader:
data, err := json.Marshal(dnscache)
if err != nil {
fmt.Fprintf(w, "{ error:'%s' }", err)
}
fmt.Fprint(w, string(data))
default:
clusternode := config.Get().Cluster.Binding.Name
title := fmt.Sprintf("Mercury %s - LocalDNS Status", clusternode)
_, username, err := authenticateUser(r)
if err != nil {
log.Warnf("Error authenticating user: %s", err)
}
page := newPage(title, r.RequestURI, username)
templateNames := []string{"localdns.tmpl", "header.tmpl", "footer.tmpl"}
backendTemplate, err := web.LoadTemplates("static", templateNames)
if err != nil {
log.Warnf("Error loading templates: %s", err)
}
data := struct {
DNS map[string]dns.Domains
Page web.Page
}{dnscache, *page}
err = backendTemplate.ExecuteTemplate(w, "glb", data)
if err != nil {
log.WithField("error", err).Warn("Error executing template")
}
}
}
func uptime(t time.Duration) string {
if (t.Hours() / 24) > 1 {
return fmt.Sprintf("%.0fd", t.Hours()/24)
} else if t.Hours() > 1 {
return fmt.Sprintf("%.0fh", t.Hours())
} else if t.Minutes() > 1 {
return fmt.Sprintf("%.0fm", t.Minutes())
} else if t.Seconds() > 1 {
return fmt.Sprintf("%.0fs", t.Seconds())
}
return fmt.Sprintf("%.0dns", t.Nanoseconds())
}
// WebRoot serves Webserver's root folder
func WebRoot(w http.ResponseWriter, r *http.Request) {
log := logging.For("core/webroot").WithField("func", "web")
_, username, err := authenticateUser(r)
if err != nil {
log.Warnf("Error authenticating user: %s", err)
}
page := newPage("Mercury Global Loadbalancer", r.RequestURI, username)
templateNames := []string{"root.tmpl", "header.tmpl", "footer.tmpl"}
template, err := web.LoadTemplates("static", templateNames)
if err != nil {
log.Warnf("Error loading templates: %s", err)
}
data := struct {
ProcessInfo processInfo
Page web.Page
}{processInfo{
strings.TrimSuffix(config.Version, "\""),
strings.TrimSuffix(config.VersionBuild, "\""),
strings.TrimSuffix(config.VersionSha, "\""),
runtime.Version(),
FormattedDate(config.StartTime),
uptime(time.Since(config.StartTime)),
FormattedDate(config.ReloadTime),
FormattedDate(config.FailedReloadTime),
config.FailedReloadError,
}, *page}
err = template.ExecuteTemplate(w, "root", data)
if err != nil {
log.WithField("error", err).Warn("Error executing template")
}
}
func newPage(title, uri, username string) *web.Page {
return &web.Page{
Title: title,
URI: uri,
Hostname: config.Get().Cluster.Binding.Name,
Time: time.Now(),
Username: username,
}
}
// NewServer sets up a new webserver
func (m *Manager) NewServer(ip string, port int) (s *http.Server, l net.Listener, err error) {
s = &http.Server{
Addr: fmt.Sprintf("%s:%d", ip, port),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
Handler: WebSecurityHeaders(http.DefaultServeMux),
}
box, _ := rice.FindBox("static")
staticContent := http.StripPrefix("/static/", http.FileServer(box.HTTPBox()))
http.Handle("/static/", staticContent)
fs := http.FileServer(http.Dir(config.Get().Web.Path))
http.Handle("/internal/", http.StripPrefix("/internal/", fs))
http.HandleFunc("/glb", WebGLBStatus)
http.HandleFunc("/localdns", WebLocalDNSStatus)
http.HandleFunc("/backend", WebBackendStatus)
http.HandleFunc("/proxy", WebProxyStatus)
http.HandleFunc("/cluster", WebClusterStatus)
http.HandleFunc("/backenddetails", WebBackendDetails)
http.HandleFunc("/", WebRoot)
l, err = net.Listen("tcp", fmt.Sprintf("%s:%d", ip, port))
return
}
// InitializeWebserver starts the webserver
func (m *Manager) InitializeWebserver() {
log := logging.For("core/webserver").WithField("ip", config.Get().Web.Binding).WithField("port", config.Get().Web.Port).WithField("func", "web")
log.Info("Starting web server")
server, listener, err := m.NewServer(config.Get().Web.Binding, config.Get().Web.Port)
if config.Get().Web.TLSConfig.CertificateFile != "" {
log.WithField("file", config.Get().Web.TLSConfig.CertificateFile).Debug("Enabling SSL for web service")
tlsconf, terr := tlsconfig.LoadCertificate(config.Get().Web.TLSConfig)
if terr != nil {
log.WithField("error", terr).Errorf("Failed to load SSL certificate for web service")
}
server.TLSConfig = tlsconf
http2.ConfigureServer(server, &http2.Server{})
listener = tls.NewListener(listener, server.TLSConfig)
}
if err == nil {
defer listener.Close()
log.Info("Started web server")
err = server.Serve(listener)
if err != nil {
log.Fatalf("Error Starting Webservice: %s", err)
}
}
}
func webWriteError(w http.ResponseWriter, statusCode int, err string) {
w.WriteHeader(statusCode)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte("Oops... " + err))
}
// WebSecurityHeaders adds security headers to the web gui
func WebSecurityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("X-XSS-Protection", "1; mode=block")
w.Header().Add("X-Frame-Options", "SAMEORIGIN")
w.Header().Add("X-Content-Type-Options", "nosniff")
if r.TLS != nil {
w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubdomains; preload")
}
next.ServeHTTP(w, r)
})
}