| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package observ |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
"net/http" |
| 9 |
"testing" |
| 10 |
|
| 11 |
"github.com/go-logr/logr" |
| 12 |
"github.com/go-logr/logr/testr" |
| 13 |
"github.com/stretchr/testify/assert" |
| 14 |
"github.com/stretchr/testify/require" |
| 15 |
|
| 16 |
"go.opentelemetry.io/otel" |
| 17 |
"go.opentelemetry.io/otel/attribute" |
| 18 |
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp/internal" |
| 19 |
"go.opentelemetry.io/otel/internal/global" |
| 20 |
mapi "go.opentelemetry.io/otel/metric" |
| 21 |
"go.opentelemetry.io/otel/metric/embedded" |
| 22 |
"go.opentelemetry.io/otel/sdk/instrumentation" |
| 23 |
"go.opentelemetry.io/otel/sdk/metric" |
| 24 |
"go.opentelemetry.io/otel/sdk/metric/metricdata" |
| 25 |
"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest" |
| 26 |
semconv "go.opentelemetry.io/otel/semconv/v1.40.0" |
| 27 |
"go.opentelemetry.io/otel/semconv/v1.40.0/otelconv" |
| 28 |
) |
| 29 |
|
| 30 |
const ( |
| 31 |
ID = 0 |
| 32 |
TARGET = "localhost:8080" |
| 33 |
) |
| 34 |
|
| 35 |
type errMeterProvider struct { |
| 36 |
mapi.MeterProvider |
| 37 |
err error |
| 38 |
} |
| 39 |
|
| 40 |
func (m *errMeterProvider) Meter(string, ...mapi.MeterOption) mapi.Meter { |
| 41 |
return &errMeter{err: m.err} |
| 42 |
} |
| 43 |
|
| 44 |
type errMeter struct { |
| 45 |
mapi.Meter |
| 46 |
err error |
| 47 |
} |
| 48 |
|
| 49 |
func (m *errMeter) Int64UpDownCounter(string, ...mapi.Int64UpDownCounterOption) (mapi.Int64UpDownCounter, error) { |
| 50 |
return nil, m.err |
| 51 |
} |
| 52 |
|
| 53 |
func (m *errMeter) Int64Counter(string, ...mapi.Int64CounterOption) (mapi.Int64Counter, error) { |
| 54 |
return nil, m.err |
| 55 |
} |
| 56 |
|
| 57 |
func (m *errMeter) Float64Histogram(string, ...mapi.Float64HistogramOption) (mapi.Float64Histogram, error) { |
| 58 |
return nil, m.err |
| 59 |
} |
| 60 |
|
| 61 |
func TestNewInstrumentationObservabilityErrors(t *testing.T) { |
| 62 |
orig := otel.GetMeterProvider() |
| 63 |
t.Cleanup(func() { otel.SetMeterProvider(orig) }) |
| 64 |
mp := &errMeterProvider{err: assert.AnError} |
| 65 |
otel.SetMeterProvider(mp) |
| 66 |
|
| 67 |
t.Setenv("OTEL_GO_X_OBSERVABILITY", "true") |
| 68 |
|
| 69 |
_, err := NewInstrumentation(ID, TARGET) |
| 70 |
require.ErrorIs(t, err, assert.AnError, "new instrument errors") |
| 71 |
|
| 72 |
assert.ErrorContains(t, err, "inflight metric") |
| 73 |
assert.ErrorContains(t, err, "exported metric") |
| 74 |
assert.ErrorContains(t, err, "operation duration metric") |
| 75 |
} |
| 76 |
|
| 77 |
func TestNewInstrumentationObservabilityDisabled(t *testing.T) { |
| 78 |
// Do not set OTEL_GO_X_OBSERVABILITY. |
| 79 |
got, err := NewInstrumentation(ID, TARGET) |
| 80 |
assert.NoError(t, err) |
| 81 |
assert.Nil(t, got) |
| 82 |
} |
| 83 |
|
| 84 |
func set(err error) attribute.Set { |
| 85 |
attrs := []attribute.KeyValue{ |
| 86 |
semconv.OTelComponentName(GetComponentName(ID)), |
| 87 |
semconv.OTelComponentTypeKey.String(string(otelconv.ComponentTypeOtlpHTTPLogExporter)), |
| 88 |
} |
| 89 |
attrs = append(attrs, ServerAddrAttrs(TARGET)...) |
| 90 |
if err != nil { |
| 91 |
attrs = append(attrs, semconv.ErrorType(err)) |
| 92 |
} |
| 93 |
return attribute.NewSet(attrs...) |
| 94 |
} |
| 95 |
|
| 96 |
func inflightMetric() metricdata.Metrics { |
| 97 |
inflight := otelconv.SDKExporterLogInflight{} |
| 98 |
|
| 99 |
return metricdata.Metrics{ |
| 100 |
Name: inflight.Name(), |
| 101 |
Description: inflight.Description(), |
| 102 |
Unit: inflight.Unit(), |
| 103 |
Data: metricdata.Sum[int64]{ |
| 104 |
Temporality: metricdata.CumulativeTemporality, |
| 105 |
DataPoints: []metricdata.DataPoint[int64]{ |
| 106 |
{ |
| 107 |
Attributes: set(nil), |
| 108 |
Value: 0, |
| 109 |
}, |
| 110 |
}, |
| 111 |
}, |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
func exportedMetric(err error, total, success int64) metricdata.Metrics { |
| 116 |
dp := []metricdata.DataPoint[int64]{ |
| 117 |
{ |
| 118 |
Attributes: set(nil), |
| 119 |
Value: success, |
| 120 |
}, |
| 121 |
} |
| 122 |
|
| 123 |
if err != nil { |
| 124 |
dp = append(dp, metricdata.DataPoint[int64]{ |
| 125 |
Attributes: set(err), |
| 126 |
Value: total - success, |
| 127 |
}) |
| 128 |
} |
| 129 |
|
| 130 |
exported := otelconv.SDKExporterLogExported{} |
| 131 |
|
| 132 |
return metricdata.Metrics{ |
| 133 |
Name: exported.Name(), |
| 134 |
Description: exported.Description(), |
| 135 |
Unit: exported.Unit(), |
| 136 |
Data: metricdata.Sum[int64]{ |
| 137 |
Temporality: metricdata.CumulativeTemporality, |
| 138 |
IsMonotonic: true, |
| 139 |
DataPoints: dp, |
| 140 |
}, |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
func operationDurationMetric(err error, code int) metricdata.Metrics { |
| 145 |
attrs := []attribute.KeyValue{ |
| 146 |
semconv.OTelComponentName(GetComponentName(ID)), |
| 147 |
semconv.OTelComponentTypeOtlpHTTPLogExporter, |
| 148 |
semconv.HTTPResponseStatusCode(code), |
| 149 |
} |
| 150 |
attrs = append(attrs, ServerAddrAttrs(TARGET)...) |
| 151 |
if err != nil { |
| 152 |
attrs = append(attrs, semconv.ErrorType(err)) |
| 153 |
} |
| 154 |
|
| 155 |
operation := otelconv.SDKExporterOperationDuration{} |
| 156 |
|
| 157 |
return metricdata.Metrics{ |
| 158 |
Name: operation.Name(), |
| 159 |
Description: operation.Description(), |
| 160 |
Unit: operation.Unit(), |
| 161 |
Data: metricdata.Histogram[float64]{ |
| 162 |
Temporality: metricdata.CumulativeTemporality, |
| 163 |
DataPoints: []metricdata.HistogramDataPoint[float64]{ |
| 164 |
{ |
| 165 |
Attributes: attribute.NewSet(attrs...), |
| 166 |
}, |
| 167 |
}, |
| 168 |
}, |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
func setup(t *testing.T) (*Instrumentation, func() metricdata.ScopeMetrics) { |
| 173 |
t.Helper() |
| 174 |
t.Setenv("OTEL_GO_X_OBSERVABILITY", "true") |
| 175 |
original := otel.GetMeterProvider() |
| 176 |
t.Cleanup(func() { |
| 177 |
otel.SetMeterProvider(original) |
| 178 |
}) |
| 179 |
|
| 180 |
r := metric.NewManualReader() |
| 181 |
mp := metric.NewMeterProvider(metric.WithReader(r)) |
| 182 |
otel.SetMeterProvider(mp) |
| 183 |
|
| 184 |
inst, err := NewInstrumentation(ID, TARGET) |
| 185 |
require.NoError(t, err) |
| 186 |
require.NotNil(t, inst) |
| 187 |
|
| 188 |
return inst, func() metricdata.ScopeMetrics { |
| 189 |
var rm metricdata.ResourceMetrics |
| 190 |
require.NoError(t, r.Collect(t.Context(), &rm)) |
| 191 |
require.Len(t, rm.ScopeMetrics, 1) |
| 192 |
return rm.ScopeMetrics[0] |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
var Scope = instrumentation.Scope{ |
| 197 |
Name: ScopeName, |
| 198 |
Version: Version, |
| 199 |
SchemaURL: semconv.SchemaURL, |
| 200 |
} |
| 201 |
|
| 202 |
func assertMetrics( |
| 203 |
t *testing.T, |
| 204 |
got metricdata.ScopeMetrics, |
| 205 |
count int64, |
| 206 |
success int64, |
| 207 |
err error, |
| 208 |
code int, |
| 209 |
) { |
| 210 |
t.Helper() |
| 211 |
assert.Equal(t, Scope, got.Scope, "unexpected scope") |
| 212 |
m := got.Metrics |
| 213 |
require.Len(t, m, 3, "expected 3 metrics") |
| 214 |
|
| 215 |
o := metricdatatest.IgnoreTimestamp() |
| 216 |
want := inflightMetric() |
| 217 |
metricdatatest.AssertEqual(t, want, m[0], o) |
| 218 |
|
| 219 |
want = exportedMetric(err, count, success) |
| 220 |
metricdatatest.AssertEqual(t, want, m[1], o) |
| 221 |
|
| 222 |
want = operationDurationMetric(err, code) |
| 223 |
metricdatatest.AssertEqual(t, want, m[2], metricdatatest.IgnoreValue(), o) |
| 224 |
} |
| 225 |
|
| 226 |
func TestInstrumentationExportedLogs(t *testing.T) { |
| 227 |
inst, collect := setup(t) |
| 228 |
const n = 10 |
| 229 |
inst.ExportLogs(t.Context(), n).End(nil, http.StatusOK) |
| 230 |
assertMetrics(t, collect(), n, n, nil, http.StatusOK) |
| 231 |
} |
| 232 |
|
| 233 |
func TestInstrumentationExportLogsPartialErrors(t *testing.T) { |
| 234 |
inst, collect := setup(t) |
| 235 |
const n = 10 |
| 236 |
const success = 5 |
| 237 |
|
| 238 |
err := internal.PartialSuccess{RejectedItems: n - success} |
| 239 |
inst.ExportLogs(t.Context(), n).End(err, http.StatusPartialContent) |
| 240 |
|
| 241 |
assertMetrics(t, collect(), n, success, err, http.StatusPartialContent) |
| 242 |
} |
| 243 |
|
| 244 |
func TestInstrumentationExportLogAllErrors(t *testing.T) { |
| 245 |
inst, collect := setup(t) |
| 246 |
const n = 10 |
| 247 |
const success = 0 |
| 248 |
|
| 249 |
inst.ExportLogs(t.Context(), n).End(assert.AnError, http.StatusUnauthorized) |
| 250 |
|
| 251 |
assertMetrics(t, collect(), n, success, assert.AnError, http.StatusUnauthorized) |
| 252 |
} |
| 253 |
|
| 254 |
func TestInstrumentationExportLogsInvalidPartialErrored(t *testing.T) { |
| 255 |
inst, collect := setup(t) |
| 256 |
const n = 10 |
| 257 |
|
| 258 |
err := internal.PartialSuccess{RejectedItems: -5} |
| 259 |
inst.ExportLogs(t.Context(), n).End(err, http.StatusPartialContent) |
| 260 |
|
| 261 |
success := n |
| 262 |
assertMetrics(t, collect(), n, int64(success), err, http.StatusPartialContent) |
| 263 |
|
| 264 |
err.RejectedItems = n + 5 |
| 265 |
inst.ExportLogs(t.Context(), n).End(err, http.StatusPartialContent) |
| 266 |
|
| 267 |
success += 0 |
| 268 |
assertMetrics(t, collect(), n+n, int64(success), err, http.StatusPartialContent) |
| 269 |
} |
| 270 |
|
| 271 |
type spy struct { |
| 272 |
enabled bool |
| 273 |
called *bool |
| 274 |
panicMsg string |
| 275 |
} |
| 276 |
|
| 277 |
func (s spy) Enabled(context.Context) bool { return s.enabled } |
| 278 |
|
| 279 |
func (s spy) markCalled() { |
| 280 |
if !s.enabled { |
| 281 |
panic(s.panicMsg) |
| 282 |
} |
| 283 |
if s.called != nil { |
| 284 |
*s.called = true |
| 285 |
} |
| 286 |
} |
| 287 |
|
| 288 |
type upDownCounterSpy struct { |
| 289 |
embedded.Int64UpDownCounter |
| 290 |
spy |
| 291 |
} |
| 292 |
|
| 293 |
func (c upDownCounterSpy) Add(context.Context, int64, ...mapi.AddOption) { c.markCalled() } |
| 294 |
|
| 295 |
type counterSpy struct { |
| 296 |
embedded.Int64Counter |
| 297 |
spy |
| 298 |
} |
| 299 |
|
| 300 |
func (c counterSpy) Add(context.Context, int64, ...mapi.AddOption) { c.markCalled() } |
| 301 |
|
| 302 |
type histogramSpy struct { |
| 303 |
embedded.Float64Histogram |
| 304 |
spy |
| 305 |
} |
| 306 |
|
| 307 |
func (h histogramSpy) Record(context.Context, float64, ...mapi.RecordOption) { h.markCalled() } |
| 308 |
|
| 309 |
func TestEndSkipsDisabledInstruments(t *testing.T) { |
| 310 |
const n = 10 |
| 311 |
|
| 312 |
tests := []struct { |
| 313 |
name string |
| 314 |
disable string // "inflight" | "exported" | "duration" | "all" |
| 315 |
wantInflight bool |
| 316 |
wantExported bool |
| 317 |
wantDuration bool |
| 318 |
}{ |
| 319 |
{name: "inflight disabled", disable: "inflight", wantExported: true, wantDuration: true}, |
| 320 |
{name: "exported disabled", disable: "exported", wantInflight: true, wantDuration: true}, |
| 321 |
{name: "duration disabled", disable: "duration", wantInflight: true, wantExported: true}, |
| 322 |
{name: "all disabled", disable: "all"}, |
| 323 |
} |
| 324 |
|
| 325 |
for _, tt := range tests { |
| 326 |
t.Run(tt.name, func(t *testing.T) { |
| 327 |
var inflightCalled, exportedCalled, durationCalled bool |
| 328 |
|
| 329 |
inst := &Instrumentation{ |
| 330 |
inflightMetric: upDownCounterSpy{ |
| 331 |
spy: spy{ |
| 332 |
enabled: tt.disable != "inflight" && tt.disable != "all", |
| 333 |
called: &inflightCalled, |
| 334 |
panicMsg: "inflight Add called while disabled", |
| 335 |
}, |
| 336 |
}, |
| 337 |
exportedMetric: counterSpy{ |
| 338 |
spy: spy{ |
| 339 |
enabled: tt.disable != "exported" && tt.disable != "all", |
| 340 |
called: &exportedCalled, |
| 341 |
panicMsg: "exported Add called while disabled", |
| 342 |
}, |
| 343 |
}, |
| 344 |
operationDuration: histogramSpy{ |
| 345 |
spy: spy{ |
| 346 |
enabled: tt.disable != "duration" && tt.disable != "all", |
| 347 |
called: &durationCalled, |
| 348 |
panicMsg: "duration Record called while disabled", |
| 349 |
}, |
| 350 |
}, |
| 351 |
} |
| 352 |
|
| 353 |
// If your Enabled() guards are missing, this will panic in the disabled case. |
| 354 |
inst.ExportLogs(t.Context(), n).End(nil, http.StatusOK) |
| 355 |
|
| 356 |
require.Equal(t, tt.wantInflight, inflightCalled) |
| 357 |
require.Equal(t, tt.wantExported, exportedCalled) |
| 358 |
require.Equal(t, tt.wantDuration, durationCalled) |
| 359 |
}) |
| 360 |
} |
| 361 |
} |
| 362 |
|
| 363 |
func TestSetPresetAttrs(t *testing.T) { |
| 364 |
tests := []struct { |
| 365 |
endpoint string |
| 366 |
host string |
| 367 |
port int |
| 368 |
}{ |
| 369 |
// Empty. |
| 370 |
{endpoint: "", host: "", port: -1}, |
| 371 |
|
| 372 |
// Only a port. |
| 373 |
{endpoint: ":4318", host: "", port: 4318}, |
| 374 |
|
| 375 |
// Hostname. |
| 376 |
{endpoint: "localhost:4318", host: "localhost", port: 4318}, |
| 377 |
{endpoint: "localhost", host: "localhost", port: -1}, |
| 378 |
|
| 379 |
// IPv4 address. |
| 380 |
{endpoint: "127.0.0.1:4318", host: "127.0.0.1", port: 4318}, |
| 381 |
{endpoint: "127.0.0.1", host: "127.0.0.1", port: -1}, |
| 382 |
|
| 383 |
// IPv6 address. |
| 384 |
{endpoint: "2001:0db8:85a3:0000:0000:8a2e:0370:7334", host: "2001:db8:85a3::8a2e:370:7334", port: -1}, |
| 385 |
{endpoint: "2001:db8:85a3:0:0:8a2e:370:7334", host: "2001:db8:85a3::8a2e:370:7334", port: -1}, |
| 386 |
{endpoint: "2001:db8:85a3::8a2e:370:7334", host: "2001:db8:85a3::8a2e:370:7334", port: -1}, |
| 387 |
{endpoint: "[2001:db8:85a3::8a2e:370:7334]", host: "2001:db8:85a3::8a2e:370:7334", port: -1}, |
| 388 |
{endpoint: "[::1]:9090", host: "::1", port: 9090}, |
| 389 |
|
| 390 |
// Port edge cases. |
| 391 |
{endpoint: "example.com:0", host: "example.com", port: 0}, |
| 392 |
{endpoint: "example.com:65535", host: "example.com", port: 65535}, |
| 393 |
|
| 394 |
// Case insensitive. |
| 395 |
{endpoint: "ExAmPlE.COM:8080", host: "ExAmPlE.COM", port: 8080}, |
| 396 |
} |
| 397 |
for _, tt := range tests { |
| 398 |
got := setPresetAttrs(GetComponentName(ID), tt.endpoint) |
| 399 |
want := []attribute.KeyValue{ |
| 400 |
semconv.OTelComponentName(GetComponentName(ID)), |
| 401 |
semconv.OTelComponentTypeOtlpHTTPLogExporter, |
| 402 |
} |
| 403 |
|
| 404 |
if tt.host != "" { |
| 405 |
want = append(want, semconv.ServerAddress(tt.host)) |
| 406 |
} |
| 407 |
if tt.port != -1 { |
| 408 |
want = append(want, semconv.ServerPort(tt.port)) |
| 409 |
} |
| 410 |
assert.Equal(t, want, got) |
| 411 |
} |
| 412 |
} |
| 413 |
|
| 414 |
type logSink struct { |
| 415 |
logr.LogSink |
| 416 |
|
| 417 |
level int |
| 418 |
msg string |
| 419 |
keysAndValues []any |
| 420 |
} |
| 421 |
|
| 422 |
func (*logSink) Enabled(int) bool { return true } |
| 423 |
|
| 424 |
func (l *logSink) Info(level int, msg string, keysAndValues ...any) { |
| 425 |
l.level, l.msg, l.keysAndValues = level, msg, keysAndValues |
| 426 |
l.LogSink.Info(level, msg, keysAndValues...) |
| 427 |
} |
| 428 |
|
| 429 |
func TestSetPresetAttrsError(t *testing.T) { |
| 430 |
endpoints := []string{ |
| 431 |
"example.com:invalid", // Non-numeric port. |
| 432 |
"example.com:8080:9090", // Multiple colons in port. |
| 433 |
"example.com:99999", // Port out of range. |
| 434 |
"example.com:-1", // Port out of range. |
| 435 |
} |
| 436 |
for _, endpoint := range endpoints { |
| 437 |
l := &logSink{LogSink: testr.New(t).GetSink()} |
| 438 |
t.Cleanup(func(orig logr.Logger) func() { |
| 439 |
global.SetLogger(logr.New(l)) |
| 440 |
return func() { global.SetLogger(orig) } |
| 441 |
}(global.GetLogger())) |
| 442 |
|
| 443 |
// Set the logger as global so BaseAttrs can log the error. |
| 444 |
got := setPresetAttrs(GetComponentName(ID), endpoint) |
| 445 |
want := []attribute.KeyValue{ |
| 446 |
semconv.OTelComponentName(GetComponentName(ID)), |
| 447 |
semconv.OTelComponentTypeOtlpHTTPLogExporter, |
| 448 |
} |
| 449 |
assert.Equal(t, want, got) |
| 450 |
|
| 451 |
assert.Equal(t, 8, l.level, "expected Debug log level") |
| 452 |
assert.Equal(t, "failed to parse target", l.msg) |
| 453 |
} |
| 454 |
} |
| 455 |
|
| 456 |
func BenchmarkInstrumentationExportLogs(b *testing.B) { |
| 457 |
setup := func(b *testing.B) *Instrumentation { |
| 458 |
b.Helper() |
| 459 |
b.Setenv("OTEL_GO_X_OBSERVABILITY", "true") |
| 460 |
inst, err := NewInstrumentation(ID, TARGET) |
| 461 |
if err != nil { |
| 462 |
b.Fatalf("failed to create instrumentation: %v", err) |
| 463 |
} |
| 464 |
return inst |
| 465 |
} |
| 466 |
|
| 467 |
run := func(err error, statusCode int) func(*testing.B) { |
| 468 |
return func(b *testing.B) { |
| 469 |
inst := setup(b) |
| 470 |
b.ReportAllocs() |
| 471 |
b.ResetTimer() |
| 472 |
for b.Loop() { |
| 473 |
inst.ExportLogs(b.Context(), 10).End(err, statusCode) |
| 474 |
} |
| 475 |
} |
| 476 |
} |
| 477 |
|
| 478 |
b.Run("NoError", run(nil, http.StatusOK)) |
| 479 |
err := &internal.PartialSuccess{RejectedItems: 6} |
| 480 |
b.Run("PartialError", run(err, http.StatusOK)) |
| 481 |
b.Run("FullError", run(assert.AnError, http.StatusInternalServerError)) |
| 482 |
} |