-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
155 lines (132 loc) · 4.44 KB
/
grpc.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
/**
* Copyright 2022-present Coinbase Global, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"time"
"github.com/coinbase-samples/ib-usermgr-go/auth"
"github.com/coinbase-samples/ib-usermgr-go/config"
"github.com/coinbase-samples/ib-usermgr-go/handlers"
"github.com/coinbase-samples/ib-usermgr-go/log"
v1 "github.com/coinbase-samples/ib-usermgr-go/pkg/pbs/profile/v1"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_logrus "github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
grpc_validator "github.com/grpc-ecosystem/go-grpc-middleware/validator"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/reflection"
)
func gRPCListen(app config.AppConfig, aw auth.Middleware) {
// if local expose both grpc and http endpoints
activePort := app.Port
if app.IsLocalEnv() {
activePort = app.GrpcPort
}
//setup conn
lis, err := net.Listen("tcp", fmt.Sprintf(":%s", activePort))
if err != nil {
log.Fatalf("Failed to listen for gRPC: %v", err)
}
s := grpc.NewServer(setupGrpcOptions(app, aw)...)
//register grpc handlers
v1.RegisterProfileServiceServer(s, &handlers.ProfileServer{})
registerHealth(s)
reflection.Register(s)
log.Infof("gRPC Server starting on port %s", activePort)
go func() {
if err := s.Serve(lis); err != nil {
log.Fatalf("Failed to listen for gRPC: %v", err)
}
}()
//if local, start http as an interface
var gwServer *http.Server
if app.IsLocalEnv() {
gwServer, err = setupHttp(app, s)
if err != nil {
log.Errorf("issues setting up http server: %v", err)
}
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
if gwServer != nil {
gwServer.Shutdown(ctx)
}
}
func registerHealth(s *grpc.Server) {
healthServer := health.NewServer()
healthServer.SetServingStatus("grpc.health.v1.Health", grpc_health_v1.HealthCheckResponse_SERVING)
grpc_health_v1.RegisterHealthServer(s, healthServer)
}
func setupGrpcOptions(app config.AppConfig, aw auth.Middleware) []grpc.ServerOption {
// Logrus entry is used, allowing pre-definition of certain fields by the user.
// See example setup here https://github.com/grpc-ecosystem/go-grpc-middleware/blob/master/logging/logrus/examples_test.go
opts := []grpc_logrus.Option{
grpc_logrus.WithDurationField(func(duration time.Duration) (key string, value interface{}) {
return "grpc.time_ns", duration.Nanoseconds()
}),
grpc_logrus.WithDecider(func(fullMethodName string, err error) bool {
// will not log gRPC calls if it was a call to healthcheck and no error was raised
if err == nil && fullMethodName == "/grpc.health.v1.Health/Check" {
return false
}
// by default everything will be logged
return true
}),
}
grpcOptions := []grpc.ServerOption{
grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
grpc_ctxtags.UnaryServerInterceptor(),
grpc_logrus.UnaryServerInterceptor(log.NewEntry().GetUnderneath(), opts...),
aw.InterceptorNew(),
grpc_validator.UnaryServerInterceptor(),
grpc_recovery.UnaryServerInterceptor(),
)),
}
if !app.IsLocalEnv() {
// load tls for grpc
tlsCredentials, err := loadCredentials()
if err != nil {
log.Fatalf("Cannot load TLS credentials: %v", err)
}
grpcOptions = append(grpcOptions, grpc.Creds(tlsCredentials))
}
return grpcOptions
}
func loadCredentials() (credentials.TransportCredentials, error) {
cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
if err != nil {
return nil, err
}
return credentials.NewTLS(
&tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.NoClientCert,
},
), nil
}