-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
209 lines (172 loc) · 5.53 KB
/
Copy pathserver.go
File metadata and controls
209 lines (172 loc) · 5.53 KB
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
package grpc
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"time"
"github.com/roadrunner-server/errors"
"github.com/roadrunner-plugin/grpc/v5/api"
"github.com/roadrunner-plugin/grpc/v5/parser"
"github.com/roadrunner-plugin/grpc/v5/proxy"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/reflection"
"google.golang.org/grpc/status"
)
func (p *Plugin) createGRPCserver(interceptors map[string]api.Interceptor) (*grpc.Server, error) {
const op = errors.Op("grpc_plugin_create_server")
opts, err := p.serverOptions()
if err != nil {
return nil, errors.E(op, err)
}
unaryInterceptors := []grpc.UnaryServerInterceptor{
grpc.UnaryServerInterceptor(p.interceptor),
}
for _, interceptor := range interceptors {
unaryInterceptors = append(
unaryInterceptors,
interceptor.UnaryServerInterceptor(),
)
}
opts = append(
opts,
grpc.ChainUnaryInterceptor(
unaryInterceptors...,
),
)
opts = append(opts, grpc.StatsHandler(otelgrpc.NewServerHandler(otelgrpc.WithTracerProvider(p.tracer), otelgrpc.WithPropagators(p.prop))))
server := grpc.NewServer(opts...)
// Track registered services to avoid duplicates
registeredServices := make(map[string]bool)
for i := range p.config.Proto {
if p.config.Proto[i] == "" {
continue
}
services, errP := parser.FileNoImports(p.config.Proto[i])
if errP != nil {
return nil, errP
}
for _, service := range services {
fullServiceName := fmt.Sprintf("%s.%s", service.Package, service.Name)
if registeredServices[fullServiceName] {
p.log.Debug("service already registered, skipping",
zap.String("service", fullServiceName))
continue
}
px := proxy.NewProxy(
fullServiceName,
p.config.Proto[i],
p.log.Named(service.Name),
p.gPool,
p.mu,
p.prop,
)
for _, m := range service.Methods {
px.RegisterMethod(m.Name)
}
server.RegisterService(px.ServiceDesc(), px)
registeredServices[fullServiceName] = true
p.proxyList = append(p.proxyList, px)
}
}
if p.config.EnableReflection() {
// Компилируем proto файлы на лету для reflection
if err := p.buildAndRegisterDescriptors(); err != nil {
p.log.Warn("failed to build descriptors for reflection", zap.Error(err))
}
reflection.Register(server)
p.log.Info("grpc reflection enabled")
}
return server, nil
}
func (p *Plugin) interceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
start := time.Now()
p.queueSize.Inc()
resp, err := handler(ctx, req)
s, ok := status.FromError(err)
var statusCode codes.Code
switch ok {
case true:
statusCode = s.Code()
case false:
statusCode = status.New(codes.Unknown, err.Error()).Code()
}
defer func() {
p.requestCounter.WithLabelValues(info.FullMethod, statusCode.String()).Inc()
p.requestDuration.WithLabelValues(info.FullMethod).Observe(time.Since(start).Seconds())
p.queueSize.Dec()
}()
if err != nil {
p.log.Error("method call was finished with error", zap.Error(err), zap.String("method", info.FullMethod), zap.Time("start", start), zap.Int64("elapsed", time.Since(start).Milliseconds()))
return nil, err
}
p.log.Debug("method was called successfully", zap.String("method", info.FullMethod), zap.Time("start", start), zap.Int64("elapsed", time.Since(start).Milliseconds()))
return resp, nil
}
func (p *Plugin) serverOptions() ([]grpc.ServerOption, error) {
const op = errors.Op("grpc_plugin_server_options")
var tcreds credentials.TransportCredentials
var opts []grpc.ServerOption
var cert tls.Certificate
var certPool *x509.CertPool
var rca []byte
var err error
if p.config.EnableTLS() {
// if client CA is not empty, we combine it with Cert and Key
if p.config.TLS.RootCA != "" {
cert, err = tls.LoadX509KeyPair(p.config.TLS.Cert, p.config.TLS.Key)
if err != nil {
return nil, err
}
certPool, err = x509.SystemCertPool()
if err != nil {
return nil, err
}
if certPool == nil {
certPool = x509.NewCertPool()
}
rca, err = os.ReadFile(p.config.TLS.RootCA)
if err != nil {
return nil, err
}
if ok := certPool.AppendCertsFromPEM(rca); !ok {
return nil, errors.E(op, errors.Str("could not append Certs from PEM"))
}
opts = append(opts, grpc.Creds(credentials.NewTLS(&tls.Config{
MinVersion: tls.VersionTLS12,
ClientAuth: p.config.TLS.auth,
Certificates: []tls.Certificate{cert},
ClientCAs: certPool,
})))
} else {
// regular TLS from the cert+key
tcreds, err = credentials.NewServerTLSFromFile(p.config.TLS.Cert, p.config.TLS.Key)
if err != nil {
return nil, err
}
opts = append(opts, grpc.Creds(tcreds))
}
}
serverOptions := []grpc.ServerOption{
grpc.MaxSendMsgSize(int(p.config.MaxSendMsgSize)),
grpc.MaxRecvMsgSize(int(p.config.MaxRecvMsgSize)),
grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionIdle: p.config.MaxConnectionIdle,
MaxConnectionAge: p.config.MaxConnectionAge,
MaxConnectionAgeGrace: p.config.MaxConnectionAge,
Time: p.config.PingTime,
Timeout: p.config.Timeout,
}),
grpc.MaxConcurrentStreams(uint32(p.config.MaxConcurrentStreams)), //nolint:gosec
}
opts = append(opts, serverOptions...)
opts = append(opts, p.opts...)
// custom codec is required to bypass protobuf, a common interceptor used for debug and stats
return opts, nil
}