-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
404 lines (360 loc) · 9.88 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
package server
import (
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"sync"
"github.com/aukbit/pluto/v6/common"
"github.com/aukbit/pluto/v6/discovery"
"github.com/aukbit/pluto/v6/server/router"
"github.com/rs/zerolog"
"golang.org/x/net/context"
"google.golang.org/grpc/health"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc"
)
const (
// DefaultName server prefix name
DefaultName = "server"
)
// A Server defines parameters for running an HTTP server.
// The zero value for Server is a valid configuration.
type Server struct {
close chan bool
cfg Config
wg *sync.WaitGroup
httpServer *http.Server
grpcServer *grpc.Server
health *health.Server
logger zerolog.Logger
}
// New returns a new http server with cfg passed in
func New(opts ...Option) *Server {
return newServer(opts...)
}
// newServer will instantiate a new defaultServer with the given config
func newServer(opts ...Option) *Server {
s := &Server{
cfg: newConfig(),
close: make(chan bool),
wg: &sync.WaitGroup{},
health: health.NewServer(),
}
s.logger = zerolog.New(os.Stderr).With().Timestamp().Logger()
if len(opts) > 0 {
s = s.WithOptions(opts...)
}
return s
}
// WithOptions clones the current Client, applies the supplied Options, and
// returns the resulting Client. It's safe to use concurrently.
func (s *Server) WithOptions(opts ...Option) *Server {
for _, opt := range opts {
opt.apply(s)
}
return s
}
// Run Server
func (s *Server) Run(opts ...Option) error {
// set last configs
for _, opt := range opts {
opt.apply(s)
}
s.logger = s.logger.With().Dict("server", zerolog.Dict().
Str("id", s.cfg.ID).
Str("name", s.cfg.Name).
Str("format", s.cfg.Format).
Str("port", s.cfg.Addr),
).Logger()
// register at service discovery
if err := s.register(); err != nil {
return err
}
// start server
if err := s.start(); err != nil {
return err
}
// set health
s.health.SetServingStatus(s.cfg.ID, 1)
// wait for go routines to finish
s.wg.Wait()
s.logger.Warn().Msg(fmt.Sprintf("%s has just exited", s.Name()))
return nil
}
// Stop stops server by sending a message to close the listener via channel
func (s *Server) Stop() {
// set health as not serving
s.health.SetServingStatus(s.cfg.ID, 2)
// close listener
s.close <- true
}
func (s *Server) Health() *healthpb.HealthCheckResponse {
switch s.cfg.Format {
case "grpc":
s.healthGRPC()
default:
s.healthHTTP()
}
hcr, err := s.health.Check(
context.Background(), &healthpb.HealthCheckRequest{Service: s.cfg.ID})
if err != nil {
s.logger.Error().Msg(err.Error())
return &healthpb.HealthCheckResponse{Status: 2}
}
return hcr
}
// Name returns server name
func (s *Server) Name() string {
return s.cfg.Name
}
// Logger returns server logger
func (s *Server) Logger() zerolog.Logger {
return s.logger
}
func (s *Server) setHTTPServer() {
if s.cfg.Mux == nil {
s.cfg.Mux = router.New()
}
// set health check handler
s.cfg.Mux.GET("/_health", router.Wrap(healthHandler))
s.cfg.mu.Lock()
// append logger
s.cfg.Middlewares = append(s.cfg.Middlewares,
loggerMiddleware(s), eidMiddleware(s), serverMiddleware(s),
)
// wrap Middlewares
s.cfg.Mux.WrapperMiddleware(s.cfg.Middlewares...)
s.cfg.mu.Unlock()
// initialize http server
s.httpServer = &http.Server{
// handler to invoke, http.DefaultServeMux if nil
Handler: s.cfg.Mux,
// ReadTimeout is used by the http server to set a maximum duration before
// timing out read of the request. The default timeout is 10 seconds.
ReadTimeout: s.cfg.ReadTimeout,
// WriteTimeout is used by the http server to set a maximum duration before
// timing out write of the response. The default timeout is 10 seconds.
WriteTimeout: s.cfg.WriteTimeout,
TLSConfig: s.cfg.TLSConfig,
}
}
func (s *Server) start() (err error) {
s.logger.Info().Msg(fmt.Sprintf("starting %s %s, listening on %s", s.cfg.Format, s.Name(), s.cfg.Addr))
var ln net.Listener
switch s.cfg.Format {
case "https":
// append strict security header
s.cfg.mu.Lock()
s.cfg.Middlewares = append(s.cfg.Middlewares, strictSecurityHeaderMiddleware())
s.cfg.mu.Unlock()
ln, err = s.listenTLS()
if err != nil {
return err
}
default:
ln, err = s.listen()
if err != nil {
return err
}
}
switch s.cfg.Format {
case "grpc":
s.setGRPCServer()
if err := s.serveGRPC(ln); err != nil {
return err
}
default:
s.setHTTPServer()
if err := s.serve(ln); err != nil {
return err
}
}
// add go routine to WaitGroup
s.wg.Add(1)
go s.waitUntilStop(ln)
return nil
}
// listen based on http.ListenAndServe
// listens on the TCP network address srv.Addr
// If srv.Addr is blank, ":http" is used.
// returns nil or new listener
func (s *Server) listen() (net.Listener, error) {
addr := s.cfg.Addr
if addr == "" {
addr = ":http"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
ln = net.Listener(TCPKeepAliveListener{ln.(*net.TCPListener)})
return ln, nil
}
// listenTLS based on http.ListenAndServeTLS
// listens on the TCP network address srv.Addr
// If srv.Addr is blank, ":https" is used.
// returns nil or new listener
func (s *Server) listenTLS() (net.Listener, error) {
addr := s.cfg.Addr
if addr == "" {
addr = ":https"
}
ln, err := tls.Listen("tcp", addr, s.cfg.TLSConfig)
if err != nil {
return nil, err
}
return ln, nil
}
// serve based on http.ListenAndServe
// calls Serve to handle requests on incoming connections.
// Accepted connections are configured to enable TCP keep-alives.
// serve always returns a non-nil error.
func (s *Server) serve(ln net.Listener) error {
// add go routine to WaitGroup
s.wg.Add(1)
go func(s *Server, ln net.Listener) {
defer s.wg.Done()
if err := s.httpServer.Serve(ln); err != nil {
if err.Error() == errClosing(ln).Error() {
return
}
s.logger.Error().Msg(err.Error())
return
}
}(s, ln)
return nil
}
// errClosing is the currently error raised when we gracefull
// close the listener. If this is the case there is no point to log
func errClosing(ln net.Listener) error {
return fmt.Errorf("accept tcp %v: use of closed network connection", ln.Addr().String())
}
// waitUntilStop waits for close channel
func (s *Server) waitUntilStop(ln net.Listener) {
defer s.wg.Done()
// Waits for call to stop
<-s.close
s.unregister()
switch s.cfg.Format {
case "grpc":
s.grpcServer.GracefulStop()
default:
if err := ln.Close(); err != nil {
s.logger.Error().Msg(err.Error())
}
}
}
// register Server within the service discovery system
func (s *Server) register() error {
if _, ok := s.cfg.Discovery.(discovery.Discovery); ok {
// define service
dse := discovery.Service{
Name: s.cfg.Name,
Address: common.IPaddress(),
Port: s.cfg.Port(),
Tags: []string{s.cfg.ID},
}
// define check
dck := discovery.Check{
Name: fmt.Sprintf("Service '%s' check", s.cfg.Name),
Notes: fmt.Sprintf("Ensure the server is listening on port %s", s.cfg.Addr),
DeregisterCriticalServiceAfter: "10m",
HTTP: fmt.Sprintf("http://%s:9090/_health/server/%s", common.IPaddress(), s.cfg.Name),
Interval: "30s",
Timeout: "1s",
ServiceID: s.cfg.Name,
}
if err := s.cfg.Discovery.Register(discovery.ServicesCfg(dse), discovery.ChecksCfg(dck)); err != nil {
return err
}
}
return nil
}
// unregister Server from the service discovery system
func (s *Server) unregister() error {
if _, ok := s.cfg.Discovery.(discovery.Discovery); ok {
if err := s.cfg.Discovery.Unregister(); err != nil {
return err
}
}
return nil
}
func (s *Server) healthHTTP() {
r, err := http.Get(fmt.Sprintf(`http://localhost:%d/_health`, s.cfg.Port()))
if err != nil {
s.logger.Error().Msg(err.Error())
s.health.SetServingStatus(s.cfg.ID, 2)
return
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
s.logger.Error().Msg(err.Error())
s.health.SetServingStatus(s.cfg.ID, 2)
return
}
defer r.Body.Close()
hcr := &healthpb.HealthCheckResponse{}
if err := json.Unmarshal(b, hcr); err != nil {
s.logger.Error().Msg(err.Error())
s.health.SetServingStatus(s.cfg.ID, 2)
return
}
s.health.SetServingStatus(s.cfg.ID, hcr.Status)
}
func (s *Server) healthGRPC() {
conn, err := grpc.Dial(fmt.Sprintf("localhost:%d", s.cfg.Port()), grpc.WithInsecure())
if err != nil {
s.logger.Error().Msg(err.Error())
s.health.SetServingStatus(s.cfg.ID, 2)
return
}
defer conn.Close()
c := healthpb.NewHealthClient(conn)
hcr, err := c.Check(context.Background(), &healthpb.HealthCheckRequest{Service: s.cfg.ID})
if err != nil {
s.logger.Error().Msg(err.Error())
s.health.SetServingStatus(s.cfg.ID, 2)
return
}
s.health.SetServingStatus(s.cfg.ID, hcr.Status)
}
func (s *Server) setGRPCServer() {
s.cfg.mu.Lock()
// add default interceptors
s.cfg.UnaryServerInterceptors = append(s.cfg.UnaryServerInterceptors,
loggerUnaryServerInterceptor(s),
serverUnaryServerInterceptor(s))
s.cfg.StreamServerInterceptors = append(s.cfg.StreamServerInterceptors,
loggerStreamServerInterceptor(s),
serverStreamServerInterceptor(s))
// initialize grpc server
s.grpcServer = grpc.NewServer(
grpc.UnaryInterceptor(WrapperUnaryServer(s.cfg.UnaryServerInterceptors...)),
grpc.StreamInterceptor(WrapperStreamServer(s.cfg.StreamServerInterceptors...)),
)
s.cfg.mu.Unlock()
// register grpc internal health handlers
healthpb.RegisterHealthServer(s.grpcServer, s.health)
// register grpc handlers
s.cfg.GRPCRegister(s.grpcServer)
}
// serveGRPC serves *grpc.Server
func (s *Server) serveGRPC(ln net.Listener) (err error) {
// add go routine to WaitGroup
s.wg.Add(1)
go func(s *Server, ln net.Listener) {
defer s.wg.Done()
if err := s.grpcServer.Serve(ln); err != nil {
if err.Error() == errClosing(ln).Error() {
return
}
s.logger.Error().Msg(err.Error())
return
}
}(s, ln)
return nil
}