-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
414 lines (317 loc) · 9.48 KB
/
server.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
package webfmwk
import (
"context"
"fmt"
"log/slog"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"github.com/burgesQ/webfmwk/v6/tls"
fasthttp2 "github.com/dgrr/http2"
"github.com/lab259/cors"
"github.com/valyala/fasthttp"
// "golang.org/x/sync/errgroup"
)
const (
exitTLSConfigFailure = 2
exitTLSListenerFailure = 3
)
type (
// Server is a struct holding all the necessary data / struct
Server struct {
ctx context.Context //nolint:containedctx
cancel context.CancelFunc
wg *sync.WaitGroup
launcher WorkerLauncher
// log log.Log
slog *slog.Logger
isReady chan bool
meta serverMeta
}
)
var (
// TODO: use sync.Pool
// poolOfServers hold all the http(s) server to properly shut them down
poolOfServers []*fasthttp.Server
poolMu sync.Mutex
)
// Run allow to launch multiple server from a single call.
// It take an va arg list of Address as argument.
// The method wait for the server to end via a call to WaitAndStop.
func (s *Server) Run(addrs ...Address) {
defer s.WaitForStop()
for i := range addrs {
addr := addrs[i]
if !addr.IsOk() {
s.GetStructuredLogger().Error("invalid format", "address", addr)
continue
}
switch cfg := addr.GetTLS(); {
case cfg != nil && !cfg.Empty():
s.GetStructuredLogger().Info("starting https server",
"name", addr.GetName(), "address", "https://"+addr.GetAddr())
s.StartTLS(addr.GetAddr(), cfg)
case addr.IsUnixPath():
s.GetStructuredLogger().Info("starting unix socket server",
"name", addr.GetName(), "path", addr.GetAddr())
if e := s.StartUnixSocket(addr.GetAddr()); e != nil {
s.slog.Error("starting server", slog.Any("error", e))
s.cancel()
return
}
// continue
default:
s.GetStructuredLogger().Info("starting http server",
"name", addr.GetName(), "address", "http://"+addr.GetAddr())
s.Start(addr.GetAddr())
}
}
}
//
// Global methods
//
// Shututdown terminate all running servers.
func Shutdown() error {
poolMu.Lock()
defer poolMu.Unlock()
var senti error
for i, server := range poolOfServers {
if e := server.Shutdown(); e != nil {
senti = fmt.Errorf("shutdowning server %d : %w", i, e)
}
}
poolOfServers = nil
return senti
}
//
// Server implemtation
//
//
// Process methods
//
// Start expose an server to an HTTP endpoint.
func (s *Server) Start(addr string) {
if s.meta.http2 {
s.slog.Warn("https endpoints required with http2, skipping", slog.String("address", addr))
return
}
s.internalHandler()
started := make(chan struct{})
s.launcher.Start(func() {
s.slog.Debug("http server: starting", slog.String("address", addr))
go s.pollPingEndpoint(addr)
close(started)
if e := s.internalInit(addr).ListenAndServe(addr); e != nil {
s.slog.Error("http server", slog.String("address", addr), slog.Any("error", e))
}
s.slog.Info("http server: done", slog.String("address", addr))
})
<-started
}
func (s *Server) StartUnixSocket(path string) error {
s.internalHandler()
server := s.internalInit(path)
s.launcher.Start(func() {
s.slog.Debug("unix socket server: starting", slog.String("path", path))
defer s.slog.Info("unix socket server: done", slog.String("path", path))
if e := server.ListenAndServeUNIX(
strings.TrimPrefix(path, _unixSocketPrefix),
os.ModeSocket); e != nil {
s.slog.Error("unix socket server", slog.String("path", path), slog.Any("error", e))
}
})
return nil
}
// StartTLS expose an https server.
// The server may have mTLS and/or http2 capabilities.
func (s *Server) StartTLS(addr string, cfg tls.IConfig) {
s.internalHandler()
tlsCfg, err := tls.GetTLSCfg(cfg, s.meta.http2)
if err != nil {
s.slog.Error("loading tls config", slog.Any("error", err))
os.Exit(exitTLSConfigFailure)
}
listner, err := tls.LoadListner(addr, tlsCfg)
if err != nil {
s.slog.Error("loading tls listener", slog.Any("error", err))
os.Exit(exitTLSListenerFailure)
}
server := s.internalInit(addr)
if s.meta.http2 {
s.slog.Info("loading http2 support")
fasthttp2.ConfigureServer(server, fasthttp2.ServerConfig{Debug: true})
}
so2 := sOr2(s.meta.http2)
s.launcher.Start(func() {
s.slog.Debug(fmt.Sprintf("%s server: starting", so2), slog.String("address", addr))
defer s.slog.Info(fmt.Sprintf("%s server: done", so2), slog.String("address", addr))
go s.pollPingEndpoint(addr, cfg)
if e := server.Serve(listner); e != nil {
s.slog.Error(fmt.Sprintf("%s server", so2),
slog.String("address", addr), slog.Any("error", e))
}
})
}
func sOr2(http2 bool) string {
if http2 {
return "http2"
}
return "https"
}
// ShutdownAndWait call for Shutdown and wait for all server to terminate.
func (s *Server) ShutdownAndWait() error {
defer s.WaitForStop()
return s.Shutdown()
}
// Shutdown call the framework shutdown to stop all running server.
func (s *Server) Shutdown() error {
s.cancel()
return Shutdown()
}
// WaitForStop wait for all servers to terminate.
// Use of a sync.waitGroup to properly wait all running servers.
func (s *Server) WaitForStop() {
s.wg.Wait()
// g := errgroup.Group{}
// if err := g.Wait(); err != nil {
// return nil, err
// }
}
// DumpRoutes dump the API endpoints using the server logger.
func (s *Server) DumpRoutes() map[string][]string {
all := s.GetRouter().List()
for m, p := range all {
for i := range p {
s.slog.Info("routes", slog.String("name", m), slog.String("route", p[i]))
}
}
return all
}
type FastLogger struct{ *slog.Logger }
func (flg *FastLogger) Printf(msg string, keys ...any) {
flg.Info(fmt.Sprintf(msg, keys...))
}
// Initialize a http.Server struct. Save the server in the pool of workers.
func (s *Server) internalInit(addr string) *fasthttp.Server {
var (
worker = s.meta.toServer(addr)
router = s.GetRouter()
)
// register CORS handler - note that it should be the first one
if s.meta.cors {
worker.Handler = cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedHeaders: []string{"X-Requested-With", "Content-Type"},
AllowedMethods: []string{"POST", "PUT", "PATCH", "OPTIONS"},
AllowCredentials: true,
// Debug: true,
}).Handler(router.Handler)
} else {
worker.Handler = router.Handler
}
worker.Logger = &FastLogger{s.slog}
// save the server
poolMu.Lock()
defer poolMu.Unlock()
poolOfServers = append(poolOfServers, worker)
s.slog.Debug("[+] server ", slog.String("address", addr), slog.Int("total", len(poolOfServers)))
return worker
}
func concatAddr(addr, prefix string) string {
if len(addr) > 1 && addr[0] == ':' {
return "http://127.0.0.1" + addr + prefix + _pingEndpoint
} else if strings.HasPrefix(addr, "127.0.0.1") {
return "http://" + addr + prefix + _pingEndpoint
}
return addr + prefix + _pingEndpoint
}
// launch the ctrl+c job if needed.
func (s *Server) internalHandler() {
if s.meta.ctrlc && !s.meta.ctrlcStarted {
s.launcher.Start(func() {
s.slog.Debug("exit handler: starting")
s.exitHandler(os.Interrupt, syscall.SIGHUP)
s.slog.Info("exit handler: done")
})
s.meta.ctrlcStarted = true
}
}
// handle ctrl+c internaly.
func (s *Server) exitHandler(sig ...os.Signal) {
c := make(chan os.Signal, 1)
signal.Notify(c, sig...)
defer func() {
if e := s.Shutdown(); e != nil {
s.slog.Error("cannot stop the server", slog.Any("error", e))
}
}()
for s.ctx.Err() == nil {
select {
case si := <-c:
s.slog.Info("captured signal, exiting...", slog.String("signal", si.String()))
return
case <-s.ctx.Done():
return
}
}
}
//
// Setter/Getter
//
// GetLogger return the used Log instance.
func (s *Server) GetStructuredLogger() *slog.Logger { return s.slog }
// GetLauncher return a pointer to the internal workerLauncher.
func (s *Server) GetLauncher() WorkerLauncher { return s.launcher }
// GetContext return the context.Context used.
func (s *Server) GetContext() context.Context { return s.ctx }
// GetContext return the server' context cancel func.
func (s *Server) GetCancel() context.CancelFunc { return s.cancel }
// IsReady return the channel on which `true` is send once the server is up.
func (s *Server) IsReady() chan bool { return s.isReady }
// AddHandlers register the Handler handlers. Handler are executed from the top most.
func (s *Server) addHandlers(h ...Handler) *Server { //nolint: unparam
s.meta.handlers = append(s.meta.handlers, h...)
return s
}
// RegisterDocHandler is used to register an swagger doc handler.
func (s *Server) addDocHandlers(h ...DocHandler) *Server {
s.meta.docHandlers = append(s.meta.docHandlers, h...)
return s
}
// SetPrefix save a custom context so it can be fetched in the controllers.
func (s *Server) setPrefix(prefix string) *Server {
s.meta.prefix = prefix
return s
}
// RegisterLogger register the Log used.
func (s *Server) registerStructuredLogger(slg *slog.Logger) *Server {
s.slog = slg
return s
}
// EnableCORS enable CORS verification.
func (s *Server) enableCORS() *Server {
s.meta.cors = true
return s
}
// enableCheckIsUp add an /ping endpoint.
// If used, once a server is started, the user can check weather the server is
// up or not by reading the isReady channel vie the IsReady() method.
func (s *Server) EnableCheckIsUp() *Server {
s.meta.checkIsUp = true
return s
}
// DisableHTTP2 allow to disable HTTP2 on the fly.
// It usage isn't recommanded.
// For testing purpore only.
func (s *Server) DisableHTTP2() *Server {
s.meta.http2 = false
return s
}
// EnableCtrlC let the server handle the SIGINT interuption.
// To add worker to the interuption pool, please use the `GetLauncher` method.
func (s *Server) enableCtrlC() *Server {
s.meta.ctrlc = true
return s
}