| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package 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 |
|
| 45 |
|
| 46 |
|
| 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 |
|
| 52 |
_ struct{} |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
func NewDefaultKeepaliveClientConfig() KeepaliveClientConfig { |
| 57 |
return KeepaliveClientConfig{ |
| 58 |
Time: time.Second * 10, |
| 59 |
Timeout: time.Second * 10, |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
func BalancerName() string { |
| 65 |
return "round_robin" |
| 66 |
} |
| 67 |
|
| 68 |
|
| 69 |
type ClientConfig struct { |
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
Endpoint string `mapstructure:"endpoint,omitempty"` |
| 74 |
|
| 75 |
|
| 76 |
Compression configcompression.Type `mapstructure:"compression,omitempty"` |
| 77 |
|
| 78 |
|
| 79 |
TLS configtls.ClientConfig `mapstructure:"tls,omitempty"` |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
Keepalive configoptional.Optional[KeepaliveClientConfig] `mapstructure:"keepalive,omitempty"` |
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
ReadBufferSize int `mapstructure:"read_buffer_size,omitempty"` |
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
WriteBufferSize int `mapstructure:"write_buffer_size,omitempty"` |
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
WaitForReady bool `mapstructure:"wait_for_ready,omitempty"` |
| 96 |
|
| 97 |
|
| 98 |
Headers configopaque.MapList `mapstructure:"headers,omitempty"` |
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
BalancerName string `mapstructure:"balancer_name"` |
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
Authority string `mapstructure:"authority,omitempty"` |
| 107 |
|
| 108 |
|
| 109 |
Auth configoptional.Optional[configauth.Config] `mapstructure:"auth,omitempty"` |
| 110 |
|
| 111 |
|
| 112 |
Middlewares []configmiddleware.Config `mapstructure:"middlewares,omitempty"` |
| 113 |
} |
| 114 |
|
| 115 |
|
| 116 |
func NewDefaultClientConfig() ClientConfig { |
| 117 |
return ClientConfig{ |
| 118 |
TLS: configtls.NewDefaultClientConfig(), |
| 119 |
Keepalive: configoptional.Some(NewDefaultKeepaliveClientConfig()), |
| 120 |
BalancerName: BalancerName(), |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
|
| 125 |
type KeepaliveServerConfig struct { |
| 126 |
ServerParameters configoptional.Optional[KeepaliveServerParameters] `mapstructure:"server_parameters,omitempty"` |
| 127 |
EnforcementPolicy configoptional.Optional[KeepaliveEnforcementPolicy] `mapstructure:"enforcement_policy,omitempty"` |
| 128 |
|
| 129 |
_ struct{} |
| 130 |
} |
| 131 |
|
| 132 |
|
| 133 |
func NewDefaultKeepaliveServerConfig() KeepaliveServerConfig { |
| 134 |
return KeepaliveServerConfig{ |
| 135 |
ServerParameters: configoptional.Some(NewDefaultKeepaliveServerParameters()), |
| 136 |
EnforcementPolicy: configoptional.Some(NewDefaultKeepaliveEnforcementPolicy()), |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 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 |
|
| 150 |
_ struct{} |
| 151 |
} |
| 152 |
|
| 153 |
|
| 154 |
func NewDefaultKeepaliveServerParameters() KeepaliveServerParameters { |
| 155 |
return KeepaliveServerParameters{} |
| 156 |
} |
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
type KeepaliveEnforcementPolicy struct { |
| 162 |
MinTime time.Duration `mapstructure:"min_time,omitempty"` |
| 163 |
PermitWithoutStream bool `mapstructure:"permit_without_stream,omitempty"` |
| 164 |
|
| 165 |
_ struct{} |
| 166 |
} |
| 167 |
|
| 168 |
|
| 169 |
func NewDefaultKeepaliveEnforcementPolicy() KeepaliveEnforcementPolicy { |
| 170 |
return KeepaliveEnforcementPolicy{} |
| 171 |
} |
| 172 |
|
| 173 |
|
| 174 |
type ServerConfig struct { |
| 175 |
|
| 176 |
NetAddr confignet.AddrConfig `mapstructure:",squash"` |
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
TLS configoptional.Optional[configtls.ServerConfig] `mapstructure:"tls,omitempty"` |
| 181 |
|
| 182 |
|
| 183 |
MaxRecvMsgSizeMiB int `mapstructure:"max_recv_msg_size_mib,omitempty"` |
| 184 |
|
| 185 |
|
| 186 |
|
| 187 |
MaxConcurrentStreams uint32 `mapstructure:"max_concurrent_streams,omitempty,omitempty"` |
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
ReadBufferSize int `mapstructure:"read_buffer_size,omitempty"` |
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
WriteBufferSize int `mapstructure:"write_buffer_size,omitempty"` |
| 196 |
|
| 197 |
|
| 198 |
Keepalive configoptional.Optional[KeepaliveServerConfig] `mapstructure:"keepalive,omitempty"` |
| 199 |
|
| 200 |
|
| 201 |
Auth configoptional.Optional[configauth.Config] `mapstructure:"auth,omitempty"` |
| 202 |
|
| 203 |
|
| 204 |
IncludeMetadata bool `mapstructure:"include_metadata,omitempty"` |
| 205 |
|
| 206 |
|
| 207 |
Middlewares []configmiddleware.Config `mapstructure:"middlewares,omitempty"` |
| 208 |
|
| 209 |
|
| 210 |
_ struct{} |
| 211 |
} |
| 212 |
|
| 213 |
|
| 214 |
func NewDefaultServerConfig() ServerConfig { |
| 215 |
netAddr := confignet.NewDefaultAddrConfig() |
| 216 |
|
| 217 |
|
| 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 |
|
| 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 |
|
| 257 |
type ToClientConnOption interface { |
| 258 |
isToClientConnOption() |
| 259 |
} |
| 260 |
|
| 261 |
type grpcDialOptionWrapper struct { |
| 262 |
opt grpc.DialOption |
| 263 |
} |
| 264 |
|
| 265 |
|
| 266 |
func WithGrpcDialOption(opt grpc.DialOption) ToClientConnOption { |
| 267 |
return grpcDialOptionWrapper{opt: opt} |
| 268 |
} |
| 269 |
func (grpcDialOptionWrapper) isToClientConnOption() {} |
| 270 |
|
| 271 |
|
| 272 |
|
| 273 |
|
| 274 |
|
| 275 |
|
| 276 |
|
| 277 |
|
| 278 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 432 |
type ToServerOption interface { |
| 433 |
isToServerOption() |
| 434 |
} |
| 435 |
|
| 436 |
type grpcServerOptionWrapper struct { |
| 437 |
opt grpc.ServerOption |
| 438 |
} |
| 439 |
|
| 440 |
|
| 441 |
func WithGrpcServerOption(opt grpc.ServerOption) ToServerOption { |
| 442 |
return grpcServerOptionWrapper{opt: opt} |
| 443 |
} |
| 444 |
func (grpcServerOptionWrapper) isToServerOption() {} |
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
|
| 450 |
|
| 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 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 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 |
|
| 513 |
|
| 514 |
|
| 515 |
|
| 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)) |
| 536 |
} |
| 537 |
|
| 538 |
otelOpts := []otelgrpc.Option{ |
| 539 |
otelgrpc.WithTracerProvider(settings.TracerProvider), |
| 540 |
otelgrpc.WithPropagators(otel.GetTextMapPropagator()), |
| 541 |
otelgrpc.WithMeterProvider(settings.MeterProvider), |
| 542 |
} |
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
uInterceptors = append(uInterceptors, enhanceWithClientInformation(sc.IncludeMetadata)) |
| 547 |
sInterceptors = append(sInterceptors, enhanceStreamWithClientInformation(sc.IncludeMetadata)) |
| 548 |
|
| 549 |
opts = append(opts, grpc.StatsHandler(otelgrpc.NewServerHandler(otelOpts...)), grpc.ChainUnaryInterceptor(uInterceptors...), grpc.ChainStreamInterceptor(sInterceptors...)) |
| 550 |
|
| 551 |
|
| 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 |
|
| 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 |
|
| 584 |
|
| 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 |
|
| 598 |
|
| 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 |
} |