Debian Codegraph @

config/configgrpc/configgrpc.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package configgrpc // import "go.opentelemetry.io/collector/config/configgrpc"
5
6 import (
7 "context"
8 "crypto/tls"
9 "errors"
10 "fmt"
11 "math"
12 "strings"
13 "time"
14
15 "github.com/mostynb/go-grpc-compression/nonclobbering/snappy"
16 "github.com/mostynb/go-grpc-compression/nonclobbering/zstd"
17 "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
18 "go.opentelemetry.io/otel"
19 "google.golang.org/grpc"
20 "google.golang.org/grpc/balancer"
21 "google.golang.org/grpc/codes"
22 "google.golang.org/grpc/credentials"
23 "google.golang.org/grpc/credentials/insecure"
24 "google.golang.org/grpc/encoding/gzip"
25 "google.golang.org/grpc/keepalive"
26 "google.golang.org/grpc/metadata"
27 "google.golang.org/grpc/peer"
28 "google.golang.org/grpc/status"
29
30 "go.opentelemetry.io/collector/client"
31 "go.opentelemetry.io/collector/component"
32 "go.opentelemetry.io/collector/config/configauth"
33 "go.opentelemetry.io/collector/config/configcompression"
34 "go.opentelemetry.io/collector/config/configmiddleware"
35 "go.opentelemetry.io/collector/config/confignet"
36 "go.opentelemetry.io/collector/config/configopaque"
37 "go.opentelemetry.io/collector/config/configoptional"
38 "go.opentelemetry.io/collector/config/configtls"
39 "go.opentelemetry.io/collector/extension/extensionauth"
40 )
41
42 var errMetadataNotFound = errors.New("no request metadata found")
43
44 // KeepaliveClientConfig exposes the keepalive.ClientParameters to be used by the exporter.
45 // Refer to the original data-structure for the meaning of each parameter:
46 // https://godoc.org/google.golang.org/grpc/keepalive#ClientParameters
47 type KeepaliveClientConfig struct {
48 Time time.Duration `mapstructure:"time"`
49 Timeout time.Duration `mapstructure:"timeout"`
50 PermitWithoutStream bool `mapstructure:"permit_without_stream,omitempty"`
51 // prevent unkeyed literal initialization
52 _ struct{}
53 }
54
55 // NewDefaultKeepaliveClientConfig returns a new instance of KeepaliveClientConfig with default values.
56 func NewDefaultKeepaliveClientConfig() KeepaliveClientConfig {
57 return KeepaliveClientConfig{
58 Time: time.Second * 10,
59 Timeout: time.Second * 10,
60 }
61 }
62
63 // BalancerName returns a string with default load balancer value
64 func BalancerName() string {
65 return "round_robin"
66 }
67
68 // ClientConfig defines common settings for a gRPC client configuration.
69 type ClientConfig struct {
70 // The target to which the exporter is going to send traces or metrics,
71 // using the gRPC protocol. The valid syntax is described at
72 // https://github.com/grpc/grpc/blob/master/doc/naming.md.
73 Endpoint string `mapstructure:"endpoint,omitempty"`
74
75 // The compression key for supported compression types within collector.
76 Compression configcompression.Type `mapstructure:"compression,omitempty"`
77
78 // TLS struct exposes TLS client configuration.
79 TLS configtls.ClientConfig `mapstructure:"tls,omitempty"`
80
81 // The keepalive parameters for gRPC client. See grpc.WithKeepaliveParams.
82 // (https://godoc.org/google.golang.org/grpc#WithKeepaliveParams).
83 Keepalive configoptional.Optional[KeepaliveClientConfig] `mapstructure:"keepalive,omitempty"`
84
85 // ReadBufferSize for gRPC client. See grpc.WithReadBufferSize.
86 // (https://godoc.org/google.golang.org/grpc#WithReadBufferSize).
87 ReadBufferSize int `mapstructure:"read_buffer_size,omitempty"`
88
89 // WriteBufferSize for gRPC gRPC. See grpc.WithWriteBufferSize.
90 // (https://godoc.org/google.golang.org/grpc#WithWriteBufferSize).
91 WriteBufferSize int `mapstructure:"write_buffer_size,omitempty"`
92
93 // WaitForReady parameter configures client to wait for ready state before sending data.
94 // (https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md)
95 WaitForReady bool `mapstructure:"wait_for_ready,omitempty"`
96
97 // The headers associated with gRPC requests.
98 Headers configopaque.MapList `mapstructure:"headers,omitempty"`
99
100 // Sets the balancer in grpclb_policy to discover the servers. Default is pick_first.
101 // https://github.com/grpc/grpc-go/blob/master/examples/features/load_balancing/README.md
102 BalancerName string `mapstructure:"balancer_name"`
103
104 // WithAuthority parameter configures client to rewrite ":authority" header
105 // (godoc.org/google.golang.org/grpc#WithAuthority)
106 Authority string `mapstructure:"authority,omitempty"`
107
108 // Auth configuration for outgoing RPCs.
109 Auth configoptional.Optional[configauth.Config] `mapstructure:"auth,omitempty"`
110
111 // Middlewares for the gRPC client.
112 Middlewares []configmiddleware.Config `mapstructure:"middlewares,omitempty"`
113 }
114
115 // NewDefaultClientConfig returns a new instance of ClientConfig with default values.
116 func NewDefaultClientConfig() ClientConfig {
117 return ClientConfig{
118 TLS: configtls.NewDefaultClientConfig(),
119 Keepalive: configoptional.Some(NewDefaultKeepaliveClientConfig()),
120 BalancerName: BalancerName(),
121 }
122 }
123
124 // KeepaliveServerConfig is the configuration for keepalive.
125 type KeepaliveServerConfig struct {
126 ServerParameters configoptional.Optional[KeepaliveServerParameters] `mapstructure:"server_parameters,omitempty"`
127 EnforcementPolicy configoptional.Optional[KeepaliveEnforcementPolicy] `mapstructure:"enforcement_policy,omitempty"`
128 // prevent unkeyed literal initialization
129 _ struct{}
130 }
131
132 // NewDefaultKeepaliveServerConfig returns a new instance of KeepaliveServerConfig with default values.
133 func NewDefaultKeepaliveServerConfig() KeepaliveServerConfig {
134 return KeepaliveServerConfig{
135 ServerParameters: configoptional.Some(NewDefaultKeepaliveServerParameters()),
136 EnforcementPolicy: configoptional.Some(NewDefaultKeepaliveEnforcementPolicy()),
137 }
138 }
139
140 // KeepaliveServerParameters allow configuration of the keepalive.ServerParameters.
141 // The same default values as keepalive.ServerParameters are applicable and get applied by the server.
142 // See https://godoc.org/google.golang.org/grpc/keepalive#ServerParameters for details.
143 type KeepaliveServerParameters struct {
144 MaxConnectionIdle time.Duration `mapstructure:"max_connection_idle,omitempty"`
145 MaxConnectionAge time.Duration `mapstructure:"max_connection_age,omitempty"`
146 MaxConnectionAgeGrace time.Duration `mapstructure:"max_connection_age_grace,omitempty"`
147 Time time.Duration `mapstructure:"time,omitempty"`
148 Timeout time.Duration `mapstructure:"timeout,omitempty"`
149 // prevent unkeyed literal initialization
150 _ struct{}
151 }
152
153 // NewDefaultKeepaliveServerParameters creates and returns a new instance of KeepaliveServerParameters with default settings.
154 func NewDefaultKeepaliveServerParameters() KeepaliveServerParameters {
155 return KeepaliveServerParameters{}
156 }
157
158 // KeepaliveEnforcementPolicy allow configuration of the keepalive.EnforcementPolicy.
159 // The same default values as keepalive.EnforcementPolicy are applicable and get applied by the server.
160 // See https://godoc.org/google.golang.org/grpc/keepalive#EnforcementPolicy for details.
161 type KeepaliveEnforcementPolicy struct {
162 MinTime time.Duration `mapstructure:"min_time,omitempty"`
163 PermitWithoutStream bool `mapstructure:"permit_without_stream,omitempty"`
164 // prevent unkeyed literal initialization
165 _ struct{}
166 }
167
168 // NewDefaultKeepaliveEnforcementPolicy creates and returns a new instance of KeepaliveEnforcementPolicy with default settings.
169 func NewDefaultKeepaliveEnforcementPolicy() KeepaliveEnforcementPolicy {
170 return KeepaliveEnforcementPolicy{}
171 }
172
173 // ServerConfig defines common settings for a gRPC server configuration.
174 type ServerConfig struct {
175 // Server net.Addr config. For transport only "tcp" and "unix" are valid options.
176 NetAddr confignet.AddrConfig `mapstructure:",squash"`
177
178 // Configures the protocol to use TLS.
179 // The default value is nil, which will cause the protocol to not use TLS.
180 TLS configoptional.Optional[configtls.ServerConfig] `mapstructure:"tls,omitempty"`
181
182 // MaxRecvMsgSizeMiB sets the maximum size (in MiB) of messages accepted by the server.
183 MaxRecvMsgSizeMiB int `mapstructure:"max_recv_msg_size_mib,omitempty"`
184
185 // MaxConcurrentStreams sets the limit on the number of concurrent streams to each ServerTransport.
186 // It has effect only for streaming RPCs.
187 MaxConcurrentStreams uint32 `mapstructure:"max_concurrent_streams,omitempty,omitempty"`
188
189 // ReadBufferSize for gRPC server. See grpc.ReadBufferSize.
190 // (https://godoc.org/google.golang.org/grpc#ReadBufferSize).
191 ReadBufferSize int `mapstructure:"read_buffer_size,omitempty"`
192
193 // WriteBufferSize for gRPC server. See grpc.WriteBufferSize.
194 // (https://godoc.org/google.golang.org/grpc#WriteBufferSize).
195 WriteBufferSize int `mapstructure:"write_buffer_size,omitempty"`
196
197 // Keepalive anchor for all the settings related to keepalive.
198 Keepalive configoptional.Optional[KeepaliveServerConfig] `mapstructure:"keepalive,omitempty"`
199
200 // Auth for this receiver
201 Auth configoptional.Optional[configauth.Config] `mapstructure:"auth,omitempty"`
202
203 // Include propagates the incoming connection's metadata to downstream consumers.
204 IncludeMetadata bool `mapstructure:"include_metadata,omitempty"`
205
206 // Middlewares for the gRPC server.
207 Middlewares []configmiddleware.Config `mapstructure:"middlewares,omitempty"`
208
209 // prevent unkeyed literal initialization
210 _ struct{}
211 }
212
213 // NewDefaultServerConfig returns a new instance of ServerConfig with default values.
214 func NewDefaultServerConfig() ServerConfig {
215 netAddr := confignet.NewDefaultAddrConfig()
216
217 // We typically want to create a TCP server and listen over a network.
218 netAddr.Transport = confignet.TransportTypeTCP
219
220 return ServerConfig{
221 Keepalive: configoptional.Some(NewDefaultKeepaliveServerConfig()),
222 NetAddr: netAddr,
223 }
224 }
225
226 func (cc *ClientConfig) Validate() error {
227 if cc.BalancerName != "" {
228 if balancer.Get(cc.BalancerName) == nil {
229 return fmt.Errorf("invalid balancer_name: %s", cc.BalancerName)
230 }
231 }
232
233 return nil
234 }
235
236 // sanitizedEndpoint strips the prefix of either http:// or https:// from configgrpc.ClientConfig.Endpoint.
237 func (cc *ClientConfig) sanitizedEndpoint() string {
238 switch {
239 case cc.isSchemeHTTP():
240 return strings.TrimPrefix(cc.Endpoint, "http://")
241 case cc.isSchemeHTTPS():
242 return strings.TrimPrefix(cc.Endpoint, "https://")
243 default:
244 return cc.Endpoint
245 }
246 }
247
248 func (cc *ClientConfig) isSchemeHTTP() bool {
249 return strings.HasPrefix(cc.Endpoint, "http://")
250 }
251
252 func (cc *ClientConfig) isSchemeHTTPS() bool {
253 return strings.HasPrefix(cc.Endpoint, "https://")
254 }
255
256 // ToClientConnOption is a sealed interface wrapping options for [ClientConfig.ToClientConn].
257 type ToClientConnOption interface {
258 isToClientConnOption()
259 }
260
261 type grpcDialOptionWrapper struct {
262 opt grpc.DialOption
263 }
264
265 // WithGrpcDialOption wraps a [grpc.DialOption] into a [ToClientConnOption].
266 func WithGrpcDialOption(opt grpc.DialOption) ToClientConnOption {
267 return grpcDialOptionWrapper{opt: opt}
268 }
269 func (grpcDialOptionWrapper) isToClientConnOption() {}
270
271 // ToClientConn creates a client connection to the given target. By default, it's
272 // a non-blocking dial (the function won't wait for connections to be
273 // established, and connecting happens in the background). To make it a blocking
274 // dial, use the WithGrpcDialOption(grpc.WithBlock()) option.
275 //
276 // To allow the configuration to reference middleware or authentication extensions,
277 // the `extensions` argument should be the output of `host.GetExtensions()`.
278 // It may also be `nil` in tests where no such extension is expected to be used.
279 func (cc *ClientConfig) ToClientConn(
280 ctx context.Context,
281 extensions map[component.ID]component.Component,
282 settings component.TelemetrySettings,
283 extraOpts ...ToClientConnOption,
284 ) (*grpc.ClientConn, error) {
285 grpcOpts, err := cc.getGrpcDialOptions(ctx, extensions, settings, extraOpts)
286 if err != nil {
287 return nil, err
288 }
289 //nolint:staticcheck // SA1019 see https://github.com/open-telemetry/opentelemetry-collector/pull/11575
290 return grpc.DialContext(ctx, cc.sanitizedEndpoint(), grpcOpts...)
291 }
292
293 func (cc *ClientConfig) addHeadersIfAbsent(ctx context.Context) context.Context {
294 kv := make([]string, 0, 2*len(cc.Headers))
295 existingMd, _ := metadata.FromOutgoingContext(ctx)
296 for k, v := range cc.Headers.Iter {
297 if len(existingMd.Get(k)) == 0 {
298 kv = append(kv, k, string(v))
299 }
300 }
301 return metadata.AppendToOutgoingContext(ctx, kv...)
302 }
303
304 func (cc *ClientConfig) getGrpcDialOptions(
305 ctx context.Context,
306 extensions map[component.ID]component.Component,
307 settings component.TelemetrySettings,
308 extraOpts []ToClientConnOption,
309 ) ([]grpc.DialOption, error) {
310 var opts []grpc.DialOption
311 if cc.Compression.IsCompressed() {
312 cp, err := getGRPCCompressionName(cc.Compression)
313 if err != nil {
314 return nil, err
315 }
316 opts = append(opts, grpc.WithDefaultCallOptions(grpc.UseCompressor(cp)))
317 }
318
319 tlsCfg, err := cc.TLS.LoadTLSConfig(ctx)
320 if err != nil {
321 return nil, err
322 }
323 cred := insecure.NewCredentials()
324 if tlsCfg != nil {
325 cred = credentials.NewTLS(tlsCfg)
326 } else if cc.isSchemeHTTPS() {
327 cred = credentials.NewTLS(&tls.Config{})
328 }
329 opts = append(opts, grpc.WithTransportCredentials(cred))
330
331 if cc.ReadBufferSize > 0 {
332 opts = append(opts, grpc.WithReadBufferSize(cc.ReadBufferSize))
333 }
334
335 if cc.WriteBufferSize > 0 {
336 opts = append(opts, grpc.WithWriteBufferSize(cc.WriteBufferSize))
337 }
338
339 if cc.Keepalive.HasValue() {
340 keepaliveConfig := cc.Keepalive.Get()
341 keepAliveOption := grpc.WithKeepaliveParams(keepalive.ClientParameters{
342 Time: keepaliveConfig.Time,
343 Timeout: keepaliveConfig.Timeout,
344 PermitWithoutStream: keepaliveConfig.PermitWithoutStream,
345 })
346 opts = append(opts, keepAliveOption)
347 }
348
349 if cc.Auth.HasValue() {
350 if extensions == nil {
351 return nil, errors.New("authentication was configured but this component or its host does not support extensions")
352 }
353
354 grpcAuthenticator, cerr := cc.Auth.Get().GetGRPCClientAuthenticator(ctx, extensions)
355 if cerr != nil {
356 return nil, cerr
357 }
358
359 perRPCCredentials, perr := grpcAuthenticator.PerRPCCredentials()
360 if perr != nil {
361 return nil, err
362 }
363 opts = append(opts, grpc.WithPerRPCCredentials(perRPCCredentials))
364 }
365
366 if cc.BalancerName != "" {
367 opts = append(opts, grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"loadBalancingPolicy":%q}`, cc.BalancerName)))
368 }
369
370 if cc.Authority != "" {
371 opts = append(opts, grpc.WithAuthority(cc.Authority))
372 }
373
374 otelOpts := []otelgrpc.Option{
375 otelgrpc.WithTracerProvider(settings.TracerProvider),
376 otelgrpc.WithPropagators(otel.GetTextMapPropagator()),
377 otelgrpc.WithMeterProvider(settings.MeterProvider),
378 }
379
380 // Enable OpenTelemetry observability plugin.
381 opts = append(opts, grpc.WithStatsHandler(otelgrpc.NewClientHandler(otelOpts...)))
382
383 if len(cc.Headers) > 0 {
384 opts = append(opts,
385 grpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply any, gcc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
386 return invoker(cc.addHeadersIfAbsent(ctx), method, req, reply, gcc, opts...)
387 }),
388 grpc.WithStreamInterceptor(func(ctx context.Context, desc *grpc.StreamDesc, gcc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
389 return streamer(cc.addHeadersIfAbsent(ctx), desc, gcc, method, opts...)
390 }),
391 )
392 }
393
394 // Apply middleware options. Note: OpenTelemetry could be registered as an extension.
395 if len(cc.Middlewares) > 0 && extensions == nil {
396 return nil, errors.New("middlewares were configured but this component or its host does not support extensions")
397 }
398 for _, middleware := range cc.Middlewares {
399 middlewareOptions, err := middleware.GetGRPCClientOptions(ctx, extensions)
400 if err != nil {
401 return nil, fmt.Errorf("failed to get gRPC client options from middleware: %w", err)
402 }
403 opts = append(opts, middlewareOptions...)
404 }
405
406 for _, opt := range extraOpts {
407 if wrapper, ok := opt.(grpcDialOptionWrapper); ok {
408 opts = append(opts, wrapper.opt)
409 }
410 }
411
412 return opts, nil
413 }
414
415 func (sc *ServerConfig) Validate() error {
416 if sc.MaxRecvMsgSizeMiB*1024*1024 < 0 {
417 return fmt.Errorf("invalid max_recv_msg_size_mib value, must be between 1 and %d: %d", math.MaxInt/1024/1024, sc.MaxRecvMsgSizeMiB)
418 }
419
420 if sc.ReadBufferSize < 0 {
421 return fmt.Errorf("invalid read_buffer_size value: %d", sc.ReadBufferSize)
422 }
423
424 if sc.WriteBufferSize < 0 {
425 return fmt.Errorf("invalid write_buffer_size value: %d", sc.WriteBufferSize)
426 }
427
428 return nil
429 }
430
431 // ToServerOption is a sealed interface wrapping options for [ServerConfig.ToServer].
432 type ToServerOption interface {
433 isToServerOption()
434 }
435
436 type grpcServerOptionWrapper struct {
437 opt grpc.ServerOption
438 }
439
440 // WithGrpcServerOption wraps a [grpc.ServerOption] into a [ToServerOption].
441 func WithGrpcServerOption(opt grpc.ServerOption) ToServerOption {
442 return grpcServerOptionWrapper{opt: opt}
443 }
444 func (grpcServerOptionWrapper) isToServerOption() {}
445
446 // ToServer returns a [grpc.Server] for the configuration.
447 //
448 // To allow the configuration to reference middleware or authentication extensions,
449 // the `extensions` argument should be the output of `host.GetExtensions()`.
450 // It may also be `nil` in tests where no such extension is expected to be used.
451 func (sc *ServerConfig) ToServer(
452 ctx context.Context,
453 extensions map[component.ID]component.Component,
454 settings component.TelemetrySettings,
455 extraOpts ...ToServerOption,
456 ) (*grpc.Server, error) {
457 grpcOpts, err := sc.getGrpcServerOptions(ctx, extensions, settings, extraOpts)
458 if err != nil {
459 return nil, err
460 }
461 return grpc.NewServer(grpcOpts...), nil
462 }
463
464 func (sc *ServerConfig) getGrpcServerOptions(
465 ctx context.Context,
466 extensions map[component.ID]component.Component,
467 settings component.TelemetrySettings,
468 extraOpts []ToServerOption,
469 ) ([]grpc.ServerOption, error) {
470 var opts []grpc.ServerOption
471
472 if sc.TLS.HasValue() {
473 tlsCfg, err := sc.TLS.Get().LoadTLSConfig(ctx)
474 if err != nil {
475 return nil, err
476 }
477 opts = append(opts, grpc.Creds(credentials.NewTLS(tlsCfg)))
478 }
479
480 if sc.MaxRecvMsgSizeMiB > 0 && sc.MaxRecvMsgSizeMiB*1024*1024 > 0 {
481 opts = append(opts, grpc.MaxRecvMsgSize(sc.MaxRecvMsgSizeMiB*1024*1024))
482 }
483
484 if sc.MaxConcurrentStreams > 0 {
485 opts = append(opts, grpc.MaxConcurrentStreams(sc.MaxConcurrentStreams))
486 }
487
488 if sc.ReadBufferSize > 0 {
489 opts = append(opts, grpc.ReadBufferSize(sc.ReadBufferSize))
490 }
491
492 if sc.WriteBufferSize > 0 {
493 opts = append(opts, grpc.WriteBufferSize(sc.WriteBufferSize))
494 }
495
496 // The default values referenced in the GRPC docs are set within the server, so this code doesn't need
497 // to apply them over zero/nil values before passing these as grpc.ServerOptions.
498 // The following shows the server code for applying default grpc.ServerOptions.
499 // https://github.com/grpc/grpc-go/blob/120728e1f775e40a2a764341939b78d666b08260/internal/transport/http2_server.go#L184-L200
500 if sc.Keepalive.HasValue() {
501 keepaliveConfig := sc.Keepalive.Get()
502 if keepaliveConfig.ServerParameters.HasValue() {
503 svrParams := keepaliveConfig.ServerParameters.Get()
504 opts = append(opts, grpc.KeepaliveParams(keepalive.ServerParameters{
505 MaxConnectionIdle: svrParams.MaxConnectionIdle,
506 MaxConnectionAge: svrParams.MaxConnectionAge,
507 MaxConnectionAgeGrace: svrParams.MaxConnectionAgeGrace,
508 Time: svrParams.Time,
509 Timeout: svrParams.Timeout,
510 }))
511 }
512 // The default values referenced in the GRPC are set within the server, so this code doesn't need
513 // to apply them over zero/nil values before passing these as grpc.ServerOptions.
514 // The following shows the server code for applying default grpc.ServerOptions.
515 // https://github.com/grpc/grpc-go/blob/120728e1f775e40a2a764341939b78d666b08260/internal/transport/http2_server.go#L202-L205
516 if keepaliveConfig.EnforcementPolicy.HasValue() {
517 enfPol := keepaliveConfig.EnforcementPolicy.Get()
518 opts = append(opts, grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{
519 MinTime: enfPol.MinTime,
520 PermitWithoutStream: enfPol.PermitWithoutStream,
521 }))
522 }
523 }
524
525 var uInterceptors []grpc.UnaryServerInterceptor
526 var sInterceptors []grpc.StreamServerInterceptor
527
528 if sc.Auth.HasValue() {
529 authenticator, err := sc.Auth.Get().GetServerAuthenticator(ctx, extensions)
530 if err != nil {
531 return nil, err
532 }
533
534 uInterceptors = append(uInterceptors, authUnaryServerInterceptor(authenticator))
535 sInterceptors = append(sInterceptors, authStreamServerInterceptor(authenticator)) //nolint:contextcheck // context already handled
536 }
537
538 otelOpts := []otelgrpc.Option{
539 otelgrpc.WithTracerProvider(settings.TracerProvider),
540 otelgrpc.WithPropagators(otel.GetTextMapPropagator()),
541 otelgrpc.WithMeterProvider(settings.MeterProvider),
542 }
543
544 // Enable OpenTelemetry observability plugin.
545
546 uInterceptors = append(uInterceptors, enhanceWithClientInformation(sc.IncludeMetadata))
547 sInterceptors = append(sInterceptors, enhanceStreamWithClientInformation(sc.IncludeMetadata)) //nolint:contextcheck // context already handled
548
549 opts = append(opts, grpc.StatsHandler(otelgrpc.NewServerHandler(otelOpts...)), grpc.ChainUnaryInterceptor(uInterceptors...), grpc.ChainStreamInterceptor(sInterceptors...))
550
551 // Apply middleware options. Note: OpenTelemetry could be registered as an extension.
552 for _, middleware := range sc.Middlewares {
553 middlewareOptions, err := middleware.GetGRPCServerOptions(ctx, extensions)
554 if err != nil {
555 return nil, fmt.Errorf("failed to get gRPC server options from middleware: %w", err)
556 }
557 opts = append(opts, middlewareOptions...)
558 }
559
560 for _, opt := range extraOpts {
561 if wrapper, ok := opt.(grpcServerOptionWrapper); ok {
562 opts = append(opts, wrapper.opt)
563 }
564 }
565
566 return opts, nil
567 }
568
569 // getGRPCCompressionName returns compression name registered in grpc.
570 func getGRPCCompressionName(compressionType configcompression.Type) (string, error) {
571 switch compressionType {
572 case configcompression.TypeGzip:
573 return gzip.Name, nil
574 case configcompression.TypeSnappy:
575 return snappy.Name, nil
576 case configcompression.TypeZstd:
577 return zstd.Name, nil
578 default:
579 return "", fmt.Errorf("unsupported compression type %q", compressionType)
580 }
581 }
582
583 // enhanceWithClientInformation intercepts the incoming RPC, replacing the incoming context with one that includes
584 // a client.Info, potentially with the peer's address.
585 func enhanceWithClientInformation(includeMetadata bool) grpc.UnaryServerInterceptor {
586 return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
587 return handler(contextWithClient(ctx, includeMetadata), req)
588 }
589 }
590
591 func enhanceStreamWithClientInformation(includeMetadata bool) grpc.StreamServerInterceptor {
592 return func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
593 return handler(srv, wrapServerStream(contextWithClient(ss.Context(), includeMetadata), ss))
594 }
595 }
596
597 // contextWithClient attempts to add the peer address to the client.Info from the context. When no
598 // client.Info exists in the context, one is created.
599 func contextWithClient(ctx context.Context, includeMetadata bool) context.Context {
600 cl := client.FromContext(ctx)
601 if p, ok := peer.FromContext(ctx); ok {
602 cl.Addr = p.Addr
603 }
604 if includeMetadata {
605 if md, ok := metadata.FromIncomingContext(ctx); ok {
606 copiedMD := md.Copy()
607 if len(md[client.MetadataHostName]) == 0 && len(md[":authority"]) > 0 {
608 copiedMD[client.MetadataHostName] = md[":authority"]
609 }
610 cl.Metadata = client.NewMetadata(copiedMD)
611 }
612 }
613 return client.NewContext(ctx, cl)
614 }
615
616 func authUnaryServerInterceptor(server extensionauth.Server) grpc.UnaryServerInterceptor {
617 return func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
618 headers, ok := metadata.FromIncomingContext(ctx)
619 if !ok {
620 return nil, errMetadataNotFound
621 }
622
623 ctx, err := server.Authenticate(ctx, headers)
624 if err != nil {
625 if s, ok := status.FromError(err); ok {
626 return nil, s.Err()
627 }
628
629 return nil, status.Error(codes.Unauthenticated, err.Error())
630 }
631
632 return handler(ctx, req)
633 }
634 }
635
636 func authStreamServerInterceptor(server extensionauth.Server) grpc.StreamServerInterceptor {
637 return func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
638 ctx := stream.Context()
639 headers, ok := metadata.FromIncomingContext(ctx)
640 if !ok {
641 return errMetadataNotFound
642 }
643
644 ctx, err := server.Authenticate(ctx, headers)
645 if err != nil {
646 if s, ok := status.FromError(err); ok {
647 return s.Err()
648 }
649
650 return status.Error(codes.Unauthenticated, err.Error())
651 }
652
653 return handler(srv, wrapServerStream(ctx, stream))
654 }
655 }