forked from gcash/bchd
-
Notifications
You must be signed in to change notification settings - Fork 2
/
grpcserver.go
179 lines (149 loc) · 4.87 KB
/
grpcserver.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
package main
import (
"context"
"errors"
"net"
"net/http"
"strings"
"time"
"github.com/gcash/bchd/bchrpc"
"github.com/gorilla/mux"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"github.com/improbable-eng/grpc-web/go/grpcweb"
"github.com/prometheus/client_golang/prometheus/promhttp"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
)
// AuthenticationTokenKey is the key used in the context to authenticate clients.
// If this is set to anything other than "" in the config, then the server expects
// the client to set a key value in the context metadata to 'AuthenticationToken: cfg.AuthToken'
const AuthenticationTokenKey = "AuthenticationToken"
var prometheusEnabled = false
func newGrpcServer(netAddrs []net.Addr, rpcCfg *bchrpc.GrpcServerConfig, svr *server) (*bchrpc.GrpcServer, error) {
for _, addr := range netAddrs {
rpcCfg.NetMgr = svr
opts := []grpc.ServerOption{grpc.StreamInterceptor(interceptStreaming), grpc.UnaryInterceptor(interceptUnary)}
creds, err := credentials.NewServerTLSFromFile(cfg.RPCCert, cfg.RPCKey)
if err != nil {
return nil, err
}
opts = append(opts, grpc.Creds(creds))
server := grpc.NewServer(opts...)
allowAllOrigins := grpcweb.WithOriginFunc(func(origin string) bool {
return true
})
wrappedGrpc := grpcweb.WrapServer(server, allowAllOrigins)
rpcCfg.Server = server
handler := func(resp http.ResponseWriter, req *http.Request) {
if wrappedGrpc.IsGrpcWebRequest(req) || wrappedGrpc.IsAcceptableGrpcCorsRequest(req) {
wrappedGrpc.ServeHTTP(resp, req)
} else {
server.ServeHTTP(resp, req)
}
}
httpServer := &http.Server{
Addr: addr.String(),
Handler: http.HandlerFunc(handler),
}
rpcCfg.HTTPServer = httpServer
gRPCServer := bchrpc.NewGrpcServer(rpcCfg)
grpcLog.Infof("Experimental gRPC server listening on %s", addr)
go func() {
if err := httpServer.ListenAndServeTLS(cfg.RPCCert, cfg.RPCKey); err != nil {
grpcLog.Tracef("Finished serving expimental gRPC: %v", err)
}
}()
if len(cfg.PrometheusListen) != 0 {
// init Prometheus metrics
grpc_prometheus.EnableHandlingTimeHistogram()
grpc_prometheus.Register(server)
router := mux.NewRouter()
router.Handle("/metrics", promhttp.Handler())
prometheusHTTPServer := &http.Server{
Addr: cfg.PrometheusListen,
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
prometheusEnabled = true
go func() {
if err := prometheusHTTPServer.ListenAndServeTLS(cfg.RPCCert, cfg.RPCKey); err != nil {
grpcLog.Tracef("Finished serving Prometheus metrics %v", err)
}
}()
}
return gRPCServer, nil
}
return nil, nil
}
// serviceName returns the package.service segment from the full gRPC method
// name `/package.service/method`.
func serviceName(method string) string {
// Slice off first /
method = method[1:]
// Keep everything before the next /
return method[:strings.IndexRune(method, '/')]
}
func interceptStreaming(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
// collect prometheus metrics before auth
if prometheusEnabled {
if err := grpc_prometheus.StreamServerInterceptor(srv, ss, info, handler); err != nil {
return err
}
}
p, ok := peer.FromContext(ss.Context())
if ok {
grpcLog.Infof("Streaming method %s invoked by %s", info.FullMethod,
p.Addr.String())
}
err := validateAuthenticationToken(ss.Context())
if err != nil {
return err
}
err = bchrpc.ServiceReady(serviceName(info.FullMethod))
if err != nil {
return err
}
err = handler(srv, ss)
if err != nil && ok {
grpcLog.Errorf("Streaming method %s invoked by %s errored: %v",
info.FullMethod, p.Addr.String(), err)
}
return err
}
func interceptUnary(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
if prometheusEnabled {
resp, err = grpc_prometheus.UnaryServerInterceptor(ctx, req, info, handler)
if err != nil {
return resp, err
}
}
p, ok := peer.FromContext(ctx)
if ok {
grpcLog.Infof("Unary method %s invoked by %s", info.FullMethod,
p.Addr.String())
}
err = validateAuthenticationToken(ctx)
if err != nil {
return nil, err
}
err = bchrpc.ServiceReady(serviceName(info.FullMethod))
if err != nil {
return nil, err
}
resp, err = handler(ctx, req)
if err != nil && ok {
grpcLog.Errorf("Unary method %s invoked by %s errored: %v",
info.FullMethod, p.Addr.String(), err)
}
return resp, err
}
func validateAuthenticationToken(ctx context.Context) error {
md, ok := metadata.FromIncomingContext(ctx)
if cfg.GrpcAuthToken != "" && (!ok || len(md.Get(AuthenticationTokenKey)) == 0 || md.Get(AuthenticationTokenKey)[0] != cfg.GrpcAuthToken) {
return errors.New("invalid authentication token")
}
return nil
}