Documentation
¶
Overview ¶
Package otlp provides hardware-neutral OpenTelemetry trace wire encoding, schema validation, span tracing, claim checking, and collector test sinks.
It merges span production (Tracer, Region, TraceSpan), attribute and span-kind schema registries (Valid, IsFloat, Kinds), OTLP protobuf and JSON wire encoders and decoders (Span, MarshalTraces, MarshalTracesJSON, ReadTracesJSON, ReadSpansJSONL), claim verification (Claim, Check), and in-process test collectors (Sink, NewSink, ReadTraces, CheckTraces).
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
A loader traces each shard. Past two shards, the rest are folded into one span.
package main
import (
"bytes"
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/host/otlp"
spantrace "github.com/tmc/lib/nvidia/x/host/otlp"
)
func main() {
var buf bytes.Buffer
t, err := spantrace.New(spantrace.Config{Service: "loader", Writer: &buf, MaxChildren: 2})
if err != nil {
fmt.Println(err)
return
}
ctx, root := t.Root(context.Background(), "load", "shards", 5)
for i := range 5 {
_, s := spantrace.Region(ctx, "shard", "index", i)
s.End()
}
root.End()
if err := t.Close(ctx); err != nil {
fmt.Println(err)
return
}
spans, err := otlp.ReadTraces(&buf)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(spans), "spans, check:", otlp.CheckTraces(spans))
for _, s := range otlp.Find(spans, "shard") {
if n, ok := s.Attrs[spantrace.FoldedCountKey]; ok {
fmt.Println("folded", n)
} else {
fmt.Println("shard", s.Attrs["index"])
}
}
}
Output: 4 spans, check: <nil> shard 0 shard 1 folded 3
Example (Otlptest) ¶
A sink that is down for two requests and then accepts.
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/host/otlp"
)
func main() {
s := otlp.NewSink(otlp.Fail(503), otlp.Fail(503))
defer s.Close()
for range 3 {
resp, err := s.Client().Post(s.URL+"/v1/metrics", "application/json", strings.NewReader(`{"resourceMetrics":[]}`))
if err != nil {
fmt.Println(err)
return
}
resp.Body.Close()
}
for _, r := range s.Requests() {
fmt.Println(r.Seq, r.Path, r.Status)
}
}
Output: 0 /v1/metrics 503 1 /v1/metrics 503 2 /v1/metrics 200
Example (Spanschema) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/otlp"
)
func main() {
for _, key := range []string{"kernel.role", "serve.decode_rows", "op_gemm_ms", "iket.bogus"} {
fmt.Println(key, otlp.Valid(key))
}
}
Output: kernel.role true serve.decode_rows true op_gemm_ms true iket.bogus false
Example (Tracecheck) ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/host/otlp"
)
func main() {
trace := otlp.DeterministicTraceID("example")
spans := []otlp.Span{
{TraceID: trace, SpanID: otlp.DeterministicSpanID("0"), Name: "step 0", Start: 10, End: 20, Attrs: map[string]any{"span_kind": "step", "serve.decode_rows": 4}},
{TraceID: trace, SpanID: otlp.DeterministicSpanID("1"), Name: "step 1", Start: 20, End: 20, Attrs: map[string]any{"span_kind": "step"}},
}
claims, err := otlp.ReadClaims(strings.NewReader(`[
{"name": "decode steps", "kind": "step", "count": 2, "keys": ["serve.decode_rows"], "timed": true}
]`))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(otlp.Check(spans, claims))
}
Output: claim "decode steps": serve.decode_rows missing on 1 of 2 spans claim "decode steps": no timings on 1 of 2 spans
Index ¶
- Constants
- Variables
- func Check(spans []Span, claims []Claim) error
- func CheckTraces(spans []RecordedSpan, remote ...string) error
- func DecodeExportResponse(b []byte) (rejected int, msg string, err error)
- func DeterministicSpanID(parts ...string) string
- func DeterministicTraceID(parts ...string) string
- func EncodeRequest(service string, spans []Span) ([]byte, error)
- func FloatKeys() []string
- func FormatTraceparent(traceID, spanID string, sampled bool) string
- func IsFloat(key string) bool
- func KernelRoles() []string
- func Keys() []string
- func Kinds() []string
- func MarshalTraces(spans []Span, opts *EncodeOptions) ([]byte, error)
- func MarshalTracesJSON(spans []Span, opts *EncodeOptions) ([]byte, error)
- func ParseTraceparent(hdr string) (traceID, spanID string, sampled bool, err error)
- func Remote(ctx context.Context, traceparent string) context.Context
- func ServeKeys() []string
- func TraceStateValue(state, key string) (string, error)
- func Valid(key string) bool
- func WriteSpansJSONL(w io.Writer, spans []Span) error
- func WriteTraces(w io.Writer, spans []Span, opts *EncodeOptions) error
- func WriteTracesJSON(w io.Writer, spans []Span, opts *EncodeOptions) error
- type Claim
- type Config
- type EncodeOptions
- type Event
- type ExportStats
- type RecordedEvent
- type RecordedLink
- type RecordedSpan
- type Request
- type ResourceAttributer
- type Response
- type Result
- type Sink
- func (s *Sink) Await(ctx context.Context, n int) ([]Request, error)
- func (s *Sink) AwaitMatch(ctx context.Context, match func(Request) bool) (Request, error)
- func (s *Sink) Client() *http.Client
- func (s *Sink) Close()
- func (s *Sink) Requests() []Request
- func (s *Sink) Script(rs ...Response)
- func (s *Sink) SetDefault(r Response)
- type Span
- type SpanLink
- type TraceSpan
- type Tracer
Examples ¶
Constants ¶
const ( FoldedCountKey = "trace.folded.count" // number of folded spans FoldedFailedKey = "trace.folded.failed" // number of them that failed FoldedTotalMsKey = "trace.folded.total_ms" // their summed duration, in milliseconds )
Attribute keys of a span that stands for folded children.
const ( DefaultQueue = 4096 DefaultMaxChildren = 64 DefaultTimeout = 10 * time.Second )
Defaults for zero Config fields.
const ( SpanKindCapture = "capture" SpanKindStep = "step" SpanKindPrefill = "prefill" SpanKindLayer = "layer" SpanKindKernel = "kernel" SpanKindIKETStage = "iket_stage" SpanKindIKETDiff = "iket_diff" SpanKindGPU = "gpu" SpanKindCandidate = "candidate" SpanKindNVTX = "nvtx" SpanKindRequest = "request" )
Span kinds used in the "span_kind" attribute across the lib-why-slower / lib-nvidia OTLP schema.
const ( PassTimeline = "timeline" PassTiming = "timing" PassPCSampling = "pcsampling" PassCounters = "counters" PassTelemetry = "telemetry" PassIKET = "iket" PassLineage = "lineage" )
Pass values used in the "pass" attribute across the schema.
const ( DefaultServiceName = "lib-nvidia" DefaultScopeName = "github.com/tmc/lib/nvidia/x/cudaotlp" WhySlowerService = "lib-why-slower" WhySlowerScope = "why-slower/otlpsend" )
DefaultServiceName and DefaultScopeName are used when EncodeOptions omits them.
const ScopeName = "github.com/tmc/lib/nvidia/x/spantrace"
ScopeName is the instrumentation scope of exported spans.
const ServeVersion = "1.0.0"
ServeVersion identifies the serve.* attribute vocabulary.
const Version = "1.23.0"
Version identifies the core vocabulary: span kinds, kernel roles, and every attribute key outside serve.*.
Variables ¶
var ( // ErrInvertedStageSpan reports that an IKET stage range or OTLP span has an // end timestamp earlier than its start timestamp. ErrInvertedStageSpan = errors.New("cudaotlp: stage span ends before it starts") // ErrEmptyOTLPBatch reports that an OTLP trace export was invoked with zero spans. ErrEmptyOTLPBatch = errors.New("cudaotlp: empty OTLP span batch") )
Functions ¶
func Check ¶
Check checks each claim against spans and returns an error with one line for each way a claim does not hold, or nil if all hold.
func CheckTraces ¶
func CheckTraces(spans []RecordedSpan, remote ...string) error
Check reports whether spans form well-linked traces: there is at least one span, no span ID appears twice in a trace, every parent is a span of the same trace or one of the remote span IDs, no span is its own ancestor, and no span ends before it starts.
func DecodeExportResponse ¶
DecodeExportResponse parses an OTLP ExportTraceServiceResponse protobuf:
message ExportTraceServiceResponse { ExportTracePartialSuccess partial_success = 1; }
message ExportTracePartialSuccess { int64 rejected_spans = 1; string error_message = 2; }
func DeterministicSpanID ¶
DeterministicSpanID derives a non-zero 16-hex-character (8-byte) OTLP span_id from parts, matching why-slower's sid(..., n=8).
func DeterministicTraceID ¶
DeterministicTraceID derives a non-zero 32-hex-character (16-byte) OTLP trace_id from parts, matching why-slower's sid(..., n=16).
func EncodeRequest ¶
EncodeRequest encodes spans as a binary OTLP/HTTP ExportTraceServiceRequest with service.name=service and scope="why-slower/otlpsend", producing byte-for-byte identical output to why-slower/otlpsend.
func FloatKeys ¶
func FloatKeys() []string
FloatKeys returns the registered literal keys whose values are float64, in sorted order.
func FormatTraceparent ¶
FormatTraceparent formats a version-00 header with canonical lowercase IDs. It returns an empty string if either ID is malformed or all zero.
func IsFloat ¶
IsFloat reports whether key is registered as a float64 attribute, including the dynamic op_<name>_ms, stall_<reason>_pct, pcsamp.stall_<reason>_pct, and iket.<stage>.payload_* families, so that whole-valued numbers keep their OTLP doubleValue encoding.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/otlp"
)
func main() {
fmt.Println(otlp.IsFloat("serve.request.ttft_ms"), otlp.IsFloat("serve.decode_rows"))
}
Output: true false
func KernelRoles ¶
func KernelRoles() []string
KernelRoles returns the registered kernel.role values in sorted order. A role names the transformer operation a kernel span performs the same way for every engine, so one query can group engines by it. A fused kernel's role is its primary operation, the projection of a GEMM with an epilogue; cast is a dtype conversion, quantization included; megakernel is a persistent kernel that runs several roles as stages, each of whose stage spans carries its own role.
func Keys ¶
func Keys() []string
Keys returns the registered literal attribute keys of both vocabularies in sorted order. Legacy unprefixed names are retained for existing consumers. Dynamic op_<name>_ms, stall_<reason>_pct, pcsamp.stall_<reason>_pct, and iket.<stage> families are described by Valid.
func MarshalTraces ¶
func MarshalTraces(spans []Span, opts *EncodeOptions) ([]byte, error)
MarshalTraces encodes spans as a binary OTLP/HTTP ExportTraceServiceRequest. It fails closed with ErrEmptyOTLPBatch when spans is empty and with ErrInvertedStageSpan when any span has End < Start.
func MarshalTracesJSON ¶
func MarshalTracesJSON(spans []Span, opts *EncodeOptions) ([]byte, error)
MarshalTracesJSON encodes spans in the OTLP/JSON ExportTraceServiceRequest representation.
func ParseTraceparent ¶
ParseTraceparent parses a W3C Trace Context header. It rejects zero IDs, uppercase hexadecimal, version ff, and version-00 extensions. Unknown versions retain the known prefix; unknown flag bits do not affect sampled.
func Remote ¶
Remote returns a context whose next Tracer.Root joins the trace named by a W3C traceparent header value, as a child of its span. If traceparent is not valid, Remote returns ctx.
func ServeKeys ¶
func ServeKeys() []string
ServeKeys returns the registered serve.* attribute keys in sorted order. They are versioned by ServeVersion, not Version.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/host/otlp"
)
func main() {
fmt.Println(otlp.ServeKeys()[0])
}
Output: serve.context_tokens
func TraceStateValue ¶
TraceStateValue validates a W3C tracestate list and returns the value for key, or an empty string when absent. Empty list members are accepted. Values may contain semicolons and colons, but cannot contain commas or equals signs.
func Valid ¶
Valid reports whether key belongs to either vocabulary. Dynamic names must contain a nonempty ASCII identifier, or for the iket.<stage>.payload_{min,p50,max} family a dotted stage name; arbitrary iket.* keys are not accepted.
func WriteSpansJSONL ¶
WriteSpansJSONL writes spans as newline-delimited JSON to w after validating that the batch is non-empty and no span is inverted. The first span carries cudaotlp schema and per-kind batch counts; the input is not modified.
func WriteTraces ¶
func WriteTraces(w io.Writer, spans []Span, opts *EncodeOptions) error
WriteTraces encodes spans as a binary OTLP/HTTP ExportTraceServiceRequest and writes the protobuf payload to w.
func WriteTracesJSON ¶
func WriteTracesJSON(w io.Writer, spans []Span, opts *EncodeOptions) error
WriteTracesJSON encodes spans in the OTLP/JSON ExportTraceServiceRequest representation and writes the JSON payload to w.
Types ¶
type Claim ¶
type Claim struct {
Name string `json:"name"` // how the report refers to the claim
Kind string `json:"kind,omitempty"` // select spans whose span_kind is Kind
Span string `json:"span,omitempty"` // select spans named Span
Count *int `json:"count,omitempty"` // exactly this many spans are selected
Keys []string `json:"keys,omitempty"` // every selected span carries these attributes
Timed bool `json:"timed,omitempty"` // every selected span has a start and a later end
}
A Claim is one statement a report makes about the spans of a trace.
type Config ¶
type Config struct {
Service string // service.name; "" means "unknown_service"
Version string // service.version; "" for none
Writer io.Writer // receives one OTLP/JSON request per line; nil for none
Endpoint string // OTLP/HTTP traces URL, such as http://host:4318/v1/traces; "" for none
Headers map[string]string // added to each request to Endpoint
JSON bool // post OTLP/JSON instead of OTLP/protobuf
Timeout time.Duration // per request to Endpoint; 0 means DefaultTimeout
Client *http.Client // nil means a new client
// Queue bounds the spans waiting for export; 0 means DefaultQueue.
Queue int
// MaxChildren bounds the exported children of one name under one
// span; 0 means DefaultMaxChildren and a negative value means no
// bound.
MaxChildren int
// Logf, if not nil, reports export failures.
Logf func(format string, args ...any)
}
A Config says where a Tracer exports spans and how.
func (*Config) Env ¶
Env sets c's fields from the OpenTelemetry environment variables that are set, as the OTLP exporter specification defines them:
OTEL_SERVICE_NAME Service OTEL_EXPORTER_OTLP_TRACES_ENDPOINT Endpoint, used as is OTEL_EXPORTER_OTLP_ENDPOINT Endpoint, with /v1/traces appended OTEL_EXPORTER_OTLP_[TRACES_]HEADERS Headers, as key=value,... OTEL_EXPORTER_OTLP_[TRACES_]PROTOCOL JSON: http/json or http/protobuf OTEL_EXPORTER_OTLP_[TRACES_]TIMEOUT Timeout, in milliseconds
A TRACES_ variable takes precedence over its general form; for headers, key by key. Env leaves fields alone whose variables are unset or empty, and returns an error for a value it cannot use, such as the grpc protocol.
type EncodeOptions ¶
type EncodeOptions struct {
// ServiceName sets the "service.name" resource attribute. Empty defaults to
// DefaultServiceName ("lib-nvidia").
ServiceName string
// ScopeName sets the OTLP InstrumentationScope.name. Empty defaults to
// DefaultScopeName ("github.com/tmc/lib/nvidia/x/cudaotlp").
ScopeName string
// ResourceAttrs holds additional resource attributes merged with SystemInfo.
ResourceAttrs map[string]any
// SystemInfo, when non-nil, populates hardware/toolchain resource attributes.
SystemInfo ResourceAttributer
}
EncodeOptions configures MarshalTraces and MarshalTracesJSON.
type Event ¶
type Event struct {
Time uint64 `json:"time_ns"`
Name string `json:"name"`
Attrs map[string]any `json:"attrs"`
}
Event is a timestamped annotation attached to a Span (such as "sass_hot" or "gpu_sample").
type ExportStats ¶
ExportStats describes spans and distinct attribute values in one export. Event attributes are included in Cardinality. Counts never stand for drops.
func InspectExport ¶
func InspectExport(spans []Span) (ExportStats, error)
InspectExport inventories spans and validates the registered vocabulary. It rejects missing or unknown span kinds and unregistered span/event keys. Custom attributes can still be encoded by the general OTLP writers.
type RecordedEvent ¶
An Event is a timestamped annotation on a Span.
type RecordedLink ¶
A Link points from a Span to another span, possibly in another trace.
type RecordedSpan ¶
type RecordedSpan struct {
TraceID string // 32 lowercase hex digits
SpanID string // 16 lowercase hex digits
ParentID string // 16 lowercase hex digits, or "" for a root
Name string
Kind int
Start uint64 // Unix nanoseconds
End uint64 // Unix nanoseconds
Attrs map[string]any
Events []RecordedEvent
Links []RecordedLink
Status int // 0 unset, 1 ok, 2 error
Message string
Scope string // instrumentation scope name
Resource map[string]any // resource attributes
}
A Span is one span read by ReadTraces.
func Find ¶
func Find(spans []RecordedSpan, name string) []RecordedSpan
Find returns the spans named name, in order.
func ReadTraces ¶
func ReadTraces(r io.Reader) ([]RecordedSpan, error)
ReadTraces reads OTLP/JSON ExportTraceServiceRequest documents from r, one after another as an OpenTelemetry Collector file exporter writes them, and returns their spans in input order.
ReadTraces shares no code with any producer's decoder, so it can serve as an independent oracle for one. It is strict: a field the OTLP/JSON encoding does not define, a trace or span ID that is not lowercase hex of the right length or is all zeros, and a span that ends before it starts are errors.
Attribute values are string, bool, int64, float64, []byte, []any (an array value) or map[string]any (a key-value list).
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/host/otlp"
)
func main() {
const trace = `{"resourceSpans":[{"scopeSpans":[{"spans":[` +
`{"traceId":"0af7651916cd43dd8448eb211c80319c","spanId":"b7ad6b7169203331","name":"load","startTimeUnixNano":"1000","endTimeUnixNano":"5000"},` +
`{"traceId":"0af7651916cd43dd8448eb211c80319c","spanId":"00f067aa0ba902b7","parentSpanId":"b7ad6b7169203331","name":"shard","startTimeUnixNano":"1000","endTimeUnixNano":"3000",` +
`"attributes":[{"key":"bytes","value":{"intValue":"4096"}}]}]}]}]}`
spans, err := otlp.ReadTraces(strings.NewReader(trace))
if err != nil {
fmt.Println(err)
return
}
if err := otlp.CheckTraces(spans); err != nil {
fmt.Println(err)
return
}
for _, s := range otlp.Find(spans, "shard") {
fmt.Println(s.Name, s.End-s.Start, s.Attrs["bytes"])
}
}
Output: shard 2000 4096
func ReadTracesFile ¶
func ReadTracesFile(path string) ([]RecordedSpan, error)
ReadTracesFile is like ReadTraces but reads the named file.
type Request ¶
type Request struct {
Seq int // arrival order, from 0
Method string
Path string
Header http.Header
Body []byte
TLS bool // whether the request arrived over TLS
Status int // the status answered, or 0 if the client went away first
}
A Request is one request a Sink received.
func (Request) JSON ¶
JSON decodes r's body as JSON, with numbers as json.Number.
Example ¶
package main
import (
"fmt"
"net/http"
"strings"
"github.com/tmc/lib/nvidia/x/host/otlp"
)
func main() {
s := otlp.NewSink()
defer s.Close()
resp, err := http.Post(s.URL+"/v1/logs", "application/json", strings.NewReader(`{"resourceLogs":[{"scopeLogs":[]}]}`))
if err != nil {
fmt.Println(err)
return
}
resp.Body.Close()
v, err := s.Requests()[0].JSON()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(v["resourceLogs"].([]any)))
}
Output: 1
type ResourceAttributer ¶
ResourceAttributer supplies hardware or environment resource attributes keyed by service name (for example github.com/tmc/lib/nvidia/x/obs/cudaprof.SystemInfo).
type Response ¶
type Response struct {
Status int // 0 means 200
Header http.Header // added to the response header
Body string
// Hold holds the request open before answering, until the client
// cancels it, Release is closed, or the sink closes. A held request
// that is released is then answered as the other fields say.
Hold bool
Release <-chan struct{}
Delay time.Duration // wait before answering
ByteDelay time.Duration // wait before each byte of Body, flushing each
}
A Response is how a Sink answers one request.
func Hold ¶
func Hold() Response
Hold returns a response that holds the request until the client cancels it or the sink closes.
func HoldUntil ¶
func HoldUntil(release <-chan struct{}) Response
HoldUntil returns a response that holds the request until release is closed, the client cancels it, or the sink closes, and then answers OK.
func Malformed ¶
func Malformed() Response
Malformed returns a 200 response whose body is truncated JSON.
func OK ¶
func OK() Response
OK returns a 200 response with an empty OTLP/JSON body, a full success.
func PartialLogs ¶
PartialLogs returns a 200 partial success rejecting n log records.
func PartialMetrics ¶
PartialMetrics returns a 200 partial success rejecting n data points.
func PartialSpans ¶
PartialSpans returns a 200 partial success rejecting n spans.
type Result ¶
type Result struct {
Status int // HTTP status code
Rejected int64 // spans the collector reported rejecting
Message string // the collector's error message, if any
}
A Result is a collector's answer to one export request.
func Post ¶
func Post(ctx context.Context, client *http.Client, endpoint string, header http.Header, body []byte) (Result, error)
Post sends body, an encoded OTLP ExportTraceServiceRequest, to an OTLP/HTTP traces endpoint, and decodes the collector's partial-success answer. The request carries header; its Content-Type defaults to application/x-protobuf and must be application/json for an OTLP/JSON body. A nil client means http.DefaultClient.
A status other than 2xx is an error; the Result then holds the status and the start of the response body as Message.
type Sink ¶
type Sink struct {
URL string // base URL, with no path
// contains filtered or unexported fields
}
A Sink is a fake OTLP/HTTP collector on a loopback httptest server. Create one with NewSink and Close it when done.
func NewSink ¶
NewSink starts a sink that answers its first requests with script, in order, and every later request with OK.
func NewTLSSink ¶
NewTLSSink is like NewSink but serves HTTPS with a self-signed certificate that only the sink's Client trusts.
func (*Sink) AwaitMatch ¶
AwaitMatch waits until a received request satisfies match, and returns the first that does.
func (*Sink) Client ¶
Client returns an HTTP client for the sink. For a TLS sink, it trusts the sink's certificate.
func (*Sink) Requests ¶
Requests returns a copy of the requests received so far, in arrival order. A request is recorded when its body has been read, before it is answered.
func (*Sink) SetDefault ¶
SetDefault sets the response for requests the script does not cover.
type Span ¶
type Span struct {
TraceID string `json:"trace_id"`
SpanID string `json:"span_id"`
ParentID string `json:"parent_id"`
Name string `json:"name"`
Start uint64 `json:"start_ns"`
End uint64 `json:"end_ns"`
Attrs map[string]any `json:"attrs"`
Events []Event `json:"events"`
Links []SpanLink `json:"links,omitempty"`
Status int `json:"status,omitempty"`
Message string `json:"message,omitempty"`
}
Span is one OpenTelemetry trace span matching why-slower's JSONL and OTLP/HTTP export representation.
func ReadSpans ¶
ReadSpans reads the spans of a trace file, either newline-delimited spans as [cudaotlp.WriteSpansJSONL] writes them or OTLP/JSON documents as [cudaotlp.WriteTracesJSON] writes them.
func ReadSpansFile ¶
ReadSpansFile reads newline-delimited JSON spans from path.
func ReadSpansJSONL ¶
ReadSpansJSONL reads newline-delimited JSON spans from r. An empty input returns ErrEmptyOTLPBatch.
func ReadSpansJSONLLimit ¶
ReadSpansJSONLLimit reads newline-delimited JSON spans from r. If limit > 0, at most limit spans are read. An empty input returns ErrEmptyOTLPBatch.
func ReadTracesJSON ¶
ReadTracesJSON reads OTLP/JSON ExportTraceServiceRequest documents from r, such as the output of WriteTracesJSON or an OpenTelemetry Collector file exporter (one document per line), and returns their spans in input order.
Resource and scope attributes are not copied onto the spans. String, bool, integer and double attribute values are supported; array, key-value list and bytes values are an error, since Span cannot hold them. An input with no spans returns ErrEmptyOTLPBatch.
type SpanLink ¶
type SpanLink struct {
TraceID string `json:"trace_id"`
SpanID string `json:"span_id"`
TraceState string `json:"trace_state,omitempty"`
Attrs map[string]any `json:"attrs,omitempty"`
}
SpanLink links an operation to another trace's active span, for example one request participating in a multi-request batch. IDs must be nonzero hex.
type TraceSpan ¶
type TraceSpan struct {
// contains filtered or unexported fields
}
A Span is one timed phase of a trace. Its methods are safe for concurrent use, and do nothing on a nil *Span or after End.
func Region ¶
Region starts a child of the span in ctx and returns a context holding the child. If ctx holds no span, Region returns ctx and a nil *Span.
func (*TraceSpan) End ¶
func (s *TraceSpan) End()
End ends the span and queues it for export. Calls after the first do nothing.
type Tracer ¶
type Tracer struct {
// contains filtered or unexported fields
}
A Tracer starts traces and exports their spans. Create one with New and Close it when done. A nil *Tracer does nothing.
func New ¶
New returns a tracer that exports as cfg says. If cfg has neither a Writer nor an Endpoint, New returns nil, nil: a tracer that does nothing.
func (*Tracer) Close ¶
Close flushes the tracer and stops its exporter. If ctx ends first, Close abandons the export in progress and drops what is left. Spans that end after Close are dropped.
func (*Tracer) Dropped ¶
Dropped returns the number of spans dropped: those that found the queue full or the tracer closed, and those in batches that failed to export or that the collector rejected.