-
Notifications
You must be signed in to change notification settings - Fork 1
/
serve.go
478 lines (410 loc) · 14.1 KB
/
serve.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
// Code generated by protoc-gen-gomeet-service. DO NOT EDIT.
// source: pb/profile.proto
package cmd
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"github.com/auth0/go-jwt-middleware"
"github.com/cockroachdb/cmux"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
"github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/grpc-ecosystem/go-grpc-middleware/auth"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
"github.com/grpc-ecosystem/go-grpc-middleware/recovery"
"github.com/grpc-ecosystem/go-grpc-middleware/tags"
"github.com/grpc-ecosystem/go-grpc-middleware/validator"
"github.com/grpc-ecosystem/go-grpc-prometheus"
nlog "github.com/meatballhat/negroni-logrus"
"github.com/rs/cors"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/urfave/negroni"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"github.com/gomeet-examples/svc-profile/models"
grpc_acl "github.com/gomeet/gomeet/utils/grpc-middlewares/acl"
grpc_cid "github.com/gomeet/gomeet/utils/grpc-middlewares/cid"
)
var (
debugMode bool
serverAddress string
grpcServerAddress string
httpServerAddress string
corsAllowedOrigins string
jwtSecret string
// EXTRA : var
mysqlMigrate bool
mysqlDataSourceName string
// END EXTRA : var
// SUB-SERVICES DEFINITION : var-address
// svc{{SubServiceNamePascalCase}}Address string
// END SUB-SERVICES DEFINITION : var-address
// serveCmd represents the serve command
serveCmd = &cobra.Command{
Use: "serve",
Short: "Launches the svc-profile service webserver",
Run: func(cmd *cobra.Command, args []string) {
serve()
},
}
)
func init() {
RootCmd.AddCommand(serveCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// force debug mode
serveCmd.PersistentFlags().BoolVarP(&debugMode, "debug", "d", false, "Force debug mode")
// address flag (to serve all protocols on a single port)
serveCmd.PersistentFlags().StringVarP(&serverAddress, "address", "a", ":13000", "Multiplexed gRPC/HTTP server address")
// gRPC address flag (to serve gRPC on a separate address)
serveCmd.PersistentFlags().StringVar(&grpcServerAddress, "grpc-address", "", "gRPC server address")
// HTTP/1.1 address flag (to serve HTTP on a separate address)
serveCmd.PersistentFlags().StringVar(&httpServerAddress, "http-address", "", "HTTP server address")
// cors flag
serveCmd.PersistentFlags().StringVarP(&corsAllowedOrigins, "cors", "c", "*", "Cross Origin Resource Sharing AllowedOrigins (string) separed by | ex: http://*gomeet.com|http://*example.com")
// JWT secret signing key
serveCmd.PersistentFlags().StringVarP(&jwtSecret, "jwt-secret", "j", "", "JSON Web Token secret signing key (required for JWT support)")
// CA certificate
serveCmd.PersistentFlags().StringVar(&caCertificate, "ca", "", "X.509 certificate of the Certificate Authority (required for gRPC TLS support)")
// gRPC server certificate
serveCmd.PersistentFlags().StringVar(&serverCertificate, "cert", "", "X.509 certificate of the gRPC server (required for gRPC TLS support)")
// gRPC server private key
serveCmd.PersistentFlags().StringVar(&serverPrivateKey, "key", "", "RSA private key of the gRPC server (required for gRPC TLS support)")
// EXTRA : flags
// Mysql data migration on start
serveCmd.PersistentFlags().BoolVar(&mysqlMigrate, "mysql-migrate", false, "Mysql data migration on start")
// Mysql data source name: https://github.com/go-sql-driver/mysql#dsn-data-source-name
serveCmd.PersistentFlags().StringVar(&mysqlDataSourceName, "mysql-dsn", "", "Mysql connection informations (USERNAME:PASSWORD@tcp(HOSTNAME:3306)/DBNAME)")
// END EXTRA : flags
// SUB-SERVICES DEFINITION : flag-address
// // {{SubServiceNamePascalCase}} service address
// serveCmd.PersistentFlags().StringVar(&svc{{SubServiceNamePascalCase}}Address, "svc-{{SubServiceNameKebabCase}}-address", "", "{{SubServiceNamePascalCase}} service address (host:port)")
// END SUB-SERVICES DEFINITION : flag-address
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// serveCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func serve() {
if strings.HasSuffix(svc.Version, "+dev") || debugMode {
log.SetLevel(log.DebugLevel)
log.WithFields(log.Fields{
"Name": svc.Name,
"Version": svc.Version,
"FullName": svcName,
}).Debug("set log debug level")
}
log.Infof("%s version %s - %s", svc.Name, svc.Version, svcName)
// Mysql data migration on start
if mysqlMigrate {
if mysqlDataSourceName == "" {
log.Errorf("The --mysql-dsn flag is required for automatic schema migration")
os.Exit(1)
}
err := models.MigrateSchema(mysqlDataSourceName)
if err != nil {
log.Errorf("Database schema migration failure: %v\n", err)
os.Exit(1)
}
}
if grpcServerAddress != "" && httpServerAddress != "" {
serveOnMultipleAddresses(grpcServerAddress, httpServerAddress)
} else {
serveOnSingleAddress(serverAddress)
}
}
func recoverFromPanic(p interface{}) error {
log.Infof("recovering from panic: %s", p)
return fmt.Errorf("panic in gRPC procedure: %v", p)
}
func grpcServer(
caCert string,
serverCert string,
serverKey string,
jwtKey string,
// EXTRA : param
mysqlDSN string,
// END EXTRA : param
// SUB-SERVICES DEFINITION : param-address
// svc{{SubServiceNamePascalCase}}Address string,
// END SUB-SERVICES DEFINITION : param-address
) *grpc.Server {
var grpcS *grpc.Server
//middlewares definition
recoveryOpt := grpc_recovery.WithRecoveryHandler(recoverFromPanic)
logrusEntry := log.NewEntry(log.StandardLogger())
// stream middlewares
sMdl := grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(
grpc_prometheus.StreamServerInterceptor,
grpc_cid.StreamServerInterceptor(false),
grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_logrus.StreamServerInterceptor(logrusEntry),
grpc_auth.StreamServerInterceptor(nil),
grpc_validator.StreamServerInterceptor(),
grpc_acl.StreamServerInterceptor(nil),
grpc_recovery.StreamServerInterceptor(recoveryOpt),
))
// unary middlewares
uMdl := grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
grpc_prometheus.UnaryServerInterceptor,
grpc_cid.UnaryServerInterceptor(false),
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_logrus.UnaryServerInterceptor(logrusEntry),
grpc_auth.UnaryServerInterceptor(nil),
grpc_validator.UnaryServerInterceptor(),
grpc_acl.UnaryServerInterceptor(nil),
grpc_recovery.UnaryServerInterceptor(recoveryOpt),
))
if caCert != "" && serverCert != "" && serverKey != "" {
// load the server's key pair
serverKeyPair, err := tls.LoadX509KeyPair(serverCert, serverKey)
if err != nil {
log.Fatalf("failed to load gateway key pair: %v", err)
}
// create a certificate pool from the CA
certPool := x509.NewCertPool()
ca, err := ioutil.ReadFile(caCert)
if err != nil {
log.Fatalf("failed to read CA certificate: %v", err)
}
if ok := certPool.AppendCertsFromPEM(ca); !ok {
log.Fatalf("failed to build certificate pool")
}
// set up the TLS credentials
serverCredentials := credentials.NewTLS(&tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{serverKeyPair},
ClientCAs: certPool,
})
grpcS = grpc.NewServer(grpc.Creds(serverCredentials), sMdl, uMdl)
} else {
grpcS = grpc.NewServer(sMdl, uMdl)
}
svc.RegisterGRPCServices(
grpcS,
jwtKey,
caCert,
serverCert,
serverKey,
// EXTRA : register
mysqlDSN,
// END EXTRA : register
// SUB-SERVICES DEFINITION : register-address
// svc{{SubServiceNamePascalCase}}Address,
// END SUB-SERVICES DEFINITION : register-address
)
grpc_prometheus.Register(grpcS)
return grpcS
}
func httpServer(httpServerAddr string, grpcServerAddr string, ctx context.Context, caCert string, gatewayCert string, gatewayKey string, jwtKey string) *http.Server {
// create the HTTP request router
h := mux.NewRouter()
// register the gRPC gateway
var opts []grpc.DialOption
if caCert != "" && gatewayCert != "" && gatewayKey != "" {
// load the gateway's key pair
gatewayKeyPair, err := tls.LoadX509KeyPair(gatewayCert, gatewayKey)
if err != nil {
log.Fatalf("failed to load client key pair: %v", err)
}
// create a certificate pool from the CA
certPool := x509.NewCertPool()
ca, err := ioutil.ReadFile(caCert)
if err != nil {
log.Fatalf("failed to read CA certificate: %v", err)
}
if ok := certPool.AppendCertsFromPEM(ca); !ok {
log.Fatalf("failed to build certificate pool")
}
// set up the TLS credentials
serverHost, _, err := net.SplitHostPort(grpcServerAddr)
if err != nil {
log.Fatalf("failed to parse server hostname in %s: %v", grpcServerAddr, err)
}
if serverHost == "" {
serverHost = "localhost"
}
gatewayCredentials := credentials.NewTLS(&tls.Config{
ServerName: serverHost,
Certificates: []tls.Certificate{gatewayKeyPair},
RootCAs: certPool,
})
opts = []grpc.DialOption{grpc.WithTransportCredentials(gatewayCredentials)}
} else {
opts = []grpc.DialOption{grpc.WithInsecure()}
}
// register other HTTP handlers
if jwtKey != "" {
// setup the JWT authentication middleware
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(jwtKey), nil
},
SigningMethod: jwt.SigningMethodHS256,
})
svc.RegisterHTTPServices(ctx, h, grpcServerAddr, opts, jwtMiddleware)
} else {
svc.RegisterHTTPServices(ctx, h, grpcServerAddr, opts, nil)
}
// setup the negroni middleware for request logging
n := negroni.New(
// no crash with 500
negroni.NewRecovery(),
// global logrus logger
nlog.NewMiddlewareFromLogger(log.StandardLogger(), "svc-profile"),
)
// CORS support
if corsAllowedOrigins != "" {
log.Infof("HTTP with Cross Origin Resource Sharing, AllowedOrigins: %s", corsAllowedOrigins)
n.Use(cors.New(cors.Options{
AllowedOrigins: strings.Split(corsAllowedOrigins, "|"),
}))
}
n.UseHandler(h)
return &http.Server{Handler: n}
}
func serveOnMultipleAddresses(grpcAddr string, httpAddr string) {
// create the gRPC server
grpcS := grpcServer(
caCertificate,
serverCertificate,
serverPrivateKey,
jwtSecret,
// EXTRA : register
mysqlDataSourceName,
// END EXTRA : register
// SUB-SERVICES DEFINITION : register-address
// svc{{SubServiceNamePascalCase}}Address,
// END SUB-SERVICES DEFINITION : register-address
)
// create the gRPC listener
grpcL, err := net.Listen("tcp", grpcAddr)
if err != nil {
log.Fatal(err)
}
// create the HTTP/1.1 server (we reuse the gRPC server's key pair for the gRPC gateway client)
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
httpS := httpServer(httpAddr, grpcAddr, ctx, caCertificate, serverCertificate, serverPrivateKey, jwtSecret)
// create the HTTP listener
httpL, err := net.Listen("tcp", httpAddr)
if err != nil {
log.Fatal(err)
}
// HTTPS support
if caCertificate != "" && serverCertificate != "" && serverPrivateKey != "" {
// load the server's key pair
serverKeyPair, err := tls.LoadX509KeyPair(serverCertificate, serverPrivateKey)
if err != nil {
log.Fatalf("failed to load HTTPS server key pair: %v", err)
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{serverKeyPair},
ClientAuth: tls.NoClientCert,
}
httpsL := tls.NewListener(httpL, tlsConfig)
httpL = httpsL
}
// collect on this channel the exits of each protocol's .Serve() call
eps := make(chan error, 2)
// start the listeners for each protocol
go func() { eps <- grpcS.Serve(grpcL) }()
go func() { eps <- httpS.Serve(httpL) }()
grpcSecurity := "insecure"
if caCertificate != "" && serverCertificate != "" && serverPrivateKey != "" {
grpcSecurity = "secure"
}
jwtSupport := "disabled"
if jwtSecret != "" {
jwtSupport = "enabled"
}
log.Infof("serving %s gRPC on %s and %s HTTP/1.1 on %s (JWT %s)", grpcSecurity, grpcAddr, grpcSecurity, httpAddr, jwtSupport)
// handle listener errors
failed := false
i := 0
for err := range eps {
if err != nil {
log.Errorf("protocol serve error: %v", err)
failed = true
}
i++
if i == cap(eps) {
close(eps)
break
}
}
if failed {
os.Exit(1)
}
}
func serveOnSingleAddress(addr string) {
// listen on the specified address
l, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal(err)
}
// create the cmux object that will multiplex 2 protocols on the same port
m := cmux.New(l)
// match HTTP/1.1 requests and gRPC requests
httpL := m.Match(cmux.HTTP1())
grpcL := m.Match(cmux.Any())
// create the gRPC server
grpcS := grpcServer(
caCertificate,
serverCertificate,
serverPrivateKey,
jwtSecret,
// EXTRA : register
mysqlDataSourceName,
// END EXTRA : register
// SUB-SERVICES DEFINITION : register-address
// svc{{SubServiceNamePascalCase}}Address,
// END SUB-SERVICES DEFINITION : register-address
)
// create the HTTP/1.1 server (we reuse the gRPC server's key pair for the gRPC gateway client)
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
httpS := httpServer(addr, addr, ctx, caCertificate, serverCertificate, serverPrivateKey, jwtSecret)
// collect on this channel the exits of each protocol's .Serve() call
eps := make(chan error, 2)
// start the listeners for each protocol
go func() { eps <- grpcS.Serve(grpcL) }()
go func() { eps <- httpS.Serve(httpL) }()
grpcSecurity := "insecure"
if caCertificate != "" && serverCertificate != "" && serverPrivateKey != "" {
grpcSecurity = "secure"
}
jwtSupport := "disabled"
if jwtSecret != "" {
jwtSupport = "enabled"
}
log.Infof("serving on %s (multiplexed, %s gRPC, JWT %s)", addr, grpcSecurity, jwtSupport)
err = m.Serve()
// the rest of the code handles exit errors of the muxes
failed := false
i := 0
for err := range eps {
if err != nil {
log.Errorf("protocol serve error: %v", err)
failed = true
}
i++
if i == cap(eps) {
close(eps)
break
}
}
if failed {
os.Exit(1)
}
}