-
Notifications
You must be signed in to change notification settings - Fork 0
/
GRPCHelper.go
364 lines (306 loc) · 10.6 KB
/
GRPCHelper.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
package utils
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"log"
"os"
"time"
"github.com/grpc-ecosystem/go-grpc-middleware/providers/prometheus"
"github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/config"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/status"
)
const ONE_GIGABYTE = 1024 * 1024 * 1024
// ---------------------------------------------------------------------
// The PasswordCredentials type and the receivers it implements, allow
// us to use the grpc.WithPerRPCCredentials() dial option to pass
// credentials to downstream middleware
type PasswordCredentials map[string]string
func NewPassCredentials(m map[string]string) PasswordCredentials {
return PasswordCredentials(m)
}
func (pc PasswordCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return pc, nil
}
func (PasswordCredentials) RequireTransportSecurity() bool {
return false
}
// ---------------------------------------------------------------------
type ConnectionOptions struct {
MaxMessageSize int // Max message size in bytes
SecurityLevel int // 0 = insecure, 1 = secure, 2 = secure with client cert
OpenTelemetry bool // Enable OpenTelemetry tracing
OpenTracing bool // Enable OpenTelemetry tracing
Prometheus bool // Enable Prometheus metrics
CertFile string // CA cert file if SecurityLevel > 0
CaCertFile string // CA cert file if SecurityLevel > 0
KeyFile string // Client key file if SecurityLevel > 1
MaxRetries int // Max number of retries for transient errors
RetryBackoff time.Duration // Backoff between retries
Credentials PasswordCredentials // Credentials to pass to downstream middleware (optional)
}
// ---------------------------------------------------------------------
func init() {
// The secret sauce
resolver.SetDefaultScheme("dns")
}
func InitGlobalTracer(serviceName string) (opentracing.Tracer, io.Closer, error) {
if opentracing.IsGlobalTracerRegistered() {
return nil, nil, errors.New("global tracer already registered")
}
cfg, err := config.FromEnv()
if err != nil {
return nil, nil, fmt.Errorf("cannot parse jaeger environment variables: %v", err.Error())
}
cfg.ServiceName = serviceName
cfg.Sampler.Type = jaeger.SamplerTypeConst
cfg.Sampler.Param = 100
var tracer opentracing.Tracer
var closer io.Closer
tracer, closer, err = cfg.NewTracer()
if err != nil {
return nil, nil, fmt.Errorf("cannot initialize jaeger tracer: %v", err.Error())
}
opentracing.SetGlobalTracer(tracer)
return tracer, closer, nil
}
func GetGRPCClient(ctx context.Context, address string, connectionOptions *ConnectionOptions) (*grpc.ClientConn, error) {
if address == "" {
return nil, errors.New("address is required")
}
if connectionOptions.MaxMessageSize == 0 {
connectionOptions.MaxMessageSize = ONE_GIGABYTE
}
opts := []grpc.DialOption{
// grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
grpc.WithDefaultServiceConfig(`{"loadBalancingConfig": [{"round_robin":{}}]}`),
grpc.WithDefaultCallOptions(
grpc.MaxCallSendMsgSize(connectionOptions.MaxMessageSize),
),
}
tlsCredentials, err := loadTLSCredentials(connectionOptions, false)
if err != nil {
return nil, err
}
opts = append(opts, grpc.WithTransportCredentials(tlsCredentials))
if connectionOptions.OpenTelemetry {
opts = append(
opts,
grpc.WithChainUnaryInterceptor(otelgrpc.UnaryClientInterceptor()),
grpc.WithChainStreamInterceptor(otelgrpc.StreamClientInterceptor()),
)
}
if connectionOptions.OpenTracing {
if opentracing.IsGlobalTracerRegistered() {
tracer := opentracing.GlobalTracer()
opts = append(
opts,
grpc.WithChainUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(tracer)),
grpc.WithChainStreamInterceptor(otgrpc.OpenTracingStreamClientInterceptor(tracer)),
)
} else {
return nil, errors.New("no global tracer set")
}
}
if connectionOptions.Prometheus {
prometheusMetrics := prometheus.NewClientMetrics()
opts = append(
opts,
grpc.WithChainUnaryInterceptor(prometheusMetrics.UnaryClientInterceptor()),
grpc.WithChainStreamInterceptor(prometheusMetrics.StreamClientInterceptor()),
)
}
if connectionOptions.Credentials != nil {
opts = append(opts, grpc.WithPerRPCCredentials(connectionOptions.Credentials))
}
// Retry interceptor...
if connectionOptions.MaxRetries > 0 {
if connectionOptions.RetryBackoff == 0 {
connectionOptions.RetryBackoff = 100 * time.Millisecond
}
opts = append(opts, grpc.WithChainUnaryInterceptor(retryInterceptor(connectionOptions.MaxRetries, connectionOptions.RetryBackoff)))
}
conn, err := grpc.DialContext(
ctx,
address,
opts...,
)
if err != nil {
return nil, fmt.Errorf("error dialling grpc service at %s: %v", address, err)
}
return conn, nil
}
func GetGRPCServer(connectionOptions *ConnectionOptions) (*grpc.Server, error) {
var opts []grpc.ServerOption
if connectionOptions.MaxMessageSize == 0 {
connectionOptions.MaxMessageSize = ONE_GIGABYTE
}
opts = append(opts, grpc.MaxRecvMsgSize(connectionOptions.MaxMessageSize))
if connectionOptions.OpenTelemetry {
opts = append(
opts,
grpc.ChainUnaryInterceptor(otelgrpc.UnaryServerInterceptor()),
grpc.ChainStreamInterceptor(otelgrpc.StreamServerInterceptor()),
)
}
if connectionOptions.OpenTracing {
if opentracing.IsGlobalTracerRegistered() {
tracer := opentracing.GlobalTracer()
opts = append(opts, grpc.ChainUnaryInterceptor(otgrpc.OpenTracingServerInterceptor(tracer)))
opts = append(opts, grpc.ChainStreamInterceptor(otgrpc.OpenTracingStreamServerInterceptor(tracer)))
} else {
return nil, errors.New("no global tracer set")
}
}
if connectionOptions.Prometheus {
prometheusMetrics := prometheus.NewServerMetrics()
opts = append(
opts,
grpc.ChainUnaryInterceptor(prometheusMetrics.UnaryServerInterceptor()),
grpc.ChainStreamInterceptor(prometheusMetrics.StreamServerInterceptor()),
)
}
tlsCredentials, err := loadTLSCredentials(connectionOptions, true)
if err != nil {
return nil, err
}
opts = append(opts, grpc.Creds(tlsCredentials))
return grpc.NewServer(opts...), nil
}
func retryInterceptor(maxRetries int, retryBackoff time.Duration) grpc.UnaryClientInterceptor {
return func(
ctx context.Context,
method string,
req, reply interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption,
) error {
var err error
for i := 0; i < maxRetries; i++ {
err = invoker(ctx, method, req, reply, cc, opts...)
if err == nil {
return nil
}
// Check if we can retry (e.g., codes.Unavailable, codes.DeadlineExceeded)
if status.Code(err) != codes.Unavailable && status.Code(err) != codes.DeadlineExceeded {
break
}
log.Printf("Retry attempt %d for request: %s\n", i+1, method)
time.Sleep(retryBackoff)
}
return err
}
}
func loadTLSCredentials(connectionData *ConnectionOptions, isServer bool) (credentials.TransportCredentials, error) {
switch connectionData.SecurityLevel {
case 0:
// No security
return insecure.NewCredentials(), nil
case 1:
// No client cert
if isServer {
cert, err := tls.LoadX509KeyPair(connectionData.CertFile, connectionData.KeyFile)
if err != nil {
return nil, fmt.Errorf("failed to read key pair: %w", err)
}
return credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: true,
ClientAuth: tls.NoClientCert,
}), nil
} else {
// Load the server's CA certificate from disk
caCert, err := os.ReadFile(connectionData.CaCertFile)
if err != nil {
return nil, fmt.Errorf("failed to read ca cert file: %w", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
return credentials.NewTLS(&tls.Config{
RootCAs: caCertPool,
}), nil
}
case 2:
// Any client cert
if isServer {
cert, err := tls.LoadX509KeyPair(connectionData.CertFile, connectionData.KeyFile)
if err != nil {
return nil, fmt.Errorf("failed to read key pair: %w", err)
}
return credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: true,
ClientAuth: tls.RequireAnyClientCert,
}), nil
} else {
// Load the server's CA certificate from disk
caCert, err := os.ReadFile(connectionData.CaCertFile)
if err != nil {
return nil, fmt.Errorf("failed to read ca cert file: %w", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
cert, err := tls.LoadX509KeyPair(connectionData.CertFile, connectionData.KeyFile)
if err != nil {
return nil, fmt.Errorf("failed to read key pair: %w", err)
}
return credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: true,
RootCAs: caCertPool,
}), nil
}
case 3:
// Require client cert
if isServer {
// Load the server's CA certificate from disk
caCert, err := os.ReadFile(connectionData.CaCertFile)
if err != nil {
return nil, fmt.Errorf("failed to read ca cert file: %w", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
cert, err := tls.LoadX509KeyPair(connectionData.CertFile, connectionData.KeyFile)
if err != nil {
return nil, fmt.Errorf("failed to read key pair: %w", err)
}
return credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: true,
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: caCertPool,
}), nil
} else {
// Load the server's CA certificate from disk
caCert, err := os.ReadFile(connectionData.CaCertFile)
if err != nil {
return nil, fmt.Errorf("failed to read ca cert file: %w", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
cert, err := tls.LoadX509KeyPair(connectionData.CertFile, connectionData.KeyFile)
if err != nil {
return nil, fmt.Errorf("failed to read key pair: %w", err)
}
return credentials.NewTLS(&tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: true,
RootCAs: caCertPool,
}), nil
}
}
return nil, errors.New("securityLevel must be 0, 1, 2 or 3")
}