forked from infobloxopen/atlas-app-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
290 lines (250 loc) · 7.33 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
package server
import (
"context"
"net"
"net/http"
"sync"
"time"
"errors"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/infobloxopen/atlas-app-toolkit/gateway"
"github.com/infobloxopen/atlas-app-toolkit/health"
"google.golang.org/grpc"
)
var (
// ErrInitializeTimeout is returned when an InitializerFunc takes too long to finish during Server.Serve
ErrInitializeTimeout = errors.New("initialization timed out")
// DefaultInitializerTimeout is the reasonable default amount of time one would expect initialization to take in the
// worst case
DefaultInitializerTimeout = time.Minute
)
// Server is a wrapper struct that will allow you to stand up your GPRC server, API Gateway and health checks within
// the same struct. The recommended way to initialize this is with the NewServer function.
type Server struct {
initializers []InitializerFunc
initializeTimeout time.Duration
registrars []func(mux *http.ServeMux) error
middlewares []Middleware
// GRPCServer will be started whenever this is served
GRPCServer *grpc.Server
// HTTPServer will be started whenever this is served
HTTPServer *http.Server
isAutomaticStop bool
}
//Middleware wrapper
type Middleware func(handler http.Handler) http.Handler
// Option is a functional option for creating a Server
type Option func(*Server) error
// InitializerFunc is a handler that can be passed into WithInitializer to be executed prior to serving
type InitializerFunc func(context.Context) error
// NewServer creates a Server from the given options. All options are processed in the order they are declared.
func NewServer(opts ...Option) (*Server, error) {
s := &Server{
initializeTimeout: DefaultInitializerTimeout,
HTTPServer: &http.Server{},
registrars: []func(mux *http.ServeMux) error{},
isAutomaticStop: true,
}
for _, opt := range opts {
if err := opt(s); err != nil {
return nil, err
}
}
mux := http.NewServeMux()
for _, register := range s.registrars {
if err := register(mux); err != nil {
return nil, err
}
}
s.HTTPServer.Handler = mux
// Revert user input middlewares
for i, j := 0, len(s.middlewares)-1; i < j; i, j = i+1, j-1 {
s.middlewares[i], s.middlewares[j] = s.middlewares[j], s.middlewares[i]
}
for _, m := range s.middlewares {
s.HTTPServer.Handler = m(s.HTTPServer.Handler)
}
return s, nil
}
// WithInitializerTimeout set the duration initialization will wait before halting and returning an error
func WithInitializerTimeout(timeout time.Duration) Option {
return func(s *Server) error {
s.initializeTimeout = timeout
return nil
}
}
// WithInitializer adds an initialization function that will get called prior to serving.
func WithInitializer(initializerFunc InitializerFunc) Option {
return func(s *Server) error {
s.initializers = append(s.initializers, initializerFunc)
return nil
}
}
// WithGrpcServer adds the given GRPC server to this server. There can only be one GRPC server within a given instance,
// so multiple calls with this option will overwrite the previous ones.
func WithGrpcServer(grpcServer *grpc.Server) Option {
return func(s *Server) error {
s.GRPCServer = grpcServer
return nil
}
}
// WithHandler registers the given http handler to this server by registering the pattern at the root of the http server
func WithHandler(pattern string, handler http.Handler) Option {
return func(s *Server) error {
s.registrars = append(s.registrars, func(mux *http.ServeMux) error {
mux.Handle(pattern, handler)
return nil
})
return nil
}
}
// WithHealthChecks registers the given health checker with this server by registering its endpoints at the root of the
// http server.
func WithHealthChecks(checker health.Checker) Option {
return func(s *Server) error {
s.registrars = append(s.registrars, func(mux *http.ServeMux) error {
checker.RegisterHandler(mux)
return nil
})
return nil
}
}
// WithGateway registers the given gateway options with this server
func WithGateway(options ...gateway.Option) Option {
return func(s *Server) error {
s.registrars = append(s.registrars, func(mux *http.ServeMux) error {
_, err := gateway.NewGateway(append(options,
gateway.WithGatewayOptions(
runtime.WithIncomingHeaderMatcher(
gateway.AtlasDefaultHeaderMatcher())),
gateway.WithMux(mux))...)
return err
})
return nil
}
}
// WithMiddlewares add opportunity to add different middleware
func WithMiddlewares(middleware ...Middleware) Option {
return func(s *Server) error {
s.middlewares = append(s.middlewares, middleware...)
return nil
}
}
func WithAutomaticStop(isAutomaticStop bool) Option {
return func(s *Server) error {
s.isAutomaticStop = isAutomaticStop
return nil
}
}
// Serve invokes all initializers then serves on the given listeners.
//
// If a listener is left blank, then that particular part will not be served.
//
// If a listener is specified for a part that doesn't have a corresponding server, then an error will be returned. This
// can happen, for instance, whenever a gRPC listener is provided but no gRPC server was set or no option was passed
// into NewServer.
//
// If both listeners are nil, then an error is returned
func (s *Server) Serve(grpcL, httpL net.Listener) error {
if grpcL == nil && httpL == nil {
return errors.New("both grpcL and httpL are nil")
}
if err := s.initialize(); err != nil {
return err
}
errC := make(chan error)
if httpL != nil {
if s.HTTPServer == nil {
return errors.New("httpL is specified, but no HTTPServer is provided")
}
go func() { errC <- s.HTTPServer.Serve(httpL) }()
} else {
s.HTTPServer = nil
}
if grpcL != nil {
if s.GRPCServer == nil {
return errors.New("grpcL is specified, but no GRPCServer is provided")
}
go func() { errC <- s.GRPCServer.Serve(grpcL) }()
} else {
s.GRPCServer = nil
}
defer func() {
if s.isAutomaticStop {
s.Stop()
}
}()
return <-errC
}
// Stop immediately terminates the grpc and http servers, immediately closing their active listeners
func (s *Server) Stop() error {
return s.shutdown(context.Background(), false)
}
func (s *Server) GracefulShutdown(ctx context.Context) error {
return s.shutdown(ctx, true)
}
func (s Server) shutdown(ctx context.Context, isGraceful bool) error {
wg := sync.WaitGroup{}
wg.Add(2)
doneC := make(chan bool)
errC := make(chan error)
go func() {
defer wg.Done()
if s.GRPCServer != nil {
if isGraceful {
s.GRPCServer.GracefulStop()
} else {
s.GRPCServer.Stop()
}
}
}()
go func() {
defer wg.Done()
if s.HTTPServer != nil {
if isGraceful {
if err := s.HTTPServer.Shutdown(ctx); err != nil {
errC <- err
}
} else {
if err := s.HTTPServer.Close(); err != nil {
errC <- err
}
}
}
}()
go func() {
wg.Wait()
doneC <- true
}()
select {
case err := <-errC:
return err
case <-doneC:
return nil
}
}
func (s Server) initialize() error {
ctx, cancel := context.WithTimeout(context.Background(), s.initializeTimeout)
defer cancel()
errC := make(chan error)
wg := sync.WaitGroup{}
wg.Add(len(s.initializers))
go func() {
wg.Wait()
errC <- nil
}()
for _, initFunc := range s.initializers {
go func(init InitializerFunc) {
defer wg.Done()
if err := init(ctx); err != nil {
errC <- err
}
}(initFunc)
}
select {
case err := <-errC:
return err
case <-time.After(s.initializeTimeout):
return ErrInitializeTimeout
}
}