| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package otelgrpc_test |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"errors" |
| 9 |
"io" |
| 10 |
"net" |
| 11 |
"strings" |
| 12 |
"testing" |
| 13 |
|
| 14 |
"github.com/stretchr/testify/assert" |
| 15 |
"github.com/stretchr/testify/require" |
| 16 |
"go.opentelemetry.io/otel/attribute" |
| 17 |
"go.opentelemetry.io/otel/baggage" |
| 18 |
"go.opentelemetry.io/otel/propagation" |
| 19 |
"go.opentelemetry.io/otel/sdk/metric" |
| 20 |
"go.opentelemetry.io/otel/sdk/metric/metricdata" |
| 21 |
"google.golang.org/grpc" |
| 22 |
"google.golang.org/grpc/credentials/insecure" |
| 23 |
testpb "google.golang.org/grpc/interop/grpc_testing" |
| 24 |
"google.golang.org/grpc/metadata" |
| 25 |
"google.golang.org/grpc/stats" |
| 26 |
|
| 27 |
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" |
| 28 |
) |
| 29 |
|
| 30 |
|
| 31 |
type testLabelerServer struct { |
| 32 |
testpb.UnimplementedTestServiceServer |
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
func (*testLabelerServer) EmptyCall(_ context.Context, _ *testpb.Empty) (*testpb.Empty, error) { |
| 37 |
return &testpb.Empty{}, nil |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
func (*testLabelerServer) UnaryCall(_ context.Context, _ *testpb.SimpleRequest) (*testpb.SimpleResponse, error) { |
| 42 |
return &testpb.SimpleResponse{}, nil |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
func (*testLabelerServer) StreamingInputCall(stream testpb.TestService_StreamingInputCallServer) error { |
| 47 |
for { |
| 48 |
_, err := stream.Recv() |
| 49 |
if err != nil { |
| 50 |
switch { |
| 51 |
case errors.Is(err, io.EOF): |
| 52 |
return stream.SendAndClose(&testpb.StreamingInputCallResponse{}) |
| 53 |
default: |
| 54 |
return err |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
func (*testLabelerServer) StreamingOutputCall(req *testpb.StreamingOutputCallRequest, stream testpb.TestService_StreamingOutputCallServer) error { |
| 62 |
for _, param := range req.ResponseParameters { |
| 63 |
payload := &testpb.Payload{ |
| 64 |
Type: testpb.PayloadType_COMPRESSABLE, |
| 65 |
Body: make([]byte, param.Size), |
| 66 |
} |
| 67 |
if err := stream.Send(&testpb.StreamingOutputCallResponse{Payload: payload}); err != nil { |
| 68 |
return err |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
return nil |
| 73 |
} |
| 74 |
|
| 75 |
const ( |
| 76 |
serverLabelingDirection = iota |
| 77 |
clientLabelingDirection |
| 78 |
) |
| 79 |
|
| 80 |
|
| 81 |
func TestMetricAttributesFn_ServerSide(t *testing.T) { |
| 82 |
reader := metric.NewManualReader() |
| 83 |
mp := metric.NewMeterProvider(metric.WithReader(reader)) |
| 84 |
|
| 85 |
lis, server := startTestServerWithOptions(t, mp, otelgrpc.WithMetricAttributesFn(func(ctx context.Context) []attribute.KeyValue { |
| 86 |
md, ok := metadata.FromIncomingContext(ctx) |
| 87 |
var origin string |
| 88 |
if ok { |
| 89 |
originVals := md.Get("x-origin") |
| 90 |
if len(originVals) > 0 { |
| 91 |
origin = originVals[0] |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
return []attribute.KeyValue{ |
| 96 |
attribute.String("origin", origin), |
| 97 |
attribute.String("tier", "premium"), |
| 98 |
} |
| 99 |
})) |
| 100 |
defer server.Stop() |
| 101 |
|
| 102 |
ctx := metadata.NewOutgoingContext(t.Context(), metadata.Pairs("x-origin", "dynamic-origin")) |
| 103 |
client := createTestClient(t, lis.Addr().String(), nil, nil) |
| 104 |
_, err := client.EmptyCall(ctx, &testpb.Empty{}) |
| 105 |
require.NoError(t, err) |
| 106 |
|
| 107 |
assertAllMetricsHaveLabels(t, reader, serverLabelingDirection, map[string]string{ |
| 108 |
"origin": "dynamic-origin", |
| 109 |
"tier": "premium", |
| 110 |
}) |
| 111 |
} |
| 112 |
|
| 113 |
|
| 114 |
func TestMetricAttributesFn_ServerSideStreaming(t *testing.T) { |
| 115 |
reader := metric.NewManualReader() |
| 116 |
mp := metric.NewMeterProvider(metric.WithReader(reader)) |
| 117 |
|
| 118 |
lis, server := startTestServerWithOptions(t, mp, otelgrpc.WithMetricAttributesFn(func(ctx context.Context) []attribute.KeyValue { |
| 119 |
md, ok := metadata.FromIncomingContext(ctx) |
| 120 |
var origin string |
| 121 |
if ok { |
| 122 |
originVals := md.Get("x-origin") |
| 123 |
if len(originVals) > 0 { |
| 124 |
origin = originVals[0] |
| 125 |
} |
| 126 |
} |
| 127 |
return []attribute.KeyValue{ |
| 128 |
attribute.String("origin", origin), |
| 129 |
attribute.String("tier", "streaming"), |
| 130 |
} |
| 131 |
})) |
| 132 |
defer server.Stop() |
| 133 |
|
| 134 |
ctx := metadata.NewOutgoingContext(t.Context(), metadata.Pairs("x-origin", "dynamic-stream-origin")) |
| 135 |
client := createTestClient(t, lis.Addr().String(), nil, nil) |
| 136 |
|
| 137 |
stream, err := client.StreamingOutputCall(ctx, &testpb.StreamingOutputCallRequest{ |
| 138 |
ResponseParameters: []*testpb.ResponseParameters{ |
| 139 |
{Size: 1}, {Size: 2}, |
| 140 |
}, |
| 141 |
}) |
| 142 |
require.NoError(t, err) |
| 143 |
|
| 144 |
var count int |
| 145 |
for { |
| 146 |
_, err := stream.Recv() |
| 147 |
if errors.Is(err, io.EOF) { |
| 148 |
break |
| 149 |
} |
| 150 |
require.NoError(t, err) |
| 151 |
count++ |
| 152 |
} |
| 153 |
require.Equal(t, 2, count) |
| 154 |
|
| 155 |
assertAllMetricsHaveLabels(t, reader, serverLabelingDirection, map[string]string{ |
| 156 |
"origin": "dynamic-stream-origin", |
| 157 |
"tier": "streaming", |
| 158 |
}) |
| 159 |
} |
| 160 |
|
| 161 |
|
| 162 |
func TestMetricAttributesFn_ServerSide_Baggage(t *testing.T) { |
| 163 |
reader := metric.NewManualReader() |
| 164 |
mp := metric.NewMeterProvider(metric.WithReader(reader)) |
| 165 |
|
| 166 |
metricFunc := func(ctx context.Context) []attribute.KeyValue { |
| 167 |
bag := baggage.FromContext(ctx) |
| 168 |
if tier := bag.Member("tenant.tier"); tier.Value() != "" { |
| 169 |
return []attribute.KeyValue{ |
| 170 |
attribute.String("tenant.tier", tier.Value()), |
| 171 |
} |
| 172 |
} |
| 173 |
return []attribute.KeyValue{ |
| 174 |
attribute.String("tenant.tier", "NOT_FOUND"), |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
lis, server := startTestServerWithOptions(t, mp, |
| 179 |
otelgrpc.WithMetricAttributesFn(metricFunc), |
| 180 |
otelgrpc.WithPropagators(propagation.NewCompositeTextMapPropagator( |
| 181 |
propagation.Baggage{}, |
| 182 |
)), |
| 183 |
) |
| 184 |
defer server.Stop() |
| 185 |
|
| 186 |
conn, err := grpc.NewClient( |
| 187 |
lis.Addr().String(), |
| 188 |
grpc.WithTransportCredentials(insecure.NewCredentials()), |
| 189 |
grpc.WithStatsHandler(otelgrpc.NewClientHandler( |
| 190 |
otelgrpc.WithPropagators(propagation.NewCompositeTextMapPropagator( |
| 191 |
propagation.Baggage{}, |
| 192 |
)), |
| 193 |
)), |
| 194 |
) |
| 195 |
require.NoError(t, err) |
| 196 |
t.Cleanup(func() { conn.Close() }) |
| 197 |
|
| 198 |
client := testpb.NewTestServiceClient(conn) |
| 199 |
|
| 200 |
member, err := baggage.NewMember("tenant.tier", "premium") |
| 201 |
require.NoError(t, err) |
| 202 |
bag, err := baggage.New(member) |
| 203 |
require.NoError(t, err) |
| 204 |
ctx := baggage.ContextWithBaggage(t.Context(), bag) |
| 205 |
|
| 206 |
_, err = client.EmptyCall(ctx, &testpb.Empty{}) |
| 207 |
require.NoError(t, err) |
| 208 |
|
| 209 |
assertAllMetricsHaveLabels(t, reader, serverLabelingDirection, map[string]string{ |
| 210 |
"tenant.tier": "premium", |
| 211 |
}) |
| 212 |
} |
| 213 |
|
| 214 |
type enrichedServerHandler struct { |
| 215 |
stats.Handler |
| 216 |
} |
| 217 |
|
| 218 |
type tenantTierKeyType struct{} |
| 219 |
|
| 220 |
var tenantTierKey tenantTierKeyType |
| 221 |
|
| 222 |
|
| 223 |
func (h *enrichedServerHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { |
| 224 |
ctx = context.WithValue(ctx, tenantTierKey, "premium") |
| 225 |
return h.Handler.TagRPC(ctx, info) |
| 226 |
} |
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
func TestMetricAttributesFn_ServerSide_WithWrappedHandler(t *testing.T) { |
| 231 |
reader := metric.NewManualReader() |
| 232 |
mp := metric.NewMeterProvider(metric.WithReader(reader)) |
| 233 |
|
| 234 |
metricFunc := func(ctx context.Context) []attribute.KeyValue { |
| 235 |
if tier, ok := ctx.Value(tenantTierKey).(string); ok { |
| 236 |
return []attribute.KeyValue{ |
| 237 |
attribute.String("tenant.tier", tier), |
| 238 |
} |
| 239 |
} |
| 240 |
return []attribute.KeyValue{ |
| 241 |
attribute.String("tenant.tier", "NOT_FOUND"), |
| 242 |
} |
| 243 |
} |
| 244 |
|
| 245 |
lis, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "localhost:0") |
| 246 |
require.NoError(t, err) |
| 247 |
|
| 248 |
wrappedHandler := &enrichedServerHandler{ |
| 249 |
Handler: otelgrpc.NewServerHandler( |
| 250 |
otelgrpc.WithMeterProvider(mp), |
| 251 |
otelgrpc.WithMetricAttributesFn(metricFunc), |
| 252 |
), |
| 253 |
} |
| 254 |
|
| 255 |
server := grpc.NewServer( |
| 256 |
grpc.StatsHandler(wrappedHandler), |
| 257 |
) |
| 258 |
testpb.RegisterTestServiceServer(server, &testLabelerServer{}) |
| 259 |
|
| 260 |
go func() { |
| 261 |
if err := server.Serve(lis); err != nil && !errors.Is(err, grpc.ErrServerStopped) { |
| 262 |
t.Errorf("server failed: %v", err) |
| 263 |
} |
| 264 |
}() |
| 265 |
defer server.Stop() |
| 266 |
|
| 267 |
client := createTestClient(t, lis.Addr().String(), nil, nil) |
| 268 |
_, err = client.EmptyCall(t.Context(), &testpb.Empty{}) |
| 269 |
require.NoError(t, err) |
| 270 |
|
| 271 |
assertAllMetricsHaveLabels(t, reader, serverLabelingDirection, map[string]string{ |
| 272 |
"tenant.tier": "premium", |
| 273 |
}) |
| 274 |
} |
| 275 |
|
| 276 |
|
| 277 |
func TestMetricAttributesFn_ClientSide(t *testing.T) { |
| 278 |
serverLis, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "localhost:0") |
| 279 |
require.NoError(t, err) |
| 280 |
|
| 281 |
server := grpc.NewServer() |
| 282 |
testpb.RegisterTestServiceServer(server, &testLabelerServer{}) |
| 283 |
|
| 284 |
go func() { |
| 285 |
if err := server.Serve(serverLis); err != nil && !errors.Is(err, grpc.ErrServerStopped) { |
| 286 |
t.Errorf("server failed: %v", err) |
| 287 |
} |
| 288 |
}() |
| 289 |
defer server.Stop() |
| 290 |
|
| 291 |
reader := metric.NewManualReader() |
| 292 |
mp := metric.NewMeterProvider(metric.WithReader(reader)) |
| 293 |
|
| 294 |
type rpcServiceKeyType struct{} |
| 295 |
var rpcServiceKey rpcServiceKeyType |
| 296 |
|
| 297 |
dynamicServiceName := "orders-service" |
| 298 |
var interceptor grpc.UnaryClientInterceptor = func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { |
| 299 |
ctx = context.WithValue(ctx, rpcServiceKey, dynamicServiceName) |
| 300 |
return invoker(ctx, method, req, reply, cc, opts...) |
| 301 |
} |
| 302 |
|
| 303 |
metricFunc := func(ctx context.Context) []attribute.KeyValue { |
| 304 |
if svc, ok := ctx.Value(rpcServiceKey).(string); ok { |
| 305 |
return []attribute.KeyValue{ |
| 306 |
attribute.String("rpc.service", svc), |
| 307 |
attribute.String("client.version", "v1.2.3"), |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
return []attribute.KeyValue{ |
| 312 |
attribute.String("client.version", "v1.2.3"), |
| 313 |
} |
| 314 |
} |
| 315 |
|
| 316 |
client := createTestClient(t, serverLis.Addr().String(), mp, metricFunc, interceptor) |
| 317 |
|
| 318 |
_, err = client.EmptyCall(t.Context(), &testpb.Empty{}) |
| 319 |
require.NoError(t, err) |
| 320 |
|
| 321 |
assertAllMetricsHaveLabels(t, reader, clientLabelingDirection, map[string]string{ |
| 322 |
"client.version": "v1.2.3", |
| 323 |
"rpc.service": dynamicServiceName, |
| 324 |
}) |
| 325 |
} |
| 326 |
|
| 327 |
|
| 328 |
func TestMetricAttributesFn_ClientSideStreaming(t *testing.T) { |
| 329 |
serverLis, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "localhost:0") |
| 330 |
require.NoError(t, err) |
| 331 |
|
| 332 |
server := grpc.NewServer() |
| 333 |
testpb.RegisterTestServiceServer(server, &testLabelerServer{}) |
| 334 |
go func() { |
| 335 |
if err := server.Serve(serverLis); err != nil && !errors.Is(err, grpc.ErrServerStopped) { |
| 336 |
t.Errorf("server failed: %v", err) |
| 337 |
} |
| 338 |
}() |
| 339 |
defer server.Stop() |
| 340 |
|
| 341 |
reader := metric.NewManualReader() |
| 342 |
mp := metric.NewMeterProvider(metric.WithReader(reader)) |
| 343 |
|
| 344 |
type rpcServiceKeyType struct{} |
| 345 |
var rpcServiceKey rpcServiceKeyType |
| 346 |
dynamicServiceName := "orders-service" |
| 347 |
|
| 348 |
var interceptor grpc.StreamClientInterceptor = func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { |
| 349 |
ctx = context.WithValue(ctx, rpcServiceKey, dynamicServiceName) |
| 350 |
return streamer(ctx, desc, cc, method, opts...) |
| 351 |
} |
| 352 |
|
| 353 |
metricFunc := func(ctx context.Context) []attribute.KeyValue { |
| 354 |
if svc, ok := ctx.Value(rpcServiceKey).(string); ok { |
| 355 |
return []attribute.KeyValue{ |
| 356 |
attribute.String("rpc.service", svc), |
| 357 |
attribute.String("client.version", "v2.0.0"), |
| 358 |
} |
| 359 |
} |
| 360 |
return []attribute.KeyValue{ |
| 361 |
attribute.String("client.version", "v2.0.0"), |
| 362 |
} |
| 363 |
} |
| 364 |
|
| 365 |
client := createTestClient(t, serverLis.Addr().String(), mp, metricFunc, interceptor) |
| 366 |
|
| 367 |
stream, err := client.StreamingInputCall(t.Context()) |
| 368 |
require.NoError(t, err) |
| 369 |
|
| 370 |
for range 3 { |
| 371 |
err := stream.Send(&testpb.StreamingInputCallRequest{ |
| 372 |
Payload: &testpb.Payload{Body: []byte("hello")}, |
| 373 |
}) |
| 374 |
require.NoError(t, err) |
| 375 |
} |
| 376 |
|
| 377 |
_, err = stream.CloseAndRecv() |
| 378 |
require.NoError(t, err) |
| 379 |
|
| 380 |
assertAllMetricsHaveLabels(t, reader, clientLabelingDirection, map[string]string{ |
| 381 |
"client.version": "v2.0.0", |
| 382 |
"rpc.service": dynamicServiceName, |
| 383 |
}) |
| 384 |
} |
| 385 |
|
| 386 |
|
| 387 |
func TestMetricAttributesFn_ClientSide_Baggage(t *testing.T) { |
| 388 |
serverLis, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "localhost:0") |
| 389 |
require.NoError(t, err) |
| 390 |
|
| 391 |
server := grpc.NewServer() |
| 392 |
testpb.RegisterTestServiceServer(server, &testLabelerServer{}) |
| 393 |
|
| 394 |
go func() { |
| 395 |
if err := server.Serve(serverLis); err != nil && !errors.Is(err, grpc.ErrServerStopped) { |
| 396 |
t.Errorf("server failed: %v", err) |
| 397 |
} |
| 398 |
}() |
| 399 |
defer server.Stop() |
| 400 |
|
| 401 |
reader := metric.NewManualReader() |
| 402 |
mp := metric.NewMeterProvider(metric.WithReader(reader)) |
| 403 |
|
| 404 |
metricFunc := func(ctx context.Context) []attribute.KeyValue { |
| 405 |
bag := baggage.FromContext(ctx) |
| 406 |
if env := bag.Member("environment"); env.Value() != "" { |
| 407 |
return []attribute.KeyValue{ |
| 408 |
attribute.String("environment", env.Value()), |
| 409 |
} |
| 410 |
} |
| 411 |
return []attribute.KeyValue{ |
| 412 |
attribute.String("environment", "NOT_FOUND"), |
| 413 |
} |
| 414 |
} |
| 415 |
|
| 416 |
client := createTestClient(t, serverLis.Addr().String(), mp, metricFunc) |
| 417 |
|
| 418 |
member, err := baggage.NewMember("environment", "staging") |
| 419 |
require.NoError(t, err) |
| 420 |
bag, err := baggage.New(member) |
| 421 |
require.NoError(t, err) |
| 422 |
ctx := baggage.ContextWithBaggage(t.Context(), bag) |
| 423 |
|
| 424 |
_, err = client.EmptyCall(ctx, &testpb.Empty{}) |
| 425 |
require.NoError(t, err) |
| 426 |
|
| 427 |
assertAllMetricsHaveLabels(t, reader, clientLabelingDirection, map[string]string{ |
| 428 |
"environment": "staging", |
| 429 |
}) |
| 430 |
} |
| 431 |
|
| 432 |
type enrichedClientHandler struct { |
| 433 |
stats.Handler |
| 434 |
} |
| 435 |
|
| 436 |
type rpcServiceKeyType struct{} |
| 437 |
|
| 438 |
var rpcServiceKey rpcServiceKeyType |
| 439 |
|
| 440 |
|
| 441 |
func (h *enrichedClientHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context { |
| 442 |
ctx = context.WithValue(ctx, rpcServiceKey, "orders-service-wrapped") |
| 443 |
return h.Handler.TagRPC(ctx, info) |
| 444 |
} |
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
func TestMetricAttributesFn_ClientSide_WithWrappedHandler(t *testing.T) { |
| 449 |
serverLis, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "localhost:0") |
| 450 |
require.NoError(t, err) |
| 451 |
|
| 452 |
server := grpc.NewServer() |
| 453 |
testpb.RegisterTestServiceServer(server, &testLabelerServer{}) |
| 454 |
|
| 455 |
go func() { |
| 456 |
if err := server.Serve(serverLis); err != nil && !errors.Is(err, grpc.ErrServerStopped) { |
| 457 |
t.Errorf("server failed: %v", err) |
| 458 |
} |
| 459 |
}() |
| 460 |
defer server.Stop() |
| 461 |
|
| 462 |
reader := metric.NewManualReader() |
| 463 |
mp := metric.NewMeterProvider(metric.WithReader(reader)) |
| 464 |
|
| 465 |
metricFunc := func(ctx context.Context) []attribute.KeyValue { |
| 466 |
if svc, ok := ctx.Value(rpcServiceKey).(string); ok { |
| 467 |
return []attribute.KeyValue{ |
| 468 |
attribute.String("rpc.service", svc), |
| 469 |
} |
| 470 |
} |
| 471 |
return []attribute.KeyValue{ |
| 472 |
attribute.String("rpc.service", "NOT_FOUND"), |
| 473 |
} |
| 474 |
} |
| 475 |
|
| 476 |
wrappedHandler := &enrichedClientHandler{ |
| 477 |
Handler: otelgrpc.NewClientHandler( |
| 478 |
otelgrpc.WithMeterProvider(mp), |
| 479 |
otelgrpc.WithMetricAttributesFn(metricFunc), |
| 480 |
), |
| 481 |
} |
| 482 |
|
| 483 |
conn, err := grpc.NewClient( |
| 484 |
serverLis.Addr().String(), |
| 485 |
grpc.WithTransportCredentials(insecure.NewCredentials()), |
| 486 |
grpc.WithStatsHandler(wrappedHandler), |
| 487 |
) |
| 488 |
require.NoError(t, err) |
| 489 |
t.Cleanup(func() { conn.Close() }) |
| 490 |
|
| 491 |
client := testpb.NewTestServiceClient(conn) |
| 492 |
_, err = client.EmptyCall(t.Context(), &testpb.Empty{}) |
| 493 |
require.NoError(t, err) |
| 494 |
|
| 495 |
assertAllMetricsHaveLabels(t, reader, clientLabelingDirection, map[string]string{ |
| 496 |
"rpc.service": "orders-service-wrapped", |
| 497 |
}) |
| 498 |
} |
| 499 |
|
| 500 |
|
| 501 |
func TestMetricAttributesFn_ClientAndServerIndependent(t *testing.T) { |
| 502 |
reader := metric.NewManualReader() |
| 503 |
mp := metric.NewMeterProvider(metric.WithReader(reader)) |
| 504 |
|
| 505 |
|
| 506 |
downstreamLis, downstreamServer := startTestServerWithOptions(t, nil) |
| 507 |
defer downstreamServer.Stop() |
| 508 |
|
| 509 |
|
| 510 |
lis, server := startTestServerWithOptions(t, mp, otelgrpc.WithMetricAttributesFn(func(_ context.Context) []attribute.KeyValue { |
| 511 |
return []attribute.KeyValue{ |
| 512 |
attribute.String("origin", "test-origin"), |
| 513 |
attribute.String("tier", "premium"), |
| 514 |
} |
| 515 |
})) |
| 516 |
defer server.Stop() |
| 517 |
|
| 518 |
metricFunc := func(_ context.Context) []attribute.KeyValue { |
| 519 |
return []attribute.KeyValue{ |
| 520 |
attribute.String("client.version", "v1.1.1"), |
| 521 |
attribute.String("client.env", "staging"), |
| 522 |
} |
| 523 |
} |
| 524 |
downstreamClient := createTestClient(t, downstreamLis.Addr().String(), mp, metricFunc) |
| 525 |
|
| 526 |
|
| 527 |
var interceptor grpc.UnaryClientInterceptor = func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { |
| 528 |
if method == "/grpc.testing.TestService/EmptyCall" { |
| 529 |
_, _ = downstreamClient.EmptyCall(ctx, &testpb.Empty{}) |
| 530 |
} |
| 531 |
|
| 532 |
return invoker(ctx, method, req, reply, cc, opts...) |
| 533 |
} |
| 534 |
client := createTestClient(t, lis.Addr().String(), nil, nil, interceptor) |
| 535 |
|
| 536 |
_, err := client.EmptyCall(t.Context(), &testpb.Empty{}) |
| 537 |
require.NoError(t, err) |
| 538 |
|
| 539 |
assertAllMetricsHaveLabels(t, reader, serverLabelingDirection, map[string]string{ |
| 540 |
"origin": "test-origin", |
| 541 |
"tier": "premium", |
| 542 |
}) |
| 543 |
|
| 544 |
assertAllMetricsHaveLabels(t, reader, clientLabelingDirection, map[string]string{ |
| 545 |
"client.version": "v1.1.1", |
| 546 |
"client.env": "staging", |
| 547 |
}) |
| 548 |
|
| 549 |
assertAllMetricsDoNotHaveLabels(t, reader, serverLabelingDirection, map[string]string{ |
| 550 |
"client.version": "v1.1.1", |
| 551 |
"client.env": "staging", |
| 552 |
}) |
| 553 |
|
| 554 |
assertAllMetricsDoNotHaveLabels(t, reader, clientLabelingDirection, map[string]string{ |
| 555 |
"origin": "test-origin", |
| 556 |
"tier": "premium", |
| 557 |
}) |
| 558 |
} |
| 559 |
|
| 560 |
func startTestServerWithOptions(t *testing.T, mp *metric.MeterProvider, opts ...otelgrpc.Option) (net.Listener, *grpc.Server) { |
| 561 |
t.Helper() |
| 562 |
|
| 563 |
lis, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "localhost:0") |
| 564 |
require.NoError(t, err) |
| 565 |
|
| 566 |
var allOpts []otelgrpc.Option |
| 567 |
if mp != nil { |
| 568 |
allOpts = append([]otelgrpc.Option{otelgrpc.WithMeterProvider(mp)}, opts...) |
| 569 |
} |
| 570 |
server := grpc.NewServer( |
| 571 |
grpc.StatsHandler(otelgrpc.NewServerHandler(allOpts...)), |
| 572 |
) |
| 573 |
testpb.RegisterTestServiceServer(server, &testLabelerServer{}) |
| 574 |
|
| 575 |
go func() { |
| 576 |
if err := server.Serve(lis); err != nil && !errors.Is(err, grpc.ErrServerStopped) { |
| 577 |
t.Errorf("server failed: %v", err) |
| 578 |
} |
| 579 |
}() |
| 580 |
|
| 581 |
return lis, server |
| 582 |
} |
| 583 |
|
| 584 |
func createTestClient(t *testing.T, addr string, mp *metric.MeterProvider, metricFunc func(ctx context.Context) []attribute.KeyValue, interceptors ...any) testpb.TestServiceClient { |
| 585 |
t.Helper() |
| 586 |
|
| 587 |
opts := []grpc.DialOption{ |
| 588 |
grpc.WithTransportCredentials(insecure.NewCredentials()), |
| 589 |
} |
| 590 |
|
| 591 |
var unaryInterceptors []grpc.UnaryClientInterceptor |
| 592 |
var streamInterceptors []grpc.StreamClientInterceptor |
| 593 |
|
| 594 |
for _, ic := range interceptors { |
| 595 |
switch v := ic.(type) { |
| 596 |
case grpc.UnaryClientInterceptor: |
| 597 |
unaryInterceptors = append(unaryInterceptors, v) |
| 598 |
case grpc.StreamClientInterceptor: |
| 599 |
streamInterceptors = append(streamInterceptors, v) |
| 600 |
default: |
| 601 |
t.Fatalf("unsupported interceptor type: %T", v) |
| 602 |
} |
| 603 |
} |
| 604 |
|
| 605 |
if len(unaryInterceptors) > 0 { |
| 606 |
opts = append(opts, grpc.WithChainUnaryInterceptor(unaryInterceptors...)) |
| 607 |
} |
| 608 |
if len(streamInterceptors) > 0 { |
| 609 |
opts = append(opts, grpc.WithChainStreamInterceptor(streamInterceptors...)) |
| 610 |
} |
| 611 |
|
| 612 |
if mp != nil && metricFunc != nil { |
| 613 |
opts = append(opts, |
| 614 |
grpc.WithStatsHandler( |
| 615 |
otelgrpc.NewClientHandler( |
| 616 |
otelgrpc.WithMeterProvider(mp), |
| 617 |
otelgrpc.WithMetricAttributesFn(metricFunc), |
| 618 |
), |
| 619 |
), |
| 620 |
) |
| 621 |
} |
| 622 |
|
| 623 |
conn, err := grpc.NewClient(addr, opts...) |
| 624 |
require.NoError(t, err) |
| 625 |
t.Cleanup(func() { conn.Close() }) |
| 626 |
|
| 627 |
return testpb.NewTestServiceClient(conn) |
| 628 |
} |
| 629 |
|
| 630 |
type dpWithAttrs struct { |
| 631 |
metricName string |
| 632 |
attrs map[string]string |
| 633 |
} |
| 634 |
|
| 635 |
func assertAllMetricsHaveLabels(t *testing.T, reader metric.Reader, direction int, expectedLabels map[string]string) { |
| 636 |
t.Helper() |
| 637 |
|
| 638 |
rm := metricdata.ResourceMetrics{} |
| 639 |
err := reader.Collect(t.Context(), &rm) |
| 640 |
require.NoError(t, err) |
| 641 |
|
| 642 |
datapoints := collectDataPointsByMetric(rm, direction) |
| 643 |
assert.NotEmpty(t, datapoints, "no metrics instrumented") |
| 644 |
|
| 645 |
for _, dp := range datapoints { |
| 646 |
for key, val := range expectedLabels { |
| 647 |
attr, ok := dp.attrs[key] |
| 648 |
t.Logf("metric %q has label %q", dp.metricName, attr) |
| 649 |
assert.Truef(t, ok, "metric %q missing label %q", dp.metricName, key) |
| 650 |
if ok { |
| 651 |
assert.Equalf(t, val, attr, "metric %q has incorrect value for label %q: %s", dp.metricName, key, attr) |
| 652 |
} |
| 653 |
} |
| 654 |
} |
| 655 |
} |
| 656 |
|
| 657 |
func assertAllMetricsDoNotHaveLabels(t *testing.T, reader metric.Reader, direction int, notExpectedLabels map[string]string) { |
| 658 |
t.Helper() |
| 659 |
|
| 660 |
rm := metricdata.ResourceMetrics{} |
| 661 |
err := reader.Collect(t.Context(), &rm) |
| 662 |
require.NoError(t, err) |
| 663 |
|
| 664 |
datapoints := collectDataPointsByMetric(rm, direction) |
| 665 |
|
| 666 |
for _, dp := range datapoints { |
| 667 |
for key := range notExpectedLabels { |
| 668 |
_, ok := dp.attrs[key] |
| 669 |
assert.Falsef(t, ok, "metric %q should NOT have label %q", dp.metricName, key) |
| 670 |
} |
| 671 |
} |
| 672 |
} |
| 673 |
|
| 674 |
func collectDataPointsByMetric(rm metricdata.ResourceMetrics, direction int) []dpWithAttrs { |
| 675 |
var result []dpWithAttrs |
| 676 |
|
| 677 |
var prefix string |
| 678 |
switch direction { |
| 679 |
case serverLabelingDirection: |
| 680 |
prefix = "rpc.server." |
| 681 |
case clientLabelingDirection: |
| 682 |
prefix = "rpc.client." |
| 683 |
} |
| 684 |
|
| 685 |
for _, scope := range rm.ScopeMetrics { |
| 686 |
for _, m := range scope.Metrics { |
| 687 |
if !strings.HasPrefix(m.Name, prefix) { |
| 688 |
continue |
| 689 |
} |
| 690 |
|
| 691 |
switch data := m.Data.(type) { |
| 692 |
case metricdata.Histogram[float64]: |
| 693 |
for _, dp := range data.DataPoints { |
| 694 |
result = append(result, dpWithAttrs{ |
| 695 |
metricName: m.Name, |
| 696 |
attrs: extractAttributes(dp.Attributes), |
| 697 |
}) |
| 698 |
} |
| 699 |
case metricdata.Histogram[int64]: |
| 700 |
for _, dp := range data.DataPoints { |
| 701 |
result = append(result, dpWithAttrs{ |
| 702 |
metricName: m.Name, |
| 703 |
attrs: extractAttributes(dp.Attributes), |
| 704 |
}) |
| 705 |
} |
| 706 |
} |
| 707 |
} |
| 708 |
} |
| 709 |
return result |
| 710 |
} |
| 711 |
|
| 712 |
func extractAttributes(attrSet attribute.Set) map[string]string { |
| 713 |
m := make(map[string]string) |
| 714 |
iter := attrSet.Iter() |
| 715 |
for iter.Next() { |
| 716 |
kv := iter.Attribute() |
| 717 |
m[string(kv.Key)] = kv.Value.AsString() |
| 718 |
} |
| 719 |
return m |
| 720 |
} |