| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package observ_test |
| 5 |
|
| 6 |
import ( |
| 7 |
"errors" |
| 8 |
"net/http" |
| 9 |
"strconv" |
| 10 |
"testing" |
| 11 |
|
| 12 |
"github.com/go-logr/logr" |
| 13 |
"github.com/go-logr/logr/testr" |
| 14 |
"github.com/stretchr/testify/assert" |
| 15 |
"github.com/stretchr/testify/require" |
| 16 |
|
| 17 |
"go.opentelemetry.io/otel" |
| 18 |
"go.opentelemetry.io/otel/attribute" |
| 19 |
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal" |
| 20 |
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp/internal/observ" |
| 21 |
"go.opentelemetry.io/otel/internal/global" |
| 22 |
mapi "go.opentelemetry.io/otel/metric" |
| 23 |
"go.opentelemetry.io/otel/sdk/instrumentation" |
| 24 |
"go.opentelemetry.io/otel/sdk/metric" |
| 25 |
"go.opentelemetry.io/otel/sdk/metric/metricdata" |
| 26 |
"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest" |
| 27 |
semconv "go.opentelemetry.io/otel/semconv/v1.40.0" |
| 28 |
"go.opentelemetry.io/otel/semconv/v1.40.0/otelconv" |
| 29 |
) |
| 30 |
|
| 31 |
const ( |
| 32 |
ID = 0 |
| 33 |
ServerAddr = "localhost" |
| 34 |
ServerPort = 4318 |
| 35 |
) |
| 36 |
|
| 37 |
var Endpoint = ServerAddr + ":" + strconv.Itoa(ServerPort) |
| 38 |
|
| 39 |
var Scope = instrumentation.Scope{ |
| 40 |
Name: observ.ScopeName, |
| 41 |
Version: observ.Version, |
| 42 |
SchemaURL: observ.SchemaURL, |
| 43 |
} |
| 44 |
|
| 45 |
type errMeterProvider struct { |
| 46 |
mapi.MeterProvider |
| 47 |
|
| 48 |
err error |
| 49 |
} |
| 50 |
|
| 51 |
func (m *errMeterProvider) Meter(string, ...mapi.MeterOption) mapi.Meter { |
| 52 |
return &errMeter{err: m.err} |
| 53 |
} |
| 54 |
|
| 55 |
type errMeter struct { |
| 56 |
mapi.Meter |
| 57 |
|
| 58 |
err error |
| 59 |
} |
| 60 |
|
| 61 |
func (m *errMeter) Int64UpDownCounter(string, ...mapi.Int64UpDownCounterOption) (mapi.Int64UpDownCounter, error) { |
| 62 |
return nil, m.err |
| 63 |
} |
| 64 |
|
| 65 |
func (m *errMeter) Int64Counter(string, ...mapi.Int64CounterOption) (mapi.Int64Counter, error) { |
| 66 |
return nil, m.err |
| 67 |
} |
| 68 |
|
| 69 |
func (m *errMeter) Float64Histogram(string, ...mapi.Float64HistogramOption) (mapi.Float64Histogram, error) { |
| 70 |
return nil, m.err |
| 71 |
} |
| 72 |
|
| 73 |
func TestNewInstrumentationObservabilityErrors(t *testing.T) { |
| 74 |
orig := otel.GetMeterProvider() |
| 75 |
t.Cleanup(func() { otel.SetMeterProvider(orig) }) |
| 76 |
mp := &errMeterProvider{err: assert.AnError} |
| 77 |
otel.SetMeterProvider(mp) |
| 78 |
|
| 79 |
t.Setenv("OTEL_GO_X_OBSERVABILITY", "true") |
| 80 |
|
| 81 |
_, err := observ.NewInstrumentation(ID, Endpoint) |
| 82 |
require.ErrorIs(t, err, assert.AnError, "new instrument errors") |
| 83 |
|
| 84 |
assert.ErrorContains(t, err, "inflight metric") |
| 85 |
assert.ErrorContains(t, err, "span exported metric") |
| 86 |
assert.ErrorContains(t, err, "operation duration metric") |
| 87 |
} |
| 88 |
|
| 89 |
func TestNewInstrumentationObservabilityDisabled(t *testing.T) { |
| 90 |
// Do not set OTEL_GO_X_OBSERVABILITY. |
| 91 |
got, err := observ.NewInstrumentation(ID, Endpoint) |
| 92 |
assert.NoError(t, err) |
| 93 |
assert.Nil(t, got) |
| 94 |
} |
| 95 |
|
| 96 |
func setup(t *testing.T) (*observ.Instrumentation, func() metricdata.ScopeMetrics) { |
| 97 |
t.Helper() |
| 98 |
|
| 99 |
t.Setenv("OTEL_GO_X_OBSERVABILITY", "true") |
| 100 |
|
| 101 |
original := otel.GetMeterProvider() |
| 102 |
t.Cleanup(func() { otel.SetMeterProvider(original) }) |
| 103 |
|
| 104 |
r := metric.NewManualReader() |
| 105 |
mp := metric.NewMeterProvider(metric.WithReader(r)) |
| 106 |
otel.SetMeterProvider(mp) |
| 107 |
|
| 108 |
inst, err := observ.NewInstrumentation(ID, Endpoint) |
| 109 |
require.NoError(t, err) |
| 110 |
require.NotNil(t, inst) |
| 111 |
|
| 112 |
return inst, func() metricdata.ScopeMetrics { |
| 113 |
var rm metricdata.ResourceMetrics |
| 114 |
require.NoError(t, r.Collect(t.Context(), &rm)) |
| 115 |
|
| 116 |
require.Len(t, rm.ScopeMetrics, 1) |
| 117 |
return rm.ScopeMetrics[0] |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
func baseAttrs(err error) []attribute.KeyValue { |
| 122 |
attrs := []attribute.KeyValue{ |
| 123 |
semconv.OTelComponentName(observ.ComponentName(ID)), |
| 124 |
semconv.OTelComponentTypeOtlpHTTPSpanExporter, |
| 125 |
semconv.ServerAddress(ServerAddr), |
| 126 |
semconv.ServerPort(ServerPort), |
| 127 |
} |
| 128 |
if err != nil { |
| 129 |
attrs = append(attrs, semconv.ErrorType(err)) |
| 130 |
} |
| 131 |
return attrs |
| 132 |
} |
| 133 |
|
| 134 |
func set(err error) attribute.Set { |
| 135 |
return attribute.NewSet(baseAttrs(err)...) |
| 136 |
} |
| 137 |
|
| 138 |
func spanInflight() metricdata.Metrics { |
| 139 |
return metricdata.Metrics{ |
| 140 |
Name: otelconv.SDKExporterSpanInflight{}.Name(), |
| 141 |
Description: otelconv.SDKExporterSpanInflight{}.Description(), |
| 142 |
Unit: otelconv.SDKExporterSpanInflight{}.Unit(), |
| 143 |
Data: metricdata.Sum[int64]{ |
| 144 |
Temporality: metricdata.CumulativeTemporality, |
| 145 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 146 |
{Attributes: set(nil), Value: 0}, |
| 147 |
}, |
| 148 |
}, |
| 149 |
} |
| 150 |
} |
| 151 |
|
| 152 |
func spanExported(success, total int64, err error) metricdata.Metrics { |
| 153 |
dp := []metricdata.DataPoint[int64]{ |
| 154 |
{Attributes: set(nil), Value: success}, |
| 155 |
} |
| 156 |
if err != nil { |
| 157 |
dp = append(dp, metricdata.DataPoint[int64]{ |
| 158 |
Attributes: set(err), |
| 159 |
Value: total - success, |
| 160 |
}) |
| 161 |
} |
| 162 |
return metricdata.Metrics{ |
| 163 |
Name: otelconv.SDKExporterSpanExported{}.Name(), |
| 164 |
Description: otelconv.SDKExporterSpanExported{}.Description(), |
| 165 |
Unit: otelconv.SDKExporterSpanExported{}.Unit(), |
| 166 |
Data: metricdata.Sum[int64]{ |
| 167 |
Temporality: metricdata.CumulativeTemporality, |
| 168 |
IsMonotonic: true, |
| 169 |
DataPoints: dp, |
| 170 |
}, |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
func operationDuration(err error, statusCode int) metricdata.Metrics { |
| 175 |
httpSet := func(err error, statusCode int) attribute.Set { |
| 176 |
attrs := baseAttrs(err) |
| 177 |
attrs = append(attrs, semconv.HTTPResponseStatusCode(statusCode)) |
| 178 |
return attribute.NewSet(attrs...) |
| 179 |
} |
| 180 |
return metricdata.Metrics{ |
| 181 |
Name: otelconv.SDKExporterOperationDuration{}.Name(), |
| 182 |
Description: otelconv.SDKExporterOperationDuration{}.Description(), |
| 183 |
Unit: otelconv.SDKExporterOperationDuration{}.Unit(), |
| 184 |
Data: metricdata.Histogram[float64]{ |
| 185 |
Temporality: metricdata.CumulativeTemporality, |
| 186 |
DataPoints: []metricdata.HistogramDataPoint[float64]{ |
| 187 |
{Attributes: httpSet(err, statusCode)}, |
| 188 |
}, |
| 189 |
}, |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
func assertMetrics(t *testing.T, got metricdata.ScopeMetrics, spans, success int64, err error, statusCode int) { |
| 194 |
t.Helper() |
| 195 |
|
| 196 |
assert.Equal(t, Scope, got.Scope, "unexpected scope") |
| 197 |
|
| 198 |
m := got.Metrics |
| 199 |
require.Len(t, m, 3, "expected 3 metrics") |
| 200 |
|
| 201 |
o := metricdatatest.IgnoreTimestamp() |
| 202 |
want := spanInflight() |
| 203 |
metricdatatest.AssertEqual(t, want, m[0], o) |
| 204 |
|
| 205 |
want = spanExported(success, spans, err) |
| 206 |
metricdatatest.AssertEqual(t, want, m[1], o) |
| 207 |
|
| 208 |
want = operationDuration(err, statusCode) |
| 209 |
metricdatatest.AssertEqual(t, want, m[2], o, metricdatatest.IgnoreValue()) |
| 210 |
} |
| 211 |
|
| 212 |
func TestInstrumentationExportSpans(t *testing.T) { |
| 213 |
inst, collect := setup(t) |
| 214 |
|
| 215 |
const n = 10 |
| 216 |
inst.ExportSpans(t.Context(), n).End(nil, http.StatusOK) |
| 217 |
|
| 218 |
assertMetrics(t, collect(), n, n, nil, http.StatusOK) |
| 219 |
} |
| 220 |
|
| 221 |
func TestInstrumentationExportSpansAllErrored(t *testing.T) { |
| 222 |
inst, collect := setup(t) |
| 223 |
|
| 224 |
const n = 10 |
| 225 |
err := errors.New("http error") |
| 226 |
inst.ExportSpans(t.Context(), n).End(err, http.StatusInternalServerError) |
| 227 |
|
| 228 |
const success = 0 |
| 229 |
assertMetrics(t, collect(), n, success, err, http.StatusInternalServerError) |
| 230 |
} |
| 231 |
|
| 232 |
func TestInstrumentationExportSpansPartialErrored(t *testing.T) { |
| 233 |
inst, collect := setup(t) |
| 234 |
|
| 235 |
const n = 10 |
| 236 |
const success = n - 5 |
| 237 |
|
| 238 |
err := errors.New("partial failure") |
| 239 |
err = errors.Join(err, &internal.PartialSuccess{RejectedItems: 5}) |
| 240 |
inst.ExportSpans(t.Context(), n).End(err, http.StatusOK) |
| 241 |
|
| 242 |
assertMetrics(t, collect(), n, success, err, http.StatusOK) |
| 243 |
} |
| 244 |
|
| 245 |
func TestInstrumentationExportSpansInvalidPartialErrored(t *testing.T) { |
| 246 |
inst, collect := setup(t) |
| 247 |
|
| 248 |
const n = 10 |
| 249 |
pErr := &internal.PartialSuccess{RejectedItems: -5} |
| 250 |
err := errors.Join(errors.New("temporary"), pErr) |
| 251 |
inst.ExportSpans(t.Context(), n).End(err, http.StatusServiceUnavailable) |
| 252 |
|
| 253 |
// Round -5 to 0. |
| 254 |
success := int64(n) // (n - 0) |
| 255 |
assertMetrics(t, collect(), n, success, err, http.StatusServiceUnavailable) |
| 256 |
|
| 257 |
// Note: the metrics are cumulative, so account for the previous |
| 258 |
// ExportSpans call. |
| 259 |
pErr.RejectedItems = n + 5 |
| 260 |
inst.ExportSpans(t.Context(), n).End(err, http.StatusServiceUnavailable) |
| 261 |
|
| 262 |
// Round n+5 to n. |
| 263 |
success += 0 // success + (n - n) |
| 264 |
assertMetrics(t, collect(), n+n, success, err, http.StatusServiceUnavailable) |
| 265 |
} |
| 266 |
|
| 267 |
func TestBaseAttrs(t *testing.T) { |
| 268 |
tests := []struct { |
| 269 |
endpoint string |
| 270 |
host string |
| 271 |
port int |
| 272 |
}{ |
| 273 |
// Empty. |
| 274 |
{endpoint: "", host: "", port: -1}, |
| 275 |
|
| 276 |
// Only a port. |
| 277 |
{endpoint: ":4318", host: "", port: 4318}, |
| 278 |
|
| 279 |
// Hostname. |
| 280 |
{endpoint: "localhost:4318", host: "localhost", port: 4318}, |
| 281 |
{endpoint: "localhost", host: "localhost", port: -1}, |
| 282 |
|
| 283 |
// IPv4 address. |
| 284 |
{endpoint: "127.0.0.1:4318", host: "127.0.0.1", port: 4318}, |
| 285 |
{endpoint: "127.0.0.1", host: "127.0.0.1", port: -1}, |
| 286 |
|
| 287 |
// IPv6 address. |
| 288 |
{endpoint: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", host: "2001:db8:85a3::8a2e:370:7334", port: -1}, |
| 289 |
{endpoint: "2001:db8:85a3:0:0:8a2e:370:7334", host: "2001:db8:85a3::8a2e:370:7334", port: -1}, |
| 290 |
{endpoint: "2001:db8:85a3::8a2e:370:7334", host: "2001:db8:85a3::8a2e:370:7334", port: -1}, |
| 291 |
{endpoint: "[2001:db8:85a3::8a2e:370:7334]", host: "2001:db8:85a3::8a2e:370:7334", port: -1}, |
| 292 |
{endpoint: "[::1]:9090", host: "::1", port: 9090}, |
| 293 |
|
| 294 |
// Port edge cases. |
| 295 |
{endpoint: "example.com:0", host: "example.com", port: 0}, |
| 296 |
{endpoint: "example.com:65535", host: "example.com", port: 65535}, |
| 297 |
|
| 298 |
// Case insensitive. |
| 299 |
{endpoint: "ExAmPlE.COM:8080", host: "ExAmPlE.COM", port: 8080}, |
| 300 |
} |
| 301 |
for _, tt := range tests { |
| 302 |
got := observ.BaseAttrs(ID, tt.endpoint) |
| 303 |
want := []attribute.KeyValue{ |
| 304 |
semconv.OTelComponentName(observ.ComponentName(ID)), |
| 305 |
semconv.OTelComponentTypeOtlpHTTPSpanExporter, |
| 306 |
} |
| 307 |
|
| 308 |
if tt.host != "" { |
| 309 |
want = append(want, semconv.ServerAddress(tt.host)) |
| 310 |
} |
| 311 |
if tt.port != -1 { |
| 312 |
want = append(want, semconv.ServerPort(tt.port)) |
| 313 |
} |
| 314 |
assert.Equal(t, want, got) |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
type logSink struct { |
| 319 |
logr.LogSink |
| 320 |
|
| 321 |
level int |
| 322 |
msg string |
| 323 |
keysAndValues []any |
| 324 |
} |
| 325 |
|
| 326 |
func (*logSink) Enabled(int) bool { return true } |
| 327 |
|
| 328 |
func (l *logSink) Info(level int, msg string, keysAndValues ...any) { |
| 329 |
l.level, l.msg, l.keysAndValues = level, msg, keysAndValues |
| 330 |
l.LogSink.Info(level, msg, keysAndValues...) |
| 331 |
} |
| 332 |
|
| 333 |
func TestBaseAttrsError(t *testing.T) { |
| 334 |
endpoints := []string{ |
| 335 |
"example.com:invalid", // Non-numeric port. |
| 336 |
"example.com:8080:9090", // Multiple colons in port. |
| 337 |
"example.com:99999", // Port out of range. |
| 338 |
"example.com:-1", // Port out of range. |
| 339 |
} |
| 340 |
for _, endpoint := range endpoints { |
| 341 |
l := &logSink{LogSink: testr.New(t).GetSink()} |
| 342 |
t.Cleanup(func(orig logr.Logger) func() { |
| 343 |
global.SetLogger(logr.New(l)) |
| 344 |
return func() { global.SetLogger(orig) } |
| 345 |
}(global.GetLogger())) |
| 346 |
|
| 347 |
// Set the logger as global so BaseAttrs can log the error. |
| 348 |
got := observ.BaseAttrs(ID, endpoint) |
| 349 |
want := []attribute.KeyValue{ |
| 350 |
semconv.OTelComponentName(observ.ComponentName(ID)), |
| 351 |
semconv.OTelComponentTypeOtlpHTTPSpanExporter, |
| 352 |
} |
| 353 |
assert.Equal(t, want, got) |
| 354 |
|
| 355 |
assert.Equal(t, 8, l.level, "expected Debug log level") |
| 356 |
assert.Equal(t, "failed to parse endpoint", l.msg) |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
func BenchmarkInstrumentationExportSpans(b *testing.B) { |
| 361 |
setup := func(b *testing.B) *observ.Instrumentation { |
| 362 |
b.Helper() |
| 363 |
b.Setenv("OTEL_GO_X_OBSERVABILITY", "true") |
| 364 |
inst, err := observ.NewInstrumentation(ID, Endpoint) |
| 365 |
if err != nil { |
| 366 |
b.Fatalf("failed to create instrumentation: %v", err) |
| 367 |
} |
| 368 |
return inst |
| 369 |
} |
| 370 |
|
| 371 |
run := func(err error, statusCode int) func(*testing.B) { |
| 372 |
return func(b *testing.B) { |
| 373 |
inst := setup(b) |
| 374 |
b.ReportAllocs() |
| 375 |
b.ResetTimer() |
| 376 |
for b.Loop() { |
| 377 |
inst.ExportSpans(b.Context(), 10).End(err, statusCode) |
| 378 |
} |
| 379 |
} |
| 380 |
} |
| 381 |
|
| 382 |
b.Run("NoError", run(nil, http.StatusOK)) |
| 383 |
err := &internal.PartialSuccess{RejectedItems: 6} |
| 384 |
b.Run("PartialError", run(err, http.StatusOK)) |
| 385 |
b.Run("FullError", run(assert.AnError, http.StatusInternalServerError)) |
| 386 |
} |