1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-11-29 23:07:45 +02:00
Files
opentelemetry-go/sdk/trace/simple_span_processor.go
Mahendra Bishnoi f7d2882606 feat: sdk/trace: span processed metric for simple span processor (#7374)
Fixes #7004 

This PR adds support for experimental otel.sdk.processor.span.processed
metric in simple span processor.
Definition of metric at:
https://github.com/open-telemetry/semantic-conventions/blob/v1.36.0/docs/otel/sdk-metrics.md

Experimental metrics are behind a feature flag:
`OTEL_GO_X_OBSERVABILITY`

<details>
<summary>Observability Implementation Checklist</summary>

## Observability Implementation Checklist
Based on the [project Observability
guidelines](e4ab314112/CONTRIBUTING.md (observability)),
ensure the following are completed:

### Environment Variable Activation
* [x] Observability features are disabled by default
* [x] Features are activated through the `OTEL_GO_X_OBSERVABILITY`
environment variable
* [x] Use consistent pattern with `x.Observability.Enabled()` check [^1]
* [x] Follow established experimental feature pattern [^2][^3]

[^1]:
e4ab314112/exporters/stdout/stdouttrace/internal/observ/instrumentation.go (L101-L103)
[^2]:
e4ab314112/exporters/stdout/stdouttrace/internal/x/x.go
[^3]:
e4ab314112/sdk/internal/x/x.go

### Encapsulation
* [x] Instrumentation is encapsulated within a dedicated `struct` (e.g.,
[`Instrumentation`](e4ab314112/exporters/stdout/stdouttrace/internal/observ/instrumentation.go (L86-L94)))
* [x] Instrumentation is not mixed into the instrumented component
* [x] Instrumentation code is in its own file or package if
complex/reused
* [x] Instrumentation setup doesn't bloat the main component code

### Initialization
* [x] Initialization is only done when observability is enabled
* [x] Setup is explicit and side-effect free
* [x] Return errors from initialization when appropriate
* [x] Use the global Meter provider (e.g., `otel.GetMeterProvider()`)
* [x] Include proper meter configuration with:
  * [x] Instrumentation package name is used for the Meter
* [x] Instrumentation version (e.g.
[`Version`](e4ab314112/exporters/stdout/stdouttrace/internal/observ/instrumentation.go (L40-L43)))
* [x] Schema URL (e.g.
[`SchemaURL`](e4ab314112/exporters/stdout/stdouttrace/internal/observ/instrumentation.go (L36-L38)))

### Performance
* [x] Little to no overhead when observability is disabled
* [x] Expensive operations are only executed when observability is
enabled
* [x] When enabled, instrumentation code paths are optimized to reduce
allocation/computation overhead

#### Attribute and Option Allocation Management
* [x] Use `sync.Pool` for attribute slices and options with dynamic
attributes
* [x] Pool objects are properly reset before returning to pool
* [x] Pools are scoped for maximum efficiency while ensuring correctness

#### Caching
* [x] Static attribute sets known at compile time are pre-computed and
cached
* [x] Common attribute combinations use lookup tables/maps

#### Benchmarking
* [x] Benchmarks provided for all instrumentation code
* [ ] Benchmark scenarios include both enabled and disabled
observability
* [x] Benchmark results show impact on allocs/op, B/op, and ns/op (use
`b.ReportAllocs()` in benchmarks)

### Error Handling and Robustness
* [x] Errors are reported back to caller when possible
* [x] Partial failures are handled gracefully
* [x] Use partially initialized components when available
* [x] Return errors to caller instead of only using `otel.Handle()`
* [x] Use `otel.Handle()` only when component cannot report error to
user

### Context Propagation
* [x] Observability measurements receive the context from the function
being measured (don't break context propagation by using
`context.Background()`)

### Semantic Conventions Compliance
* [x] All metrics follow [OpenTelemetry Semantic
Conventions](5ee549b1ce/docs/otel/sdk-metrics.md)
* [x] Use the
[`otelconv`](https://pkg.go.dev/go.opentelemetry.io/otel@v1.38.0/semconv/v1.37.0/otelconv)
convenience package for metric semantic conventions
* [x] Component names follow semantic conventions
* [x] Use package path scope type as stable identifier for non-standard
components
* [x] Component names are stable unique identifiers
* [x] Use global counter for uniqueness if necessary
* [x] Component ID counter is resettable for deterministic testing

### Testing
* [x] Use deterministic testing with isolated state
* [x] Restore previous state after tests (`t.Cleanup()`)
* [x] Isolate meter provider for testing
* [x] Use `t.Setenv()` for environment variable testing
* [x] Reset component ID counter for deterministic component names
* [x] Test order doesn't affect results
</details>

### Benchmarks

```console
> benchstat bmark.result
goos: darwin
goarch: arm64
pkg: go.opentelemetry.io/otel/sdk/trace/internal/observ
cpu: Apple M1 Pro
                             │ bmark.result │
                             │    sec/op    │
SSP/SpanProcessed-8            146.7n ± 15%
SSP/SpanProcessedWithError-8   205.1n ±  3%
geomean                        173.5n

                             │ bmark.result │
                             │     B/op     │
SSP/SpanProcessed-8              280.0 ± 0%
SSP/SpanProcessedWithError-8     408.0 ± 0%
geomean                          338.0

                             │ bmark.result │
                             │  allocs/op   │
SSP/SpanProcessed-8              3.000 ± 0%
SSP/SpanProcessedWithError-8     3.000 ± 0%
geomean                          3.000
```

---------

Co-authored-by: Tyler Yahn <MrAlias@users.noreply.github.com>
2025-10-17 15:57:35 -07:00

151 lines
4.7 KiB
Go

// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package trace // import "go.opentelemetry.io/otel/sdk/trace"
import (
"context"
"sync"
"sync/atomic"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/internal/global"
"go.opentelemetry.io/otel/sdk/trace/internal/observ"
"go.opentelemetry.io/otel/trace"
)
// simpleSpanProcessor is a SpanProcessor that synchronously sends all
// completed Spans to a trace.Exporter immediately.
type simpleSpanProcessor struct {
exporterMu sync.Mutex
exporter SpanExporter
stopOnce sync.Once
inst *observ.SSP
}
var _ SpanProcessor = (*simpleSpanProcessor)(nil)
// NewSimpleSpanProcessor returns a new SpanProcessor that will synchronously
// send completed spans to the exporter immediately.
//
// This SpanProcessor is not recommended for production use. The synchronous
// nature of this SpanProcessor makes it good for testing, debugging, or showing
// examples of other features, but it will be slow and have a high computation
// resource usage overhead. The BatchSpanProcessor is recommended for production
// use instead.
func NewSimpleSpanProcessor(exporter SpanExporter) SpanProcessor {
ssp := &simpleSpanProcessor{
exporter: exporter,
}
var err error
ssp.inst, err = observ.NewSSP(nextSimpleProcessorID())
if err != nil {
otel.Handle(err)
}
global.Warn("SimpleSpanProcessor is not recommended for production use, consider using BatchSpanProcessor instead.")
return ssp
}
var simpleProcessorIDCounter atomic.Int64
// nextSimpleProcessorID returns an identifier for this simple span processor,
// starting with 0 and incrementing by 1 each time it is called.
func nextSimpleProcessorID() int64 {
return simpleProcessorIDCounter.Add(1) - 1
}
// OnStart does nothing.
func (*simpleSpanProcessor) OnStart(context.Context, ReadWriteSpan) {}
// OnEnd immediately exports a ReadOnlySpan.
func (ssp *simpleSpanProcessor) OnEnd(s ReadOnlySpan) {
ssp.exporterMu.Lock()
defer ssp.exporterMu.Unlock()
var err error
if ssp.exporter != nil && s.SpanContext().TraceFlags().IsSampled() {
err = ssp.exporter.ExportSpans(context.Background(), []ReadOnlySpan{s})
if err != nil {
otel.Handle(err)
}
}
if ssp.inst != nil {
// Add the span to the context to ensure the metric is recorded
// with the correct span context.
ctx := trace.ContextWithSpanContext(context.Background(), s.SpanContext())
ssp.inst.SpanProcessed(ctx, err)
}
}
// Shutdown shuts down the exporter this SimpleSpanProcessor exports to.
func (ssp *simpleSpanProcessor) Shutdown(ctx context.Context) error {
var err error
ssp.stopOnce.Do(func() {
stopFunc := func(exp SpanExporter) (<-chan error, func()) {
done := make(chan error, 1)
return done, func() { done <- exp.Shutdown(ctx) }
}
// The exporter field of the simpleSpanProcessor needs to be zeroed to
// signal it is shut down, meaning all subsequent calls to OnEnd will
// be gracefully ignored. This needs to be done synchronously to avoid
// any race condition.
//
// A closure is used to keep reference to the exporter and then the
// field is zeroed. This ensures the simpleSpanProcessor is shut down
// before the exporter. This order is important as it avoids a potential
// deadlock. If the exporter shut down operation generates a span, that
// span would need to be exported. Meaning, OnEnd would be called and
// try acquiring the lock that is held here.
ssp.exporterMu.Lock()
done, shutdown := stopFunc(ssp.exporter)
ssp.exporter = nil
ssp.exporterMu.Unlock()
go shutdown()
// Wait for the exporter to shut down or the deadline to expire.
select {
case err = <-done:
case <-ctx.Done():
// It is possible for the exporter to have immediately shut down and
// the context to be done simultaneously. In that case this outer
// select statement will randomly choose a case. This will result in
// a different returned error for similar scenarios. Instead, double
// check if the exporter shut down at the same time and return that
// error if so. This will ensure consistency as well as ensure
// the caller knows the exporter shut down successfully (they can
// already determine if the deadline is expired given they passed
// the context).
select {
case err = <-done:
default:
err = ctx.Err()
}
}
})
return err
}
// ForceFlush does nothing as there is no data to flush.
func (*simpleSpanProcessor) ForceFlush(context.Context) error {
return nil
}
// MarshalLog is the marshaling function used by the logging system to represent
// this Span Processor.
func (ssp *simpleSpanProcessor) MarshalLog() any {
return struct {
Type string
Exporter SpanExporter
}{
Type: "SimpleSpanProcessor",
Exporter: ssp.exporter,
}
}