-
Notifications
You must be signed in to change notification settings - Fork 1
/
service.go
337 lines (264 loc) · 6.76 KB
/
service.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
package service
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io/ioutil"
"math"
"net"
"net/http"
"os"
"strconv"
"strings"
"github.com/go-chi/chi"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
)
// Defaults
var (
defaultPort = 8000
)
type Service struct {
HTTP *http.ServeMux
Router *chi.Mux
CertPool *x509.CertPool
PublicCert []byte
PrivateKey []byte
port int
grpc *grpc.Server
server *http.Server
gatewayMux *runtime.ServeMux
grpcPort int // to serve grpc on a separate port
maxReceiveSize int
maxSendSize int
insecureSkipVerify bool
disableTLSCerts bool
httpHandlers []httpHandler
gatewayHandlers []func(context.Context, *runtime.ServeMux, *grpc.ClientConn) error
grpcServerOptions []grpc.ServerOption
unaryInterceptors []grpc.UnaryServerInterceptor
streamInterceptors []grpc.StreamServerInterceptor
debug bool
}
type Option func(*Service) error
func New(opts ...Option) (*Service, error) {
s := Service{
port: envInt(EnvPort),
HTTP: http.NewServeMux(),
Router: chi.NewMux(),
CertPool: x509.NewCertPool(),
gatewayMux: runtime.NewServeMux(),
gatewayHandlers: []func(context.Context, *runtime.ServeMux, *grpc.ClientConn) error{},
httpHandlers: []httpHandler{},
grpcServerOptions: []grpc.ServerOption{},
unaryInterceptors: []grpc.UnaryServerInterceptor{},
streamInterceptors: []grpc.StreamServerInterceptor{},
maxReceiveSize: math.MaxInt32,
maxSendSize: math.MaxInt32,
grpcPort: envInt(EnvGRPCPort),
insecureSkipVerify: envBool(EnvInsecureVerifySkip),
disableTLSCerts: envBool(EnvTLSDisabled),
}
if envBool(EnvDebug) {
opts = append(opts, WithDebug())
}
err := s.WithOptions(opts...)
if err != nil {
return nil, err
}
return &s, nil
}
func (s *Service) Serve(ctx context.Context) error {
if s.debug {
s.PrintDebug()
log := grpclog.NewLoggerV2(os.Stdout, os.Stdout, ioutil.Discard)
grpclog.SetLoggerV2(log)
}
if s.port < 1 || s.port > 65535 {
fmt.Printf("Invalid Port %d falling back to default port %d\n", s.port, defaultPort)
s.port = defaultPort
}
if s.grpcPort > 65535 {
fmt.Printf("Invalid GRPC Port %d falling back to primary port %d\n", s.grpcPort, s.port)
s.grpcPort = 0
}
if s.grpc == nil {
return ErrServeGRPCNotYetDefined
}
if s.disableTLSCerts && s.grpcPort == 0 {
return ErrDisableTLSCertsMissingGRPCPort
}
cert, err := s.GetCertificate()
if err != nil {
return err
}
tlsConfig := tls.Config{
NextProtos: []string{"h2"},
InsecureSkipVerify: s.insecureSkipVerify,
}
grpcPort := s.port
if s.grpcPort > 0 {
grpcPort = s.grpcPort
}
// grpcAddr := fmt.Sprintf(":%d", grpcPort)
conn, err := net.Listen("tcp", fmt.Sprintf(":%d", grpcPort))
if err != nil {
return err
}
// Serving HTTP/1 and gRPC on separate ports
if s.grpcPort > 0 && s.grpcPort != s.port {
go func() {
if s.disableTLSCerts {
fmt.Printf("Serving gRPC (No TLS) on Port: %d\n", s.grpcPort)
err := s.grpc.Serve(conn)
fmt.Println("error serving grpc: ", err.Error())
return
}
fmt.Printf("Serving gRPC on Port: %d\n", s.grpcPort)
err := s.grpc.Serve(tls.NewListener(conn, &tlsConfig))
fmt.Println("error serving grpc: ", err.Error())
}()
}
if s.gatewayHandlers != nil {
opts := []grpc.DialOption{
grpc.WithTransportCredentials(
credentials.NewTLS(&tls.Config{
InsecureSkipVerify: true, // talk to grpc within the service at localhost/127.0.0.1
}),
),
}
if s.disableTLSCerts {
opts = []grpc.DialOption{
// grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(s.CertPool, "")),
grpc.WithInsecure(),
grpc.WithBlock(),
}
}
clientConn, err := grpc.DialContext(
context.Background(),
fmt.Sprintf("dns:///127.0.0.1:%d", grpcPort),
opts...,
)
if err != nil {
return err
}
for i := range s.gatewayHandlers {
err := s.gatewayHandlers[i](
ctx,
s.gatewayMux,
clientConn,
)
if err != nil {
return err
}
}
s.HTTP.Handle("/", s.gatewayMux)
}
s.Router.NotFound(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s.HTTP.ServeHTTP(w, r)
}))
s.cors()
s.server = &http.Server{
Addr: strconv.Itoa(s.port),
Handler: handlerFunc(s.grpc, s.chainHandlers(s.Router)),
}
tlsConfig.Certificates = []tls.Certificate{cert}
// tlsConfig.BuildNameToCertificate()
if s.grpcPort > 0 && s.grpcPort != s.port {
c, err := net.Listen("tcp", fmt.Sprintf(":%d", s.port))
if err != nil {
return err
}
if s.disableTLSCerts {
fmt.Printf("Serving HTTP on Port: %d\n", s.port)
return s.server.Serve(c)
}
fmt.Printf("Serving HTTPS on Port: %d\n", s.port)
return s.server.Serve(tls.NewListener(c, &tlsConfig))
}
fmt.Printf("Serving HTTPS and gRPC on Port: %d\n", s.port)
return s.server.Serve(tls.NewListener(conn, &tlsConfig))
}
// Shutdown attempts to gracefully shutdown server given a context timeout
func (s *Service) Shutdown(ctx context.Context) error {
defer s.grpc.GracefulStop()
if s.server == nil {
return errors.New("service server is nil")
}
err := s.server.Shutdown(ctx)
if err != nil {
return err
}
<-ctx.Done()
s.grpc.Stop()
return nil
}
func (s *Service) WithOptions(opts ...Option) error {
for _, opt := range opts {
if err := opt(s); err != nil {
return err
}
}
return nil
}
func WithPort(port int) func(*Service) error {
return func(s *Service) error {
if port <= 0 {
return fmt.Errorf(ErrInvalidPort.Error(), port)
}
s.port = port
return nil
}
}
func WithDebug() func(*Service) error {
return func(s *Service) error {
s.debug = true
return nil
}
}
func (s *Service) PrintDebug() {
fmt.Printf(`
=== Service Info =====================
Port : %d
Gateway Handlers : %d
HTTP Handlers : %d
--------------------------------------
--- GRPC -----------------------------
Port : %d
Service Options : %d
Unary Interceptors : %d
Stream Interceptors : %d
Max Receive Size : %d
Max Send Size : %d
--------------------------------------
--- TLS ------------------------------
Insecure Verify Skip : %t
Disable TLS : %t
======================================
`,
s.port,
len(s.gatewayHandlers),
len(s.httpHandlers),
s.grpcPort,
len(s.grpcServerOptions),
len(s.unaryInterceptors),
len(s.streamInterceptors),
s.maxReceiveSize,
s.maxSendSize,
s.insecureSkipVerify,
s.disableTLSCerts,
)
}
func handlerFunc(grpcServer *grpc.Server, httpHandler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
grpcServer.ServeHTTP(w, r)
} else {
httpHandler.ServeHTTP(w, r)
}
})
}