diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 36f70040cfe..a143996ab84 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -36,6 +36,16 @@ updates: schedule: day: sunday interval: weekly + - + package-ecosystem: gomod + directory: /bridge/opencensus + labels: + - dependencies + - go + - "Skip Changelog" + schedule: + day: sunday + interval: weekly - package-ecosystem: gomod directory: /example/basic diff --git a/CHANGELOG.md b/CHANGELOG.md index f609315f3ff..241633b10dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,23 +15,29 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - `SpanContextFromContext` returns `SpanContext` from context. (#1255) - `MetricsLabelsEnricher` type is added to `go.opentelemetry.io/otel/sdk/metric` package. (#1271) - `WithMetricsLabelsEnricher` config option is added to `go.opentelemetry.io/otel/sdk/push` and `go.opentelemetry.io/otel/sdk/pull` packages to allow providing a function to enrich metrics labels based on context. (#1271) +- Add an opencensus to opentelemetry tracing bridge. (#1305) ### Changed -- Move the `go.opentelemetry.io/otel/api/trace` package into `go.opentelemetry.io/otel` with the following changes. (#1229) +- Move the `go.opentelemetry.io/otel/api/trace` package into `go.opentelemetry.io/otel/trace` with the following changes. (#1229) (#1307) - `ID` has been renamed to `TraceID`. - `IDFromHex` has been renamed to `TraceIDFromHex`. - `ErrorOption` has been changed to an interface to conform with project design standards which included adding a `NewErrorConfig` function. - `EmptySpanContext` is removed. - Move the `go.opentelemetry.io/otel/api/trace/tracetest` package into `go.opentelemetry.io/otel/oteltest`. (#1229) -- OTLP Exporter supports OTLP v0.5.0. (#1230) +- OTLP Exporter updates: + - supports OTLP v0.5.0 (#1230) + - supports configurable aggregation temporality (default: Cumulative, optional: Stateless). (#1296) - The Sampler is now called on local child spans. (#1233) - The `Kind` type from the `go.opentelemetry.io/otel/api/metric` package was renamed to `InstrumentKind` to more specifically describe what it is and avoid semantic ambiguity. (#1240) - The `MetricKind` method of the `Descriptor` type in the `go.opentelemetry.io/otel/api/metric` package was renamed to `Descriptor.InstrumentKind`. This matches the returned type and fixes misuse of the term metric. (#1240) - Move test harness from the `go.opentelemetry.io/otel/api/apitest` package into `go.opentelemetry.io/otel/oteltest`. (#1241) - Rename `MergeItererator` to `MergeIterator` in the `go.opentelemetry.io/otel/label` package. (#1244) -- Move the `go.opentelemetry.io/otel/api/metric`, `go.opentelemetry.io/otel/api/metric/metrictest`, and `go.opentelemetry.io/otel/api/metric/registry` packages into `go.opentelemetry.io/otel` as part of #964. (#1252) +- Move the `go.opentelemetry.io/otel/api/metric/metrictest` package into `go.opentelemetry.io/oteltest` as part of #964. (#1252) +- Move the `go.opentelemetry.io/otel/api/metric` package into `go.opentelemetry.io/otel/metric` as part of #1303. (#1321) +- Move the `go.opentelemetry.io/otel/api/metric/registry` package into `go.opentelemetry.io/otel/metric/registry as a part of #1303. (#1316) +- Move the `Number` type (together with related functions) from `go.opentelemetry.io/otel/api/metric` package into `go.opentelemetry.io/otel/metric/number` as a part of #1303. (#1316) - The function signature of the Span `AddEvent` method in `go.opentelemetry.io/otel` is updated to no longer take an unused context and instead take a required name and a variable number of `EventOption`s. (#1254) - The function signature of the Span `RecordError` method in `go.opentelemetry.io/otel` is updated to no longer take an unused context and instead take a required error value and a variable number of `EventOption`s. (#1254) - Move the `go.opentelemetry.io/otel/api/global` package to `go.opentelemetry.io/otel/global`. (#1262) @@ -39,6 +45,9 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm - Fix `Code.UnmarshalJSON` to work with valid json only. (#1276) - The `resource.New()` method changes signature to support builtin attributes and functional options, including `telemetry.sdk.*` and `host.name` semantic conventions; the former method is renamed `resource.NewWithAttributes`. (#1235) +- The prometheus exporter now exports non-monotonic counters (i.e. `UpDownCounter`s) as gauges. (#1210) +- Correct the `Span.End` method documentation in the `otel` API to state updates are not allowed on a span after it has ended. (#1310) +- Updated span collection limits for attribute, event and link counts to 1000 (#1318) ### Removed diff --git a/README.md b/README.md index c448d300dcf..3b3fc877339 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # OpenTelemetry-Go [![Circle CI](https://circleci.com/gh/open-telemetry/opentelemetry-go.svg?style=svg)](https://circleci.com/gh/open-telemetry/opentelemetry-go) -[![Docs](https://godoc.org/go.opentelemetry.io/otel?status.svg)](https://pkg.go.dev/go.opentelemetry.io/otel) +[![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel)](https://pkg.go.dev/go.opentelemetry.io/otel) [![Go Report Card](https://goreportcard.com/badge/go.opentelemetry.io/otel)](https://goreportcard.com/report/go.opentelemetry.io/otel) [![Gitter](https://badges.gitter.im/open-telemetry/opentelemetry-go.svg)](https://gitter.im/open-telemetry/opentelemetry-go?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) diff --git a/bridge/opencensus/bridge.go b/bridge/opencensus/bridge.go new file mode 100644 index 00000000000..3c4e2840b25 --- /dev/null +++ b/bridge/opencensus/bridge.go @@ -0,0 +1,217 @@ +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package opencensus + +import ( + "context" + "fmt" + + octrace "go.opencensus.io/trace" + + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/global" + "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" +) + +// NewTracer returns an implementation of the OpenCensus Tracer interface which +// uses OpenTelemetry APIs. Using this implementation of Tracer "upgrades" +// libraries that use OpenCensus to OpenTelemetry to facilitate a migration. +func NewTracer(tracer trace.Tracer) octrace.Tracer { + return &otelTracer{tracer: tracer} +} + +type otelTracer struct { + tracer trace.Tracer +} + +var _ octrace.Tracer = (*otelTracer)(nil) + +func (o *otelTracer) StartSpan(ctx context.Context, name string, s ...octrace.StartOption) (context.Context, *octrace.Span) { + ctx, sp := o.tracer.Start(ctx, name, convertStartOptions(s, name)...) + return ctx, octrace.NewSpan(&span{otSpan: sp}) +} + +func convertStartOptions(optFns []octrace.StartOption, name string) []trace.SpanOption { + var ocOpts octrace.StartOptions + for _, fn := range optFns { + fn(&ocOpts) + } + otOpts := []trace.SpanOption{} + switch ocOpts.SpanKind { + case octrace.SpanKindClient: + otOpts = append(otOpts, trace.WithSpanKind(trace.SpanKindClient)) + case octrace.SpanKindServer: + otOpts = append(otOpts, trace.WithSpanKind(trace.SpanKindServer)) + case octrace.SpanKindUnspecified: + otOpts = append(otOpts, trace.WithSpanKind(trace.SpanKindUnspecified)) + } + + if ocOpts.Sampler != nil { + global.Handle(fmt.Errorf("ignoring custom sampler for span %q created by OpenCensus because OpenTelemetry does not support creating a span with a custom sampler", name)) + } + return otOpts +} + +func (o *otelTracer) StartSpanWithRemoteParent(ctx context.Context, name string, parent octrace.SpanContext, s ...octrace.StartOption) (context.Context, *octrace.Span) { + // make sure span context is zero'd out so we use the remote parent + ctx = trace.ContextWithSpan(ctx, nil) + ctx = trace.ContextWithRemoteSpanContext(ctx, ocSpanContextToOTel(parent)) + return o.StartSpan(ctx, name, s...) +} + +func (o *otelTracer) FromContext(ctx context.Context) *octrace.Span { + otSpan := trace.SpanFromContext(ctx) + return octrace.NewSpan(&span{otSpan: otSpan}) +} + +func (o *otelTracer) NewContext(parent context.Context, s *octrace.Span) context.Context { + if otSpan, ok := s.Internal().(*span); ok { + return trace.ContextWithSpan(parent, otSpan.otSpan) + } + global.Handle(fmt.Errorf("unable to create context with span %q, since it was created using a different tracer", s.String())) + return parent +} + +type span struct { + otSpan trace.Span +} + +func (s *span) IsRecordingEvents() bool { + return s.otSpan.IsRecording() +} + +func (s *span) End() { + s.otSpan.End() +} + +func (s *span) SpanContext() octrace.SpanContext { + return otelSpanContextToOc(s.otSpan.SpanContext()) +} + +func (s *span) SetName(name string) { + s.otSpan.SetName(name) +} + +func (s *span) SetStatus(status octrace.Status) { + s.otSpan.SetStatus(codes.Code(status.Code), status.Message) +} + +func (s *span) AddAttributes(attributes ...octrace.Attribute) { + s.otSpan.SetAttributes(convertAttributes(attributes)...) +} + +func convertAttributes(attributes []octrace.Attribute) []label.KeyValue { + otAttributes := make([]label.KeyValue, len(attributes)) + for i, a := range attributes { + otAttributes[i] = label.KeyValue{ + Key: label.Key(a.Key()), + Value: convertValue(a.Value()), + } + } + return otAttributes +} + +func convertValue(ocval interface{}) label.Value { + switch v := ocval.(type) { + case bool: + return label.BoolValue(v) + case int64: + return label.Int64Value(v) + case float64: + return label.Float64Value(v) + case string: + return label.StringValue(v) + default: + return label.StringValue("unknown") + } +} + +func (s *span) Annotate(attributes []octrace.Attribute, str string) { + s.otSpan.AddEvent(str, trace.WithAttributes(convertAttributes(attributes)...)) +} + +func (s *span) Annotatef(attributes []octrace.Attribute, format string, a ...interface{}) { + s.Annotate(attributes, fmt.Sprintf(format, a...)) +} + +var ( + uncompressedKey = label.Key("uncompressed byte size") + compressedKey = label.Key("compressed byte size") +) + +func (s *span) AddMessageSendEvent(messageID, uncompressedByteSize, compressedByteSize int64) { + s.otSpan.AddEvent("message send", + trace.WithAttributes( + label.KeyValue{ + Key: uncompressedKey, + Value: label.Int64Value(uncompressedByteSize), + }, + label.KeyValue{ + Key: compressedKey, + Value: label.Int64Value(compressedByteSize), + }), + ) +} + +func (s *span) AddMessageReceiveEvent(messageID, uncompressedByteSize, compressedByteSize int64) { + s.otSpan.AddEvent("message receive", + trace.WithAttributes( + label.KeyValue{ + Key: uncompressedKey, + Value: label.Int64Value(uncompressedByteSize), + }, + label.KeyValue{ + Key: compressedKey, + Value: label.Int64Value(compressedByteSize), + }), + ) +} + +func (s *span) AddLink(l octrace.Link) { + global.Handle(fmt.Errorf("ignoring OpenCensus link %+v for span %q because OpenTelemetry doesn't support setting links after creation", l, s.String())) +} + +func (s *span) String() string { + return fmt.Sprintf("span %s", s.otSpan.SpanContext().SpanID.String()) +} + +func otelSpanContextToOc(sc trace.SpanContext) octrace.SpanContext { + if sc.IsDebug() || sc.IsDeferred() { + global.Handle(fmt.Errorf("ignoring OpenTelemetry Debug or Deferred trace flags for span %q because they are not supported by OpenCensus", sc.SpanID)) + } + var to octrace.TraceOptions + if sc.IsSampled() { + // OpenCensus doesn't expose functions to directly set sampled + to = 0x1 + } + return octrace.SpanContext{ + TraceID: octrace.TraceID(sc.TraceID), + SpanID: octrace.SpanID(sc.SpanID), + TraceOptions: to, + } +} + +func ocSpanContextToOTel(sc octrace.SpanContext) trace.SpanContext { + var traceFlags byte + if sc.IsSampled() { + traceFlags = trace.FlagsSampled + } + return trace.SpanContext{ + TraceID: trace.TraceID(sc.TraceID), + SpanID: trace.SpanID(sc.SpanID), + TraceFlags: traceFlags, + } +} diff --git a/bridge/opencensus/bridge_test.go b/bridge/opencensus/bridge_test.go new file mode 100644 index 00000000000..a2cdb5d562c --- /dev/null +++ b/bridge/opencensus/bridge_test.go @@ -0,0 +1,276 @@ +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package opencensus + +import ( + "context" + "testing" + + octrace "go.opencensus.io/trace" + + "go.opentelemetry.io/otel/codes" + "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/oteltest" + "go.opentelemetry.io/otel/trace" +) + +func TestMixedAPIs(t *testing.T) { + sr := new(oteltest.StandardSpanRecorder) + tp := oteltest.NewTracerProvider(oteltest.WithSpanRecorder(sr)) + tracer := tp.Tracer("mixedapitracer") + octrace.DefaultTracer = NewTracer(tracer) + + func() { + ctx := context.Background() + var ocspan1 *octrace.Span + ctx, ocspan1 = octrace.StartSpan(ctx, "OpenCensusSpan1") + defer ocspan1.End() + + var otspan1 trace.Span + ctx, otspan1 = tracer.Start(ctx, "OpenTelemetrySpan1") + defer otspan1.End() + + var ocspan2 *octrace.Span + ctx, ocspan2 = octrace.StartSpan(ctx, "OpenCensusSpan2") + defer ocspan2.End() + + var otspan2 trace.Span + _, otspan2 = tracer.Start(ctx, "OpenTelemetrySpan2") + defer otspan2.End() + }() + + spans := sr.Completed() + + if len(spans) != 4 { + for _, span := range spans { + t.Logf("Span: %s", span.Name()) + } + t.Fatalf("Got %d spans, exepected %d.", len(spans), 4) + } + + parent := &oteltest.Span{} + for i := range spans { + // Reverse the order we look at the spans in, since they are listed in last-to-first order. + i = len(spans) - i - 1 + // Verify that OpenCensus spans and opentelemetry spans have each other as parents. + if spans[i].ParentSpanID() != parent.SpanContext().SpanID { + t.Errorf("Span %v had parent %v. Expected %d", spans[i].Name(), spans[i].ParentSpanID(), parent.SpanContext().SpanID) + } + parent = spans[i] + } +} + +func TestStartOptions(t *testing.T) { + sr := new(oteltest.StandardSpanRecorder) + tp := oteltest.NewTracerProvider(oteltest.WithSpanRecorder(sr)) + octrace.DefaultTracer = NewTracer(tp.Tracer("startoptionstracer")) + + ctx := context.Background() + _, span := octrace.StartSpan(ctx, "OpenCensusSpan", octrace.WithSpanKind(octrace.SpanKindClient)) + span.End() + + spans := sr.Completed() + + if len(spans) != 1 { + t.Fatalf("Got %d spans, exepected %d", len(spans), 1) + } + + if spans[0].SpanKind() != trace.SpanKindClient { + t.Errorf("Got span kind %v, exepected %d", spans[0].SpanKind(), trace.SpanKindClient) + } +} + +func TestStartSpanWithRemoteParent(t *testing.T) { + sr := new(oteltest.StandardSpanRecorder) + tp := oteltest.NewTracerProvider(oteltest.WithSpanRecorder(sr)) + tracer := tp.Tracer("remoteparent") + octrace.DefaultTracer = NewTracer(tracer) + + ctx := context.Background() + ctx, parent := tracer.Start(ctx, "OpenTelemetrySpan1") + + _, span := octrace.StartSpanWithRemoteParent(ctx, "OpenCensusSpan", otelSpanContextToOc(parent.SpanContext())) + span.End() + + spans := sr.Completed() + + if len(spans) != 1 { + t.Fatalf("Got %d spans, exepected %d", len(spans), 1) + } + + if spans[0].ParentSpanID() != parent.SpanContext().SpanID { + t.Errorf("Span %v, had parent %v. Expected %d", spans[0].Name(), spans[0].ParentSpanID(), parent.SpanContext().SpanID) + } +} + +func TestToFromContext(t *testing.T) { + sr := new(oteltest.StandardSpanRecorder) + tp := oteltest.NewTracerProvider(oteltest.WithSpanRecorder(sr)) + tracer := tp.Tracer("tofromcontext") + octrace.DefaultTracer = NewTracer(tracer) + + func() { + ctx := context.Background() + + _, otSpan1 := tracer.Start(ctx, "OpenTelemetrySpan1") + defer otSpan1.End() + + // Use NewContext instead of the context from Start + ctx = octrace.NewContext(ctx, octrace.NewSpan(&span{otSpan: otSpan1})) + + ctx, _ = tracer.Start(ctx, "OpenTelemetrySpan2") + + // Get the opentelemetry span using the OpenCensus FromContext, and end it + otSpan2 := octrace.FromContext(ctx) + defer otSpan2.End() + + }() + + spans := sr.Completed() + + if len(spans) != 2 { + t.Fatalf("Got %d spans, exepected %d.", len(spans), 2) + } + + parent := &oteltest.Span{} + for i := range spans { + // Reverse the order we look at the spans in, since they are listed in last-to-first order. + i = len(spans) - i - 1 + // Verify that OpenCensus spans and opentelemetry spans have each other as parents. + if spans[i].ParentSpanID() != parent.SpanContext().SpanID { + t.Errorf("Span %v had parent %v. Expected %d", spans[i].Name(), spans[i].ParentSpanID(), parent.SpanContext().SpanID) + } + parent = spans[i] + } +} + +func TestIsRecordingEvents(t *testing.T) { + sr := new(oteltest.StandardSpanRecorder) + tp := oteltest.NewTracerProvider(oteltest.WithSpanRecorder(sr)) + octrace.DefaultTracer = NewTracer(tp.Tracer("isrecordingevents")) + + ctx := context.Background() + _, ocspan := octrace.StartSpan(ctx, "OpenCensusSpan1") + if !ocspan.IsRecordingEvents() { + t.Errorf("Got %v, expected true", ocspan.IsRecordingEvents()) + } +} + +func TestSetThings(t *testing.T) { + sr := new(oteltest.StandardSpanRecorder) + tp := oteltest.NewTracerProvider(oteltest.WithSpanRecorder(sr)) + octrace.DefaultTracer = NewTracer(tp.Tracer("setthings")) + + ctx := context.Background() + _, ocspan := octrace.StartSpan(ctx, "OpenCensusSpan1") + ocspan.SetName("span-foo") + ocspan.SetStatus(octrace.Status{Code: 1, Message: "foo"}) + ocspan.AddAttributes( + octrace.BoolAttribute("bool", true), + octrace.Int64Attribute("int64", 12345), + octrace.Float64Attribute("float64", 12.345), + octrace.StringAttribute("string", "stringval"), + ) + ocspan.Annotate( + []octrace.Attribute{octrace.StringAttribute("string", "annotateval")}, + "annotate", + ) + ocspan.Annotatef( + []octrace.Attribute{ + octrace.Int64Attribute("int64", 12345), + octrace.Float64Attribute("float64", 12.345), + }, + "annotate%d", 67890, + ) + ocspan.AddMessageSendEvent(123, 456, 789) + ocspan.AddMessageReceiveEvent(246, 135, 369) + ocspan.End() + + spans := sr.Completed() + + if len(spans) != 1 { + t.Fatalf("Got %d spans, exepected %d.", len(spans), 1) + } + s := spans[0] + + if s.Name() != "span-foo" { + t.Errorf("Got name %v, expected span-foo", s.Name()) + } + + if s.StatusCode().String() != codes.Error.String() { + t.Errorf("Got code %v, expected 1", s.StatusCode().String()) + } + + if s.StatusMessage() != "foo" { + t.Errorf("Got code %v, expected foo", s.StatusMessage()) + } + + if v := s.Attributes()[label.Key("bool")]; !v.AsBool() { + t.Errorf("Got attributes[bool] %v, expected true", v.AsBool()) + } + if v := s.Attributes()[label.Key("int64")]; v.AsInt64() != 12345 { + t.Errorf("Got attributes[int64] %v, expected 12345", v.AsInt64()) + } + if v := s.Attributes()[label.Key("float64")]; v.AsFloat64() != 12.345 { + t.Errorf("Got attributes[float64] %v, expected 12.345", v.AsFloat64()) + } + if v := s.Attributes()[label.Key("string")]; v.AsString() != "stringval" { + t.Errorf("Got attributes[string] %v, expected stringval", v.AsString()) + } + + if len(s.Events()) != 4 { + t.Fatalf("Got len(events) = %v, expected 4", len(s.Events())) + } + annotateEvent := s.Events()[0] + annotatefEvent := s.Events()[1] + sendEvent := s.Events()[2] + receiveEvent := s.Events()[3] + if v := annotateEvent.Attributes[label.Key("string")]; v.AsString() != "annotateval" { + t.Errorf("Got annotateEvent.Attributes[string] = %v, expected annotateval", v.AsString()) + } + if annotateEvent.Name != "annotate" { + t.Errorf("Got annotateEvent.Name = %v, expected annotate", annotateEvent.Name) + } + if v := annotatefEvent.Attributes[label.Key("int64")]; v.AsInt64() != 12345 { + t.Errorf("Got annotatefEvent.Attributes[int64] = %v, expected 12345", v.AsInt64()) + } + if v := annotatefEvent.Attributes[label.Key("float64")]; v.AsFloat64() != 12.345 { + t.Errorf("Got annotatefEvent.Attributes[float64] = %v, expected 12.345", v.AsFloat64()) + } + if annotatefEvent.Name != "annotate67890" { + t.Errorf("Got annotatefEvent.Name = %v, expected annotate67890", annotatefEvent.Name) + } + if v := annotateEvent.Attributes[label.Key("string")]; v.AsString() != "annotateval" { + t.Errorf("Got annotateEvent.Attributes[string] = %v, expected annotateval", v.AsString()) + } + if sendEvent.Name != "message send" { + t.Errorf("Got sendEvent.Name = %v, expected message send", sendEvent.Name) + } + if v := sendEvent.Attributes[uncompressedKey]; v.AsInt64() != 456 { + t.Errorf("Got sendEvent.Attributes[uncompressedKey] = %v, expected 456", v.AsInt64()) + } + if v := sendEvent.Attributes[compressedKey]; v.AsInt64() != 789 { + t.Errorf("Got sendEvent.Attributes[compressedKey] = %v, expected 789", v.AsInt64()) + } + if receiveEvent.Name != "message receive" { + t.Errorf("Got receiveEvent.Name = %v, expected message receive", receiveEvent.Name) + } + if v := receiveEvent.Attributes[uncompressedKey]; v.AsInt64() != 135 { + t.Errorf("Got receiveEvent.Attributes[uncompressedKey] = %v, expected 135", v.AsInt64()) + } + if v := receiveEvent.Attributes[compressedKey]; v.AsInt64() != 369 { + t.Errorf("Got receiveEvent.Attributes[compressedKey] = %v, expected 369", v.AsInt64()) + } +} diff --git a/bridge/opencensus/go.mod b/bridge/opencensus/go.mod new file mode 100644 index 00000000000..a9960958414 --- /dev/null +++ b/bridge/opencensus/go.mod @@ -0,0 +1,10 @@ +module go.opentelemetry.io/opentelemetry-go/bridge/opencensus + +go 1.15 + +require ( + go.opencensus.io v0.22.6-0.20201102222123-380f4078db9f + go.opentelemetry.io/otel v0.13.0 +) + +replace go.opentelemetry.io/otel => ../.. diff --git a/bridge/opencensus/go.sum b/bridge/opencensus/go.sum new file mode 100644 index 00000000000..3d2eb5226b8 --- /dev/null +++ b/bridge/opencensus/go.sum @@ -0,0 +1,59 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 h1:ZgQEtGgCBiWRM39fZuwSd1LwSqqSW0hOdXCYYDX0R3I= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +go.opencensus.io v0.22.6-0.20201102222123-380f4078db9f h1:IUmbcoP9XyEXW+R9AbrZgDvaYVfTbISN92Y5RIV+Mx4= +go.opencensus.io v0.22.6-0.20201102222123-380f4078db9f/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/bridge/opentracing/bridge.go b/bridge/opentracing/bridge.go index 402400b9a75..87449f5caaf 100644 --- a/bridge/opentracing/bridge.go +++ b/bridge/opentracing/bridge.go @@ -32,18 +32,19 @@ import ( "go.opentelemetry.io/otel/internal/trace/noop" otelparent "go.opentelemetry.io/otel/internal/trace/parent" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/bridge/opentracing/migration" ) type bridgeSpanContext struct { baggageItems baggage.Map - otelSpanContext otel.SpanContext + otelSpanContext trace.SpanContext } var _ ot.SpanContext = &bridgeSpanContext{} -func newBridgeSpanContext(otelSpanContext otel.SpanContext, parentOtSpanContext ot.SpanContext) *bridgeSpanContext { +func newBridgeSpanContext(otelSpanContext trace.SpanContext, parentOtSpanContext ot.SpanContext) *bridgeSpanContext { bCtx := &bridgeSpanContext{ baggageItems: baggage.NewEmptyMap(), otelSpanContext: otelSpanContext, @@ -75,7 +76,7 @@ func (c *bridgeSpanContext) baggageItem(restrictedKey string) string { } type bridgeSpan struct { - otelSpan otel.Span + otelSpan trace.Span ctx *bridgeSpanContext tracer *BridgeTracer skipDeferHook bool @@ -84,7 +85,7 @@ type bridgeSpan struct { var _ ot.Span = &bridgeSpan{} -func newBridgeSpan(otelSpan otel.Span, bridgeSC *bridgeSpanContext, tracer *BridgeTracer) *bridgeSpan { +func newBridgeSpan(otelSpan trace.Span, bridgeSC *bridgeSpanContext, tracer *BridgeTracer) *bridgeSpan { return &bridgeSpan{ otelSpan: otelSpan, ctx: bridgeSC, @@ -99,10 +100,10 @@ func (s *bridgeSpan) Finish() { } func (s *bridgeSpan) FinishWithOptions(opts ot.FinishOptions) { - var otelOpts []otel.SpanOption + var otelOpts []trace.SpanOption if !opts.FinishTime.IsZero() { - otelOpts = append(otelOpts, otel.WithTimestamp(opts.FinishTime)) + otelOpts = append(otelOpts, trace.WithTimestamp(opts.FinishTime)) } for _, record := range opts.LogRecords { s.logRecord(record) @@ -116,8 +117,8 @@ func (s *bridgeSpan) FinishWithOptions(opts ot.FinishOptions) { func (s *bridgeSpan) logRecord(record ot.LogRecord) { s.otelSpan.AddEvent( "", - otel.WithTimestamp(record.Timestamp), - otel.WithAttributes(otLogFieldsToOTelLabels(record.Fields)...), + trace.WithTimestamp(record.Timestamp), + trace.WithAttributes(otLogFieldsToOTelLabels(record.Fields)...), ) } @@ -147,7 +148,7 @@ func (s *bridgeSpan) SetTag(key string, value interface{}) ot.Span { func (s *bridgeSpan) LogFields(fields ...otlog.Field) { s.otelSpan.AddEvent( "", - otel.WithAttributes(otLogFieldsToOTelLabels(fields)...), + trace.WithAttributes(otLogFieldsToOTelLabels(fields)...), ) } @@ -265,13 +266,13 @@ func (s *bridgeSpan) Log(data ot.LogData) { type bridgeSetTracer struct { isSet bool - otelTracer otel.Tracer + otelTracer trace.Tracer warningHandler BridgeWarningHandler warnOnce sync.Once } -func (s *bridgeSetTracer) tracer() otel.Tracer { +func (s *bridgeSetTracer) tracer() trace.Tracer { if !s.isSet { s.warnOnce.Do(func() { s.warningHandler("The OpenTelemetry tracer is not set, default no-op tracer is used! Call SetOpenTelemetryTracer to set it up.\n") @@ -323,7 +324,7 @@ func (t *BridgeTracer) SetWarningHandler(handler BridgeWarningHandler) { // SetWarningHandler overrides the underlying OpenTelemetry // tracer. The passed tracer should know how to operate in the // environment that uses OpenTracing API. -func (t *BridgeTracer) SetOpenTelemetryTracer(tracer otel.Tracer) { +func (t *BridgeTracer) SetOpenTelemetryTracer(tracer trace.Tracer) { t.setTracer.otelTracer = tracer t.setTracer.isSet = true } @@ -394,16 +395,16 @@ func (t *BridgeTracer) StartSpan(operationName string, opts ...ot.StartSpanOptio attributes, kind, hadTrueErrorTag := otTagsToOTelAttributesKindAndError(sso.Tags) checkCtx := migration.WithDeferredSetup(context.Background()) if parentBridgeSC != nil { - checkCtx = otel.ContextWithRemoteSpanContext(checkCtx, parentBridgeSC.otelSpanContext) + checkCtx = trace.ContextWithRemoteSpanContext(checkCtx, parentBridgeSC.otelSpanContext) } checkCtx2, otelSpan := t.setTracer.tracer().Start( checkCtx, operationName, - otel.WithAttributes(attributes...), - otel.WithTimestamp(sso.StartTime), - otel.WithLinks(links...), - otel.WithRecord(), - otel.WithSpanKind(kind), + trace.WithAttributes(attributes...), + trace.WithTimestamp(sso.StartTime), + trace.WithLinks(links...), + trace.WithRecord(), + trace.WithSpanKind(kind), ) if checkCtx != checkCtx2 { t.warnOnce.Do(func() { @@ -435,7 +436,7 @@ func (t *BridgeTracer) StartSpan(operationName string, opts ...ot.StartSpanOptio // This function should be used by the OpenTelemetry tracers that want // to be aware how to operate in the environment using OpenTracing // API. -func (t *BridgeTracer) ContextWithBridgeSpan(ctx context.Context, span otel.Span) context.Context { +func (t *BridgeTracer) ContextWithBridgeSpan(ctx context.Context, span trace.Span) context.Context { var otSpanContext ot.SpanContext if parentSpan := ot.SpanFromContext(ctx); parentSpan != nil { otSpanContext = parentSpan.Context() @@ -465,8 +466,8 @@ func (t *BridgeTracer) ContextWithSpanHook(ctx context.Context, span ot.Span) co return ctx } -func otTagsToOTelAttributesKindAndError(tags map[string]interface{}) ([]label.KeyValue, otel.SpanKind, bool) { - kind := otel.SpanKindInternal +func otTagsToOTelAttributesKindAndError(tags map[string]interface{}) ([]label.KeyValue, trace.SpanKind, bool) { + kind := trace.SpanKindInternal err := false var pairs []label.KeyValue for k, v := range tags { @@ -475,13 +476,13 @@ func otTagsToOTelAttributesKindAndError(tags map[string]interface{}) ([]label.Ke if s, ok := v.(string); ok { switch strings.ToLower(s) { case "client": - kind = otel.SpanKindClient + kind = trace.SpanKindClient case "server": - kind = otel.SpanKindServer + kind = trace.SpanKindServer case "producer": - kind = otel.SpanKindProducer + kind = trace.SpanKindProducer case "consumer": - kind = otel.SpanKindConsumer + kind = trace.SpanKindConsumer } } case string(otext.Error): @@ -527,10 +528,10 @@ func otTagToOTelLabelKey(k string) label.Key { return label.Key(k) } -func otSpanReferencesToParentAndLinks(references []ot.SpanReference) (*bridgeSpanContext, []otel.Link) { +func otSpanReferencesToParentAndLinks(references []ot.SpanReference) (*bridgeSpanContext, []trace.Link) { var ( parent *bridgeSpanContext - links []otel.Link + links []trace.Link ) for _, reference := range references { bridgeSC, ok := reference.ReferencedContext.(*bridgeSpanContext) @@ -556,8 +557,8 @@ func otSpanReferencesToParentAndLinks(references []ot.SpanReference) (*bridgeSpa return parent, links } -func otSpanReferenceToOTelLink(bridgeSC *bridgeSpanContext, refType ot.SpanReferenceType) otel.Link { - return otel.Link{ +func otSpanReferenceToOTelLink(bridgeSC *bridgeSpanContext, refType ot.SpanReferenceType) trace.Link { + return trace.Link{ SpanContext: bridgeSC.otelSpanContext, Attributes: otSpanReferenceTypeToOTelLinkAttributes(refType), } @@ -586,11 +587,11 @@ func otSpanReferenceTypeToString(refType ot.SpanReferenceType) string { // fakeSpan is just a holder of span context, nothing more. It's for // propagators, so they can get the span context from Go context. type fakeSpan struct { - otel.Span - sc otel.SpanContext + trace.Span + sc trace.SpanContext } -func (s fakeSpan) SpanContext() otel.SpanContext { +func (s fakeSpan) SpanContext() trace.SpanContext { return s.sc } @@ -618,7 +619,7 @@ func (t *BridgeTracer) Inject(sm ot.SpanContext, format interface{}, carrier int Span: noop.Span, sc: bridgeSC.otelSpanContext, } - ctx := otel.ContextWithSpan(context.Background(), fs) + ctx := trace.ContextWithSpan(context.Background(), fs) ctx = baggage.ContextWithMap(ctx, bridgeSC.baggageItems) t.getPropagator().Inject(ctx, header) return nil diff --git a/bridge/opentracing/internal/mock.go b/bridge/opentracing/internal/mock.go index 48d08eec890..b805e968e6e 100644 --- a/bridge/opentracing/internal/mock.go +++ b/bridge/opentracing/internal/mock.go @@ -21,11 +21,11 @@ import ( "sync" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/internal/baggage" otelparent "go.opentelemetry.io/otel/internal/trace/parent" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/bridge/opentracing/migration" ) @@ -47,15 +47,15 @@ type MockContextKeyValue struct { type MockTracer struct { Resources baggage.Map FinishedSpans []*MockSpan - SpareTraceIDs []otel.TraceID - SpareSpanIDs []otel.SpanID + SpareTraceIDs []trace.TraceID + SpareSpanIDs []trace.SpanID SpareContextKeyValues []MockContextKeyValue randLock sync.Mutex rand *rand.Rand } -var _ otel.Tracer = &MockTracer{} +var _ trace.Tracer = &MockTracer{} var _ migration.DeferredContextSetupTracerExtension = &MockTracer{} func NewMockTracer() *MockTracer { @@ -70,13 +70,13 @@ func NewMockTracer() *MockTracer { } } -func (t *MockTracer) Start(ctx context.Context, name string, opts ...otel.SpanOption) (context.Context, otel.Span) { - config := otel.NewSpanConfig(opts...) +func (t *MockTracer) Start(ctx context.Context, name string, opts ...trace.SpanOption) (context.Context, trace.Span) { + config := trace.NewSpanConfig(opts...) startTime := config.Timestamp if startTime.IsZero() { startTime = time.Now() } - spanContext := otel.SpanContext{ + spanContext := trace.SpanContext{ TraceID: t.getTraceID(ctx, config), SpanID: t.getSpanID(), TraceFlags: 0, @@ -93,10 +93,10 @@ func (t *MockTracer) Start(ctx context.Context, name string, opts ...otel.SpanOp EndTime: time.Time{}, ParentSpanID: t.getParentSpanID(ctx, config), Events: nil, - SpanKind: otel.ValidateSpanKind(config.SpanKind), + SpanKind: trace.ValidateSpanKind(config.SpanKind), } if !migration.SkipContextSetup(ctx) { - ctx = otel.ContextWithSpan(ctx, span) + ctx = trace.ContextWithSpan(ctx, span) ctx = t.addSpareContextValue(ctx) } return ctx, span @@ -115,7 +115,7 @@ func (t *MockTracer) addSpareContextValue(ctx context.Context) context.Context { return ctx } -func (t *MockTracer) getTraceID(ctx context.Context, config *otel.SpanConfig) otel.TraceID { +func (t *MockTracer) getTraceID(ctx context.Context, config *trace.SpanConfig) trace.TraceID { if parent := t.getParentSpanContext(ctx, config); parent.IsValid() { return parent.TraceID } @@ -130,19 +130,19 @@ func (t *MockTracer) getTraceID(ctx context.Context, config *otel.SpanConfig) ot return t.getRandTraceID() } -func (t *MockTracer) getParentSpanID(ctx context.Context, config *otel.SpanConfig) otel.SpanID { +func (t *MockTracer) getParentSpanID(ctx context.Context, config *trace.SpanConfig) trace.SpanID { if parent := t.getParentSpanContext(ctx, config); parent.IsValid() { return parent.SpanID } - return otel.SpanID{} + return trace.SpanID{} } -func (t *MockTracer) getParentSpanContext(ctx context.Context, config *otel.SpanConfig) otel.SpanContext { +func (t *MockTracer) getParentSpanContext(ctx context.Context, config *trace.SpanConfig) trace.SpanContext { spanCtx, _, _ := otelparent.GetSpanContextAndLinks(ctx, config.NewRoot) return spanCtx } -func (t *MockTracer) getSpanID() otel.SpanID { +func (t *MockTracer) getSpanID() trace.SpanID { if len(t.SpareSpanIDs) > 0 { spanID := t.SpareSpanIDs[0] t.SpareSpanIDs = t.SpareSpanIDs[1:] @@ -154,27 +154,27 @@ func (t *MockTracer) getSpanID() otel.SpanID { return t.getRandSpanID() } -func (t *MockTracer) getRandSpanID() otel.SpanID { +func (t *MockTracer) getRandSpanID() trace.SpanID { t.randLock.Lock() defer t.randLock.Unlock() - sid := otel.SpanID{} + sid := trace.SpanID{} t.rand.Read(sid[:]) return sid } -func (t *MockTracer) getRandTraceID() otel.TraceID { +func (t *MockTracer) getRandTraceID() trace.TraceID { t.randLock.Lock() defer t.randLock.Unlock() - tid := otel.TraceID{} + tid := trace.TraceID{} t.rand.Read(tid[:]) return tid } -func (t *MockTracer) DeferredContextSetupHook(ctx context.Context, span otel.Span) context.Context { +func (t *MockTracer) DeferredContextSetupHook(ctx context.Context, span trace.Span) context.Context { return t.addSpareContextValue(ctx) } @@ -186,22 +186,22 @@ type MockEvent struct { type MockSpan struct { mockTracer *MockTracer - officialTracer otel.Tracer - spanContext otel.SpanContext - SpanKind otel.SpanKind + officialTracer trace.Tracer + spanContext trace.SpanContext + SpanKind trace.SpanKind recording bool Attributes baggage.Map StartTime time.Time EndTime time.Time - ParentSpanID otel.SpanID + ParentSpanID trace.SpanID Events []MockEvent } -var _ otel.Span = &MockSpan{} +var _ trace.Span = &MockSpan{} var _ migration.OverrideTracerSpanExtension = &MockSpan{} -func (s *MockSpan) SpanContext() otel.SpanContext { +func (s *MockSpan) SpanContext() trace.SpanContext { return s.spanContext } @@ -231,11 +231,11 @@ func (s *MockSpan) applyUpdate(update baggage.MapUpdate) { s.Attributes = s.Attributes.Apply(update) } -func (s *MockSpan) End(options ...otel.SpanOption) { +func (s *MockSpan) End(options ...trace.SpanOption) { if !s.EndTime.IsZero() { return // already finished } - config := otel.NewSpanConfig(options...) + config := trace.NewSpanConfig(options...) endTime := config.Timestamp if endTime.IsZero() { endTime = time.Now() @@ -244,7 +244,7 @@ func (s *MockSpan) End(options ...otel.SpanOption) { s.mockTracer.FinishedSpans = append(s.mockTracer.FinishedSpans, s) } -func (s *MockSpan) RecordError(err error, opts ...otel.EventOption) { +func (s *MockSpan) RecordError(err error, opts ...trace.EventOption) { if err == nil { return // no-op on nil error } @@ -254,19 +254,19 @@ func (s *MockSpan) RecordError(err error, opts ...otel.EventOption) { } s.SetStatus(codes.Error, "") - opts = append(opts, otel.WithAttributes( + opts = append(opts, trace.WithAttributes( label.String("error.type", reflect.TypeOf(err).String()), label.String("error.message", err.Error()), )) s.AddEvent("error", opts...) } -func (s *MockSpan) Tracer() otel.Tracer { +func (s *MockSpan) Tracer() trace.Tracer { return s.officialTracer } -func (s *MockSpan) AddEvent(name string, o ...otel.EventOption) { - c := otel.NewEventConfig(o...) +func (s *MockSpan) AddEvent(name string, o ...trace.EventOption) { + c := trace.NewEventConfig(o...) s.Events = append(s.Events, MockEvent{ Timestamp: c.Timestamp, Name: name, @@ -276,6 +276,6 @@ func (s *MockSpan) AddEvent(name string, o ...otel.EventOption) { }) } -func (s *MockSpan) OverrideTracer(tracer otel.Tracer) { +func (s *MockSpan) OverrideTracer(tracer trace.Tracer) { s.officialTracer = tracer } diff --git a/bridge/opentracing/migration/api.go b/bridge/opentracing/migration/api.go index ea6d3afaa9a..c18fcea218b 100644 --- a/bridge/opentracing/migration/api.go +++ b/bridge/opentracing/migration/api.go @@ -20,7 +20,7 @@ package migration // import "go.opentelemetry.io/otel/bridge/opentracing/migrati import ( "context" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" ) // DeferredContextSetupTracerExtension is an interface an @@ -41,7 +41,7 @@ type DeferredContextSetupTracerExtension interface { // opentracing.ContextWithSpan happens. When bridge // OpenTracing tracer calls OpenTelemetry tracer's Start() // function, it passes a context that shouldn't be modified. - DeferredContextSetupHook(ctx context.Context, span otel.Span) context.Context + DeferredContextSetupHook(ctx context.Context, span trace.Span) context.Context } // OverrideTracerSpanExtension is an interface an OpenTelemetry span @@ -56,7 +56,7 @@ type DeferredContextSetupTracerExtension interface { // OpenTelemetry Span object and have WrapperTracer to alter the // current OpenTelemetry span in the context so it points to the // wrapped object, so the code in the tracer like -// `otel.SpanFromContent().(*realSpan)` would still work. Another +// `trace.SpanFromContent().(*realSpan)` would still work. Another // argument for getting rid of this interface is that is only called // by the WrapperTracer - WrapperTracer likely shouldn't require any // changes in the underlying OpenTelemetry tracer to have things @@ -72,5 +72,5 @@ type OverrideTracerSpanExtension interface { // API calls. In such case, there is no need to use the // WrapperTracer and thus no need to override the result of // the Tracer() function. - OverrideTracer(tracer otel.Tracer) + OverrideTracer(tracer trace.Tracer) } diff --git a/bridge/opentracing/mix_test.go b/bridge/opentracing/mix_test.go index 15c9e03c626..b6814ae648f 100644 --- a/bridge/opentracing/mix_test.go +++ b/bridge/opentracing/mix_test.go @@ -21,10 +21,10 @@ import ( ot "github.com/opentracing/opentracing-go" - "go.opentelemetry.io/otel" otelglobal "go.opentelemetry.io/otel/global" otelbaggage "go.opentelemetry.io/otel/internal/baggage" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/bridge/opentracing/internal" ) @@ -142,8 +142,8 @@ func TestMixedAPIs(t *testing.T) { // simple test type simpleTest struct { - traceID otel.TraceID - spanIDs []otel.SpanID + traceID trace.TraceID + spanIDs []trace.SpanID } func newSimpleTest() *simpleTest { @@ -177,11 +177,11 @@ func (st *simpleTest) noop(t *testing.T, ctx context.Context) context.Context { // current/active span test type currentActiveSpanTest struct { - traceID otel.TraceID - spanIDs []otel.SpanID + traceID trace.TraceID + spanIDs []trace.SpanID - recordedCurrentOtelSpanIDs []otel.SpanID - recordedActiveOTSpanIDs []otel.SpanID + recordedCurrentOtelSpanIDs []trace.SpanID + recordedActiveOTSpanIDs []trace.SpanID } func newCurrentActiveSpanTest() *currentActiveSpanTest { @@ -229,10 +229,10 @@ func (cast *currentActiveSpanTest) runOTOtelOT(t *testing.T, ctx context.Context } func (cast *currentActiveSpanTest) recordSpans(t *testing.T, ctx context.Context) context.Context { - spanID := otel.SpanContextFromContext(ctx).SpanID + spanID := trace.SpanContextFromContext(ctx).SpanID cast.recordedCurrentOtelSpanIDs = append(cast.recordedCurrentOtelSpanIDs, spanID) - spanID = otel.SpanID{} + spanID = trace.SpanID{} if bridgeSpan, ok := ot.SpanFromContext(ctx).(*bridgeSpan); ok { spanID = bridgeSpan.otelSpan.SpanContext().SpanID } @@ -423,7 +423,7 @@ func (bip *baggageItemsPreservationTest) addAndRecordBaggage(t *testing.T, ctx c type tracerMessTest struct { recordedOTSpanTracers []ot.Tracer - recordedOtelSpanTracers []otel.Tracer + recordedOtelSpanTracers []trace.Tracer } func newTracerMessTest() *tracerMessTest { @@ -475,7 +475,7 @@ func (tm *tracerMessTest) recordTracers(t *testing.T, ctx context.Context) conte tm.recordedOTSpanTracers = append(tm.recordedOTSpanTracers, otSpan.Tracer()) } - otelSpan := otel.SpanFromContext(ctx) + otelSpan := trace.SpanFromContext(ctx) tm.recordedOtelSpanTracers = append(tm.recordedOtelSpanTracers, otelSpan.Tracer()) return ctx } @@ -613,23 +613,23 @@ func generateBaggageKeys(key string) (otKey, otelKey string) { // helpers -func checkTraceAndSpans(t *testing.T, tracer *internal.MockTracer, expectedTraceID otel.TraceID, expectedSpanIDs []otel.SpanID) { +func checkTraceAndSpans(t *testing.T, tracer *internal.MockTracer, expectedTraceID trace.TraceID, expectedSpanIDs []trace.SpanID) { expectedSpanCount := len(expectedSpanIDs) // reverse spanIDs, since first span ID belongs to root, that // finishes last - spanIDs := make([]otel.SpanID, len(expectedSpanIDs)) + spanIDs := make([]trace.SpanID, len(expectedSpanIDs)) copy(spanIDs, expectedSpanIDs) reverse(len(spanIDs), func(i, j int) { spanIDs[i], spanIDs[j] = spanIDs[j], spanIDs[i] }) // the last finished span has no parent - parentSpanIDs := append(spanIDs[1:], otel.SpanID{}) + parentSpanIDs := append(spanIDs[1:], trace.SpanID{}) - sks := map[otel.SpanID]otel.SpanKind{ - {125}: otel.SpanKindProducer, - {124}: otel.SpanKindInternal, - {123}: otel.SpanKindClient, + sks := map[trace.SpanID]trace.SpanKind{ + {125}: trace.SpanKindProducer, + {124}: trace.SpanKindInternal, + {123}: trace.SpanKindClient, } if len(tracer.FinishedSpans) != expectedSpanCount { @@ -660,12 +660,12 @@ func reverse(length int, swap func(i, j int)) { } } -func simpleTraceID() otel.TraceID { +func simpleTraceID() trace.TraceID { return [16]byte{123, 42} } -func simpleSpanIDs(count int) []otel.SpanID { - base := []otel.SpanID{ +func simpleSpanIDs(count int) []trace.SpanID { + base := []trace.SpanID{ {123}, {124}, {125}, @@ -685,7 +685,7 @@ func min(a, b int) int { func runOtelOTOtel(t *testing.T, ctx context.Context, name string, callback func(*testing.T, context.Context) context.Context) { tr := otelglobal.Tracer("") - ctx, span := tr.Start(ctx, fmt.Sprintf("%s_Otel_OTOtel", name), otel.WithSpanKind(otel.SpanKindClient)) + ctx, span := tr.Start(ctx, fmt.Sprintf("%s_Otel_OTOtel", name), trace.WithSpanKind(trace.SpanKindClient)) defer span.End() ctx = callback(t, ctx) func(ctx2 context.Context) { @@ -693,7 +693,7 @@ func runOtelOTOtel(t *testing.T, ctx context.Context, name string, callback func defer span.Finish() ctx2 = callback(t, ctx2) func(ctx3 context.Context) { - ctx3, span := tr.Start(ctx3, fmt.Sprintf("%sOtelOT_Otel_", name), otel.WithSpanKind(otel.SpanKindProducer)) + ctx3, span := tr.Start(ctx3, fmt.Sprintf("%sOtelOT_Otel_", name), trace.WithSpanKind(trace.SpanKindProducer)) defer span.End() _ = callback(t, ctx3) }(ctx2) diff --git a/bridge/opentracing/util.go b/bridge/opentracing/util.go index 9dea292b733..4914607f7f8 100644 --- a/bridge/opentracing/util.go +++ b/bridge/opentracing/util.go @@ -17,7 +17,7 @@ package opentracing // import "go.opentelemetry.io/otel/bridge/opentracing" import ( "context" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" ) // NewTracerPair is a utility function that creates a BridgeTracer and a @@ -26,14 +26,14 @@ import ( // that wraps the passed tracer. BridgeTracer and WrapperTracerProvider are // returned to the caller and the caller is expected to register BridgeTracer // with opentracing and WrapperTracerProvider with opentelemetry. -func NewTracerPair(tracer otel.Tracer) (*BridgeTracer, *WrapperTracerProvider) { +func NewTracerPair(tracer trace.Tracer) (*BridgeTracer, *WrapperTracerProvider) { bridgeTracer := NewBridgeTracer() wrapperProvider := NewWrappedTracerProvider(bridgeTracer, tracer) bridgeTracer.SetOpenTelemetryTracer(wrapperProvider.Tracer("")) return bridgeTracer, wrapperProvider } -func NewTracerPairWithContext(ctx context.Context, tracer otel.Tracer) (context.Context, *BridgeTracer, *WrapperTracerProvider) { +func NewTracerPairWithContext(ctx context.Context, tracer trace.Tracer) (context.Context, *BridgeTracer, *WrapperTracerProvider) { bridgeTracer, wrapperProvider := NewTracerPair(tracer) ctx = bridgeTracer.NewHookedContext(ctx) return ctx, bridgeTracer, wrapperProvider diff --git a/bridge/opentracing/wrapper.go b/bridge/opentracing/wrapper.go index d13c7288416..149e520a634 100644 --- a/bridge/opentracing/wrapper.go +++ b/bridge/opentracing/wrapper.go @@ -17,7 +17,8 @@ package opentracing // import "go.opentelemetry.io/otel/bridge/opentracing" import ( "context" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" + "go.opentelemetry.io/otel/bridge/opentracing/migration" ) @@ -25,16 +26,16 @@ type WrapperTracerProvider struct { wTracer *WrapperTracer } -var _ otel.TracerProvider = (*WrapperTracerProvider)(nil) +var _ trace.TracerProvider = (*WrapperTracerProvider)(nil) // Tracer returns the WrapperTracer associated with the WrapperTracerProvider. -func (p *WrapperTracerProvider) Tracer(_ string, _ ...otel.TracerOption) otel.Tracer { +func (p *WrapperTracerProvider) Tracer(_ string, _ ...trace.TracerOption) trace.Tracer { return p.wTracer } // NewWrappedTracerProvider creates a new trace provider that creates a single // instance of WrapperTracer that wraps OpenTelemetry tracer. -func NewWrappedTracerProvider(bridge *BridgeTracer, tracer otel.Tracer) *WrapperTracerProvider { +func NewWrappedTracerProvider(bridge *BridgeTracer, tracer trace.Tracer) *WrapperTracerProvider { return &WrapperTracerProvider{ wTracer: NewWrapperTracer(bridge, tracer), } @@ -50,30 +51,30 @@ func NewWrappedTracerProvider(bridge *BridgeTracer, tracer otel.Tracer) *Wrapper // used. type WrapperTracer struct { bridge *BridgeTracer - tracer otel.Tracer + tracer trace.Tracer } -var _ otel.Tracer = &WrapperTracer{} +var _ trace.Tracer = &WrapperTracer{} var _ migration.DeferredContextSetupTracerExtension = &WrapperTracer{} // NewWrapperTracer wraps the passed tracer and also talks to the // passed bridge tracer when setting up the context with the new // active OpenTracing span. -func NewWrapperTracer(bridge *BridgeTracer, tracer otel.Tracer) *WrapperTracer { +func NewWrapperTracer(bridge *BridgeTracer, tracer trace.Tracer) *WrapperTracer { return &WrapperTracer{ bridge: bridge, tracer: tracer, } } -func (t *WrapperTracer) otelTracer() otel.Tracer { +func (t *WrapperTracer) otelTracer() trace.Tracer { return t.tracer } // Start forwards the call to the wrapped tracer. It also tries to // override the tracer of the returned span if the span implements the // OverrideTracerSpanExtension interface. -func (t *WrapperTracer) Start(ctx context.Context, name string, opts ...otel.SpanOption) (context.Context, otel.Span) { +func (t *WrapperTracer) Start(ctx context.Context, name string, opts ...trace.SpanOption) (context.Context, trace.Span) { ctx, span := t.otelTracer().Start(ctx, name, opts...) if spanWithExtension, ok := span.(migration.OverrideTracerSpanExtension); ok { spanWithExtension.OverrideTracer(t) @@ -88,10 +89,10 @@ func (t *WrapperTracer) Start(ctx context.Context, name string, opts ...otel.Spa // DeferredContextSetupTracerExtension interface. It will try to // forward the call to the wrapped tracer if it implements the // interface. -func (t *WrapperTracer) DeferredContextSetupHook(ctx context.Context, span otel.Span) context.Context { +func (t *WrapperTracer) DeferredContextSetupHook(ctx context.Context, span trace.Span) context.Context { if tracerWithExtension, ok := t.otelTracer().(migration.DeferredContextSetupTracerExtension); ok { ctx = tracerWithExtension.DeferredContextSetupHook(ctx, span) } - ctx = otel.ContextWithSpan(ctx, span) + ctx = trace.ContextWithSpan(ctx, span) return ctx } diff --git a/example/basic/main.go b/example/basic/main.go index f4f094d8255..93d6fa042c2 100644 --- a/example/basic/main.go +++ b/example/basic/main.go @@ -22,11 +22,13 @@ import ( "go.opentelemetry.io/otel/exporters/stdout" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagators" "go.opentelemetry.io/otel/sdk/metric/controller/push" "go.opentelemetry.io/otel/sdk/metric/processor/basic" "go.opentelemetry.io/otel/sdk/metric/selector/simple" sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" ) var ( @@ -67,14 +69,14 @@ func main() { commonLabels := []label.KeyValue{lemonsKey.Int(10), label.String("A", "1"), label.String("B", "2"), label.String("C", "3")} - oneMetricCB := func(_ context.Context, result otel.Float64ObserverResult) { + oneMetricCB := func(_ context.Context, result metric.Float64ObserverResult) { result.Observe(1, commonLabels...) } - _ = otel.Must(meter).NewFloat64ValueObserver("ex.com.one", oneMetricCB, - otel.WithDescription("A ValueObserver set to 1.0"), + _ = metric.Must(meter).NewFloat64ValueObserver("ex.com.one", oneMetricCB, + metric.WithDescription("A ValueObserver set to 1.0"), ) - valuerecorderTwo := otel.Must(meter).NewFloat64ValueRecorder("ex.com.two") + valuerecorderTwo := metric.Must(meter).NewFloat64ValueRecorder("ex.com.two") ctx := context.Background() ctx = otel.ContextWithBaggageValues(ctx, fooKey.String("foo1"), barKey.String("bar1")) @@ -83,11 +85,11 @@ func main() { defer valuerecorder.Unbind() err = func(ctx context.Context) error { - var span otel.Span + var span trace.Span ctx, span = tracer.Start(ctx, "operation") defer span.End() - span.AddEvent("Nice operation!", otel.WithAttributes(label.Int("bogons", 100))) + span.AddEvent("Nice operation!", trace.WithAttributes(label.Int("bogons", 100))) span.SetAttributes(anotherKey.String("yes")) meter.RecordBatch( @@ -99,7 +101,7 @@ func main() { ) return func(ctx context.Context) error { - var span otel.Span + var span trace.Span ctx, span = tracer.Start(ctx, "Sub operation...") defer span.End() diff --git a/example/namedtracer/foo/foo.go b/example/namedtracer/foo/foo.go index d91b99362c6..c8ee668c604 100644 --- a/example/namedtracer/foo/foo.go +++ b/example/namedtracer/foo/foo.go @@ -17,9 +17,9 @@ package foo // import "go.opentelemetry.io/otel/example/namedtracer/foo" import ( "context" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" ) var ( @@ -33,7 +33,7 @@ func SubOperation(ctx context.Context) error { // for its component to get the instance of the provider. tr := global.Tracer("example/namedtracer/foo") - var span otel.Span + var span trace.Span _, span = tr.Start(ctx, "Sub operation...") defer span.End() span.SetAttributes(lemonsKey.String("five")) diff --git a/example/namedtracer/main.go b/example/namedtracer/main.go index aacd97d8f06..75995ee75cc 100644 --- a/example/namedtracer/main.go +++ b/example/namedtracer/main.go @@ -24,6 +24,7 @@ import ( "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" ) var ( @@ -64,10 +65,10 @@ func main() { defer func() { _ = tp.Shutdown(ctx) }() ctx = otel.ContextWithBaggageValues(ctx, fooKey.String("foo1"), barKey.String("bar1")) - var span otel.Span + var span trace.Span ctx, span = tracer.Start(ctx, "operation") defer span.End() - span.AddEvent("Nice operation!", otel.WithAttributes(label.Int("bogons", 100))) + span.AddEvent("Nice operation!", trace.WithAttributes(label.Int("bogons", 100))) span.SetAttributes(anotherKey.String("yes")) if err := foo.SubOperation(ctx); err != nil { panic(err) diff --git a/example/otel-collector/main.go b/example/otel-collector/main.go index acbe3373107..732a31e165e 100644 --- a/example/otel-collector/main.go +++ b/example/otel-collector/main.go @@ -25,10 +25,10 @@ import ( "google.golang.org/grpc" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/otlp" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagators" "go.opentelemetry.io/otel/sdk/metric/controller/push" "go.opentelemetry.io/otel/sdk/metric/processor/basic" @@ -36,6 +36,7 @@ import ( "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/semconv" + "go.opentelemetry.io/otel/trace" ) // Initializes an OTLP exporter, and configures the corresponding trace and @@ -110,10 +111,10 @@ func main() { } // Recorder metric example - valuerecorder := otel.Must(meter). + valuerecorder := metric.Must(meter). NewFloat64Counter( "an_important_metric", - otel.WithDescription("Measures the cumulative epicness of the app"), + metric.WithDescription("Measures the cumulative epicness of the app"), ).Bind(commonLabels...) defer valuerecorder.Unbind() @@ -121,7 +122,7 @@ func main() { ctx, span := tracer.Start( context.Background(), "CollectorExporter-Example", - otel.WithAttributes(commonLabels...)) + trace.WithAttributes(commonLabels...)) defer span.End() for i := 0; i < 10; i++ { _, iSpan := tracer.Start(ctx, fmt.Sprintf("Sample-%d", i)) diff --git a/example/prometheus/main.go b/example/prometheus/main.go index d229108898e..b3208da51d4 100644 --- a/example/prometheus/main.go +++ b/example/prometheus/main.go @@ -22,10 +22,10 @@ import ( "sync" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/metric/prometheus" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" ) var ( @@ -52,19 +52,19 @@ func main() { observerLock := new(sync.RWMutex) observerValueToReport := new(float64) observerLabelsToReport := new([]label.KeyValue) - cb := func(_ context.Context, result otel.Float64ObserverResult) { + cb := func(_ context.Context, result metric.Float64ObserverResult) { (*observerLock).RLock() value := *observerValueToReport labels := *observerLabelsToReport (*observerLock).RUnlock() result.Observe(value, labels...) } - _ = otel.Must(meter).NewFloat64ValueObserver("ex.com.one", cb, - otel.WithDescription("A ValueObserver set to 1.0"), + _ = metric.Must(meter).NewFloat64ValueObserver("ex.com.one", cb, + metric.WithDescription("A ValueObserver set to 1.0"), ) - valuerecorder := otel.Must(meter).NewFloat64ValueRecorder("ex.com.two") - counter := otel.Must(meter).NewFloat64Counter("ex.com.three") + valuerecorder := metric.Must(meter).NewFloat64ValueRecorder("ex.com.two") + counter := metric.Must(meter).NewFloat64Counter("ex.com.three") commonLabels := []label.KeyValue{lemonsKey.Int(10), label.String("A", "1"), label.String("B", "2"), label.String("C", "3")} notSoCommonLabels := []label.KeyValue{lemonsKey.Int(13)} diff --git a/exporters/metric/prometheus/example_test.go b/exporters/metric/prometheus/example_test.go index ac0c85a74f8..921a777b106 100644 --- a/exporters/metric/prometheus/example_test.go +++ b/exporters/metric/prometheus/example_test.go @@ -22,9 +22,9 @@ import ( "net/http" "net/http/httptest" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/metric/prometheus" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/sdk/metric/controller/pull" "go.opentelemetry.io/otel/sdk/resource" ) @@ -32,7 +32,7 @@ import ( // This test demonstrates that it is relatively difficult to setup a // Prometheus export pipeline: // -// 1. The default boundaries are difficult to pass, should be []float instead of []otel.Number +// 1. The default boundaries are difficult to pass, should be []float instead of []number.Number // // TODO: Address this issue. @@ -59,13 +59,13 @@ func ExampleNewExportPipeline() { ctx := context.Background() // Use two instruments - counter := otel.Must(meter).NewInt64Counter( + counter := metric.Must(meter).NewInt64Counter( "a.counter", - otel.WithDescription("Counts things"), + metric.WithDescription("Counts things"), ) - recorder := otel.Must(meter).NewInt64ValueRecorder( + recorder := metric.Must(meter).NewInt64ValueRecorder( "a.valuerecorder", - otel.WithDescription("Records values"), + metric.WithDescription("Records values"), ) counter.Add(ctx, 100, label.String("key", "value")) diff --git a/exporters/metric/prometheus/prometheus.go b/exporters/metric/prometheus/prometheus.go index b319f4e4a6f..811b82c4674 100644 --- a/exporters/metric/prometheus/prometheus.go +++ b/exporters/metric/prometheus/prometheus.go @@ -23,9 +23,10 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/controller/pull" @@ -155,7 +156,7 @@ func (e *Exporter) SetController(config Config, options ...pull.Option) { } // MeterProvider returns the MeterProvider of this exporter. -func (e *Exporter) MeterProvider() otel.MeterProvider { +func (e *Exporter) MeterProvider() metric.MeterProvider { return e.controller.MeterProvider() } @@ -166,13 +167,13 @@ func (e *Exporter) Controller() *pull.Controller { return e.controller } -func (e *Exporter) ExportKindFor(*otel.Descriptor, aggregation.Kind) export.ExportKind { +func (e *Exporter) ExportKindFor(desc *metric.Descriptor, kind aggregation.Kind) export.ExportKind { // NOTE: Summary values should use Delta aggregation, then be // combined into a sliding window, see the TODO below. // NOTE: Prometheus also supports a "GaugeDelta" exposition format, // which is expressed as a delta histogram. Need to understand if this // should be a default behavior for ValueRecorder/ValueObserver. - return export.CumulativeExporter + return export.CumulativeExportKindSelector().ExportKindFor(desc, kind) } func (e *Exporter) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -214,6 +215,7 @@ func (c *collector) Collect(ch chan<- prometheus.Metric) { err := ctrl.ForEach(c.exp, func(record export.Record) error { agg := record.Aggregation() numberKind := record.Descriptor().NumberKind() + instrumentKind := record.Descriptor().InstrumentKind() var labelKeys, labels []string mergeLabels(record, &labelKeys, &labels) @@ -236,9 +238,13 @@ func (c *collector) Collect(ch chan<- prometheus.Metric) { if err := c.exportSummary(ch, dist, numberKind, desc, labels); err != nil { return fmt.Errorf("exporting summary: %w", err) } - } else if sum, ok := agg.(aggregation.Sum); ok { - if err := c.exportCounter(ch, sum, numberKind, desc, labels); err != nil { - return fmt.Errorf("exporting counter: %w", err) + } else if sum, ok := agg.(aggregation.Sum); ok && instrumentKind.Monotonic() { + if err := c.exportMonotonicCounter(ch, sum, numberKind, desc, labels); err != nil { + return fmt.Errorf("exporting monotonic counter: %w", err) + } + } else if sum, ok := agg.(aggregation.Sum); ok && !instrumentKind.Monotonic() { + if err := c.exportNonMonotonicCounter(ch, sum, numberKind, desc, labels); err != nil { + return fmt.Errorf("exporting non monotonic counter: %w", err) } } else if lastValue, ok := agg.(aggregation.LastValue); ok { if err := c.exportLastValue(ch, lastValue, numberKind, desc, labels); err != nil { @@ -252,7 +258,7 @@ func (c *collector) Collect(ch chan<- prometheus.Metric) { } } -func (c *collector) exportLastValue(ch chan<- prometheus.Metric, lvagg aggregation.LastValue, kind otel.NumberKind, desc *prometheus.Desc, labels []string) error { +func (c *collector) exportLastValue(ch chan<- prometheus.Metric, lvagg aggregation.LastValue, kind number.Kind, desc *prometheus.Desc, labels []string) error { lv, _, err := lvagg.LastValue() if err != nil { return fmt.Errorf("error retrieving last value: %w", err) @@ -267,7 +273,22 @@ func (c *collector) exportLastValue(ch chan<- prometheus.Metric, lvagg aggregati return nil } -func (c *collector) exportCounter(ch chan<- prometheus.Metric, sum aggregation.Sum, kind otel.NumberKind, desc *prometheus.Desc, labels []string) error { +func (c *collector) exportNonMonotonicCounter(ch chan<- prometheus.Metric, sum aggregation.Sum, kind number.Kind, desc *prometheus.Desc, labels []string) error { + v, err := sum.Sum() + if err != nil { + return fmt.Errorf("error retrieving counter: %w", err) + } + + m, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, v.CoerceToFloat64(kind), labels...) + if err != nil { + return fmt.Errorf("error creating constant metric: %w", err) + } + + ch <- m + return nil +} + +func (c *collector) exportMonotonicCounter(ch chan<- prometheus.Metric, sum aggregation.Sum, kind number.Kind, desc *prometheus.Desc, labels []string) error { v, err := sum.Sum() if err != nil { return fmt.Errorf("error retrieving counter: %w", err) @@ -282,13 +303,13 @@ func (c *collector) exportCounter(ch chan<- prometheus.Metric, sum aggregation.S return nil } -func (c *collector) exportSummary(ch chan<- prometheus.Metric, dist aggregation.Distribution, kind otel.NumberKind, desc *prometheus.Desc, labels []string) error { +func (c *collector) exportSummary(ch chan<- prometheus.Metric, dist aggregation.Distribution, kind number.Kind, desc *prometheus.Desc, labels []string) error { count, err := dist.Count() if err != nil { return fmt.Errorf("error retrieving count: %w", err) } - var sum otel.Number + var sum number.Number sum, err = dist.Sum() if err != nil { return fmt.Errorf("error retrieving distribution sum: %w", err) @@ -309,7 +330,7 @@ func (c *collector) exportSummary(ch chan<- prometheus.Metric, dist aggregation. return nil } -func (c *collector) exportHistogram(ch chan<- prometheus.Metric, hist aggregation.Histogram, kind otel.NumberKind, desc *prometheus.Desc, labels []string) error { +func (c *collector) exportHistogram(ch chan<- prometheus.Metric, hist aggregation.Histogram, kind number.Kind, desc *prometheus.Desc, labels []string) error { buckets, err := hist.Histogram() if err != nil { return fmt.Errorf("error retrieving histogram: %w", err) diff --git a/exporters/metric/prometheus/prometheus_test.go b/exporters/metric/prometheus/prometheus_test.go index 6ec49eeeb76..547b9fd6484 100644 --- a/exporters/metric/prometheus/prometheus_test.go +++ b/exporters/metric/prometheus/prometheus_test.go @@ -26,14 +26,18 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/metric/prometheus" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/sdk/metric/controller/pull" "go.opentelemetry.io/otel/sdk/resource" ) func TestPrometheusExporter(t *testing.T) { + // #TODO: This test does not adequately verify the type of + // prometheus metric exported for all types - for example, + // it does not verify that an UpDown- counter is exported + // as a gauge. To be improved. exporter, err := prometheus.NewExportPipeline( prometheus.Config{ DefaultHistogramBoundaries: []float64{-0.5, 1}, @@ -44,9 +48,9 @@ func TestPrometheusExporter(t *testing.T) { require.NoError(t, err) meter := exporter.MeterProvider().Meter("test") - - counter := otel.Must(meter).NewFloat64Counter("counter") - valuerecorder := otel.Must(meter).NewFloat64ValueRecorder("valuerecorder") + upDownCounter := metric.Must(meter).NewFloat64UpDownCounter("updowncounter") + counter := metric.Must(meter).NewFloat64Counter("counter") + valuerecorder := metric.Must(meter).NewFloat64ValueRecorder("valuerecorder") labels := []label.KeyValue{ label.Key("A").String("B"), @@ -61,6 +65,12 @@ func TestPrometheusExporter(t *testing.T) { expected = append(expected, `counter{A="B",C="D",R="V"} 15.3`) + _ = metric.Must(meter).NewInt64ValueObserver("intobserver", func(_ context.Context, result metric.Int64ObserverResult) { + result.Observe(1, labels...) + }) + + expected = append(expected, `intobserver{A="B",C="D",R="V"} 1`) + valuerecorder.Record(ctx, -0.6, labels...) valuerecorder.Record(ctx, -0.4, labels...) valuerecorder.Record(ctx, 0.6, labels...) @@ -72,6 +82,11 @@ func TestPrometheusExporter(t *testing.T) { expected = append(expected, `valuerecorder_count{A="B",C="D",R="V"} 4`) expected = append(expected, `valuerecorder_sum{A="B",C="D",R="V"} 19.6`) + upDownCounter.Add(ctx, 10, labels...) + upDownCounter.Add(ctx, -3.2, labels...) + + expected = append(expected, `updowncounter{A="B",C="D",R="V"} 6.8`) + compareExport(t, exporter, expected) compareExport(t, exporter, expected) } @@ -123,9 +138,9 @@ func TestPrometheusStatefulness(t *testing.T) { ctx := context.Background() - counter := otel.Must(meter).NewInt64Counter( + counter := metric.Must(meter).NewInt64Counter( "a.counter", - otel.WithDescription("Counts things"), + metric.WithDescription("Counts things"), ) counter.Add(ctx, 100, label.String("key", "value")) diff --git a/exporters/otlp/README.md b/exporters/otlp/README.md index d896774656c..79dbd769b28 100644 --- a/exporters/otlp/README.md +++ b/exporters/otlp/README.md @@ -1,7 +1,6 @@ # OpenTelemetry Collector Go Exporter -[![GoDoc](https://godoc.org/go.opentelemetry.io/otel?status.svg)](https://pkg.go.dev/go.opentelemetry.io/otel/exporters/otlp) - +[![PkgGoDev](https://pkg.go.dev/badge/go.opentelemetry.io/otel/exporters/otlp)](https://pkg.go.dev/go.opentelemetry.io/otel/exporters/otlp) This exporter exports OpenTelemetry spans and metrics to the OpenTelemetry Collector. diff --git a/exporters/otlp/internal/transform/metric.go b/exporters/otlp/internal/transform/metric.go index 1bcffcf19c6..20b063c389e 100644 --- a/exporters/otlp/internal/transform/metric.go +++ b/exporters/otlp/internal/transform/metric.go @@ -24,12 +24,12 @@ import ( "sync" "time" - "go.opentelemetry.io/otel" commonpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/common/v1" metricpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/metrics/v1" resourcepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/resource/v1" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/instrumentation" @@ -86,7 +86,7 @@ func CheckpointSet(ctx context.Context, exportSelector export.ExportKindSelector for i := uint(0); i < numWorkers; i++ { go func() { defer wg.Done() - transformer(ctx, records, transformed) + transformer(ctx, exportSelector, records, transformed) }() } go func() { @@ -131,9 +131,9 @@ func source(ctx context.Context, exportSelector export.ExportKindSelector, cps e // transformer transforms records read from the passed in chan into // OTLP Metrics which are sent on the out chan. -func transformer(ctx context.Context, in <-chan export.Record, out chan<- result) { +func transformer(ctx context.Context, exportSelector export.ExportKindSelector, in <-chan export.Record, out chan<- result) { for r := range in { - m, err := Record(r) + m, err := Record(exportSelector, r) // Propagate errors, but do not send empty results. if err == nil && m == nil { continue @@ -250,7 +250,7 @@ func sink(ctx context.Context, in <-chan result) ([]*metricpb.ResourceMetrics, e // Record transforms a Record into an OTLP Metric. An ErrIncompatibleAgg // error is returned if the Record Aggregator is not supported. -func Record(r export.Record) (*metricpb.Metric, error) { +func Record(exportSelector export.ExportKindSelector, r export.Record) (*metricpb.Metric, error) { agg := r.Aggregation() switch agg.Kind() { case aggregation.MinMaxSumCountKind: @@ -265,7 +265,7 @@ func Record(r export.Record) (*metricpb.Metric, error) { if !ok { return nil, fmt.Errorf("%w: %T", ErrIncompatibleAgg, agg) } - return histogram(r, h) + return histogramPoint(r, exportSelector.ExportKindFor(r.Descriptor(), aggregation.HistogramKind), h) case aggregation.SumKind: s, ok := agg.(aggregation.Sum) @@ -276,7 +276,7 @@ func Record(r export.Record) (*metricpb.Metric, error) { if err != nil { return nil, err } - return scalar(r, sum, r.StartTime(), r.EndTime()) + return sumPoint(r, sum, r.StartTime(), r.EndTime(), exportSelector.ExportKindFor(r.Descriptor(), aggregation.SumKind), r.Descriptor().InstrumentKind().Monotonic()) case aggregation.LastValueKind: lv, ok := agg.(aggregation.LastValue) @@ -287,14 +287,14 @@ func Record(r export.Record) (*metricpb.Metric, error) { if err != nil { return nil, err } - return gauge(r, value, time.Time{}, tm) + return gaugePoint(r, value, time.Time{}, tm) default: return nil, fmt.Errorf("%w: %T", ErrUnimplementedAgg, agg) } } -func gauge(record export.Record, num otel.Number, start, end time.Time) (*metricpb.Metric, error) { +func gaugePoint(record export.Record, num number.Number, start, end time.Time) (*metricpb.Metric, error) { desc := record.Descriptor() labels := record.Labels() @@ -305,7 +305,7 @@ func gauge(record export.Record, num otel.Number, start, end time.Time) (*metric } switch n := desc.NumberKind(); n { - case otel.Int64NumberKind: + case number.Int64Kind: m.Data = &metricpb.Metric_IntGauge{ IntGauge: &metricpb.IntGauge{ DataPoints: []*metricpb.IntDataPoint{ @@ -318,7 +318,7 @@ func gauge(record export.Record, num otel.Number, start, end time.Time) (*metric }, }, } - case otel.Float64NumberKind: + case number.Float64Kind: m.Data = &metricpb.Metric_DoubleGauge{ DoubleGauge: &metricpb.DoubleGauge{ DataPoints: []*metricpb.DoubleDataPoint{ @@ -338,9 +338,17 @@ func gauge(record export.Record, num otel.Number, start, end time.Time) (*metric return m, nil } -// scalar transforms a Sum or LastValue Aggregator into an OTLP Metric. -// For LastValue (Gauge), use start==time.Time{}. -func scalar(record export.Record, num otel.Number, start, end time.Time) (*metricpb.Metric, error) { +func exportKindToTemporality(ek export.ExportKind) metricpb.AggregationTemporality { + switch ek { + case export.DeltaExportKind: + return metricpb.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA + case export.CumulativeExportKind: + return metricpb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE + } + return metricpb.AggregationTemporality_AGGREGATION_TEMPORALITY_UNSPECIFIED +} + +func sumPoint(record export.Record, num number.Number, start, end time.Time, ek export.ExportKind, monotonic bool) (*metricpb.Metric, error) { desc := record.Descriptor() labels := record.Labels() @@ -351,9 +359,11 @@ func scalar(record export.Record, num otel.Number, start, end time.Time) (*metri } switch n := desc.NumberKind(); n { - case otel.Int64NumberKind: + case number.Int64Kind: m.Data = &metricpb.Metric_IntSum{ IntSum: &metricpb.IntSum{ + IsMonotonic: monotonic, + AggregationTemporality: exportKindToTemporality(ek), DataPoints: []*metricpb.IntDataPoint{ { Value: num.CoerceToInt64(n), @@ -364,9 +374,11 @@ func scalar(record export.Record, num otel.Number, start, end time.Time) (*metri }, }, } - case otel.Float64NumberKind: + case number.Float64Kind: m.Data = &metricpb.Metric_DoubleSum{ DoubleSum: &metricpb.DoubleSum{ + IsMonotonic: monotonic, + AggregationTemporality: exportKindToTemporality(ek), DataPoints: []*metricpb.DoubleDataPoint{ { Value: num.CoerceToFloat64(n), @@ -386,7 +398,7 @@ func scalar(record export.Record, num otel.Number, start, end time.Time) (*metri // minMaxSumCountValue returns the values of the MinMaxSumCount Aggregator // as discrete values. -func minMaxSumCountValues(a aggregation.MinMaxSumCount) (min, max, sum otel.Number, count int64, err error) { +func minMaxSumCountValues(a aggregation.MinMaxSumCount) (min, max, sum number.Number, count int64, err error) { if min, err = a.Min(); err != nil { return } @@ -421,7 +433,7 @@ func minMaxSumCount(record export.Record, a aggregation.MinMaxSumCount) (*metric bounds := []float64{0.0, 100.0} switch n := desc.NumberKind(); n { - case otel.Int64NumberKind: + case number.Int64Kind: m.Data = &metricpb.Metric_IntHistogram{ IntHistogram: &metricpb.IntHistogram{ DataPoints: []*metricpb.IntHistogramDataPoint{ @@ -437,7 +449,7 @@ func minMaxSumCount(record export.Record, a aggregation.MinMaxSumCount) (*metric }, }, } - case otel.Float64NumberKind: + case number.Float64Kind: m.Data = &metricpb.Metric_DoubleHistogram{ DoubleHistogram: &metricpb.DoubleHistogram{ DataPoints: []*metricpb.DoubleHistogramDataPoint{ @@ -473,7 +485,7 @@ func histogramValues(a aggregation.Histogram) (boundaries []float64, counts []fl } // histogram transforms a Histogram Aggregator into an OTLP Metric. -func histogram(record export.Record, a aggregation.Histogram) (*metricpb.Metric, error) { +func histogramPoint(record export.Record, ek export.ExportKind, a aggregation.Histogram) (*metricpb.Metric, error) { desc := record.Descriptor() labels := record.Labels() boundaries, counts, err := histogramValues(a) @@ -501,9 +513,10 @@ func histogram(record export.Record, a aggregation.Histogram) (*metricpb.Metric, Unit: string(desc.Unit()), } switch n := desc.NumberKind(); n { - case otel.Int64NumberKind: + case number.Int64Kind: m.Data = &metricpb.Metric_IntHistogram{ IntHistogram: &metricpb.IntHistogram{ + AggregationTemporality: exportKindToTemporality(ek), DataPoints: []*metricpb.IntHistogramDataPoint{ { Sum: sum.CoerceToInt64(n), @@ -517,9 +530,10 @@ func histogram(record export.Record, a aggregation.Histogram) (*metricpb.Metric, }, }, } - case otel.Float64NumberKind: + case number.Float64Kind: m.Data = &metricpb.Metric_DoubleHistogram{ DoubleHistogram: &metricpb.DoubleHistogram{ + AggregationTemporality: exportKindToTemporality(ek), DataPoints: []*metricpb.DoubleHistogramDataPoint{ { Sum: sum.CoerceToFloat64(n), diff --git a/exporters/otlp/internal/transform/metric_test.go b/exporters/otlp/internal/transform/metric_test.go index 1d1bdb5b978..d732fb1e996 100644 --- a/exporters/otlp/internal/transform/metric_test.go +++ b/exporters/otlp/internal/transform/metric_test.go @@ -24,11 +24,11 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" commonpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/common/v1" metricpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/metrics/v1" - "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/export/metric/metrictest" @@ -48,6 +48,11 @@ var ( intervalEnd = intervalStart.Add(time.Hour) ) +const ( + otelCumulative = metricpb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE + otelDelta = metricpb.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA +) + func TestStringKeyValues(t *testing.T) { tests := []struct { kvs []label.KeyValue @@ -96,28 +101,28 @@ func TestStringKeyValues(t *testing.T) { } func TestMinMaxSumCountValue(t *testing.T) { - mmsc, ckpt := metrictest.Unslice2(minmaxsumcount.New(2, &otel.Descriptor{})) + mmsc, ckpt := metrictest.Unslice2(minmaxsumcount.New(2, &metric.Descriptor{})) - assert.NoError(t, mmsc.Update(context.Background(), 1, &otel.Descriptor{})) - assert.NoError(t, mmsc.Update(context.Background(), 10, &otel.Descriptor{})) + assert.NoError(t, mmsc.Update(context.Background(), 1, &metric.Descriptor{})) + assert.NoError(t, mmsc.Update(context.Background(), 10, &metric.Descriptor{})) // Prior to checkpointing ErrNoData should be returned. _, _, _, _, err := minMaxSumCountValues(ckpt.(aggregation.MinMaxSumCount)) assert.EqualError(t, err, aggregation.ErrNoData.Error()) // Checkpoint to set non-zero values - require.NoError(t, mmsc.SynchronizedMove(ckpt, &otel.Descriptor{})) + require.NoError(t, mmsc.SynchronizedMove(ckpt, &metric.Descriptor{})) min, max, sum, count, err := minMaxSumCountValues(ckpt.(aggregation.MinMaxSumCount)) if assert.NoError(t, err) { - assert.Equal(t, min, otel.NewInt64Number(1)) - assert.Equal(t, max, otel.NewInt64Number(10)) - assert.Equal(t, sum, otel.NewInt64Number(11)) + assert.Equal(t, min, number.NewInt64Number(1)) + assert.Equal(t, max, number.NewInt64Number(10)) + assert.Equal(t, sum, number.NewInt64Number(11)) assert.Equal(t, count, int64(2)) } } func TestMinMaxSumCountDatapoints(t *testing.T) { - desc := otel.NewDescriptor("", otel.ValueRecorderInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("", metric.ValueRecorderInstrumentKind, number.Int64Kind) labels := label.NewSet() mmsc, ckpt := metrictest.Unslice2(minmaxsumcount.New(2, &desc)) @@ -149,17 +154,17 @@ func TestMinMaxSumCountPropagatesErrors(t *testing.T) { // ErrNoData should be returned by both the Min and Max values of // a MinMaxSumCount Aggregator. Use this fact to check the error is // correctly returned. - mmsc := &minmaxsumcount.New(1, &otel.Descriptor{})[0] + mmsc := &minmaxsumcount.New(1, &metric.Descriptor{})[0] _, _, _, _, err := minMaxSumCountValues(mmsc) assert.Error(t, err) assert.Equal(t, aggregation.ErrNoData, err) } func TestSumIntDataPoints(t *testing.T) { - desc := otel.NewDescriptor("", otel.ValueRecorderInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("", metric.ValueRecorderInstrumentKind, number.Int64Kind) labels := label.NewSet() s, ckpt := metrictest.Unslice2(sumAgg.New(2)) - assert.NoError(t, s.Update(context.Background(), otel.Number(1), &desc)) + assert.NoError(t, s.Update(context.Background(), number.Number(1), &desc)) require.NoError(t, s.SynchronizedMove(ckpt, &desc)) record := export.NewRecord(&desc, &labels, nil, ckpt.Aggregation(), intervalStart, intervalEnd) sum, ok := ckpt.(aggregation.Sum) @@ -167,24 +172,27 @@ func TestSumIntDataPoints(t *testing.T) { value, err := sum.Sum() require.NoError(t, err) - if m, err := scalar(record, value, record.StartTime(), record.EndTime()); assert.NoError(t, err) { + if m, err := sumPoint(record, value, record.StartTime(), record.EndTime(), export.CumulativeExportKind, true); assert.NoError(t, err) { assert.Nil(t, m.GetIntGauge()) assert.Nil(t, m.GetIntHistogram()) - assert.Equal(t, []*metricpb.IntDataPoint{{ - Value: 1, - StartTimeUnixNano: uint64(intervalStart.UnixNano()), - TimeUnixNano: uint64(intervalEnd.UnixNano()), - }}, m.GetIntSum().DataPoints) + assert.Equal(t, &metricpb.IntSum{ + AggregationTemporality: otelCumulative, + IsMonotonic: true, + DataPoints: []*metricpb.IntDataPoint{{ + Value: 1, + StartTimeUnixNano: uint64(intervalStart.UnixNano()), + TimeUnixNano: uint64(intervalEnd.UnixNano()), + }}}, m.GetIntSum()) assert.Nil(t, m.GetDoubleGauge()) assert.Nil(t, m.GetDoubleHistogram()) } } func TestSumFloatDataPoints(t *testing.T) { - desc := otel.NewDescriptor("", otel.ValueRecorderInstrumentKind, otel.Float64NumberKind) + desc := metric.NewDescriptor("", metric.ValueRecorderInstrumentKind, number.Float64Kind) labels := label.NewSet() s, ckpt := metrictest.Unslice2(sumAgg.New(2)) - assert.NoError(t, s.Update(context.Background(), otel.NewFloat64Number(1), &desc)) + assert.NoError(t, s.Update(context.Background(), number.NewFloat64Number(1), &desc)) require.NoError(t, s.SynchronizedMove(ckpt, &desc)) record := export.NewRecord(&desc, &labels, nil, ckpt.Aggregation(), intervalStart, intervalEnd) sum, ok := ckpt.(aggregation.Sum) @@ -192,25 +200,28 @@ func TestSumFloatDataPoints(t *testing.T) { value, err := sum.Sum() require.NoError(t, err) - if m, err := scalar(record, value, record.StartTime(), record.EndTime()); assert.NoError(t, err) { + if m, err := sumPoint(record, value, record.StartTime(), record.EndTime(), export.DeltaExportKind, false); assert.NoError(t, err) { assert.Nil(t, m.GetIntGauge()) assert.Nil(t, m.GetIntHistogram()) assert.Nil(t, m.GetIntSum()) assert.Nil(t, m.GetDoubleGauge()) assert.Nil(t, m.GetDoubleHistogram()) - assert.Equal(t, []*metricpb.DoubleDataPoint{{ - Value: 1, - StartTimeUnixNano: uint64(intervalStart.UnixNano()), - TimeUnixNano: uint64(intervalEnd.UnixNano()), - }}, m.GetDoubleSum().DataPoints) + assert.Equal(t, &metricpb.DoubleSum{ + IsMonotonic: false, + AggregationTemporality: otelDelta, + DataPoints: []*metricpb.DoubleDataPoint{{ + Value: 1, + StartTimeUnixNano: uint64(intervalStart.UnixNano()), + TimeUnixNano: uint64(intervalEnd.UnixNano()), + }}}, m.GetDoubleSum()) } } func TestLastValueIntDataPoints(t *testing.T) { - desc := otel.NewDescriptor("", otel.ValueRecorderInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("", metric.ValueRecorderInstrumentKind, number.Int64Kind) labels := label.NewSet() s, ckpt := metrictest.Unslice2(lvAgg.New(2)) - assert.NoError(t, s.Update(context.Background(), otel.Number(100), &desc)) + assert.NoError(t, s.Update(context.Background(), number.Number(100), &desc)) require.NoError(t, s.SynchronizedMove(ckpt, &desc)) record := export.NewRecord(&desc, &labels, nil, ckpt.Aggregation(), intervalStart, intervalEnd) sum, ok := ckpt.(aggregation.LastValue) @@ -218,7 +229,7 @@ func TestLastValueIntDataPoints(t *testing.T) { value, timestamp, err := sum.LastValue() require.NoError(t, err) - if m, err := gauge(record, value, time.Time{}, timestamp); assert.NoError(t, err) { + if m, err := gaugePoint(record, value, time.Time{}, timestamp); assert.NoError(t, err) { assert.Equal(t, []*metricpb.IntDataPoint{{ Value: 100, StartTimeUnixNano: 0, @@ -233,14 +244,14 @@ func TestLastValueIntDataPoints(t *testing.T) { } func TestSumErrUnknownValueType(t *testing.T) { - desc := otel.NewDescriptor("", otel.ValueRecorderInstrumentKind, otel.NumberKind(-1)) + desc := metric.NewDescriptor("", metric.ValueRecorderInstrumentKind, number.Kind(-1)) labels := label.NewSet() s := &sumAgg.New(1)[0] record := export.NewRecord(&desc, &labels, nil, s, intervalStart, intervalEnd) value, err := s.Sum() require.NoError(t, err) - _, err = scalar(record, value, record.StartTime(), record.EndTime()) + _, err = sumPoint(record, value, record.StartTime(), record.EndTime(), export.CumulativeExportKind, true) assert.Error(t, err) if !errors.Is(err, ErrUnknownValueType) { t.Errorf("expected ErrUnknownValueType, got %v", err) @@ -262,13 +273,13 @@ func (t *testAgg) Aggregation() aggregation.Aggregation { // None of these three are used: -func (t *testAgg) Update(ctx context.Context, number otel.Number, descriptor *otel.Descriptor) error { +func (t *testAgg) Update(ctx context.Context, number number.Number, descriptor *metric.Descriptor) error { return nil } -func (t *testAgg) SynchronizedMove(destination export.Aggregator, descriptor *otel.Descriptor) error { +func (t *testAgg) SynchronizedMove(destination export.Aggregator, descriptor *metric.Descriptor) error { return nil } -func (t *testAgg) Merge(aggregator export.Aggregator, descriptor *otel.Descriptor) error { +func (t *testAgg) Merge(aggregator export.Aggregator, descriptor *metric.Descriptor) error { return nil } @@ -284,25 +295,25 @@ type testErrMinMaxSumCount struct { testErrSum } -func (te *testErrLastValue) LastValue() (otel.Number, time.Time, error) { +func (te *testErrLastValue) LastValue() (number.Number, time.Time, error) { return 0, time.Time{}, te.err } func (te *testErrLastValue) Kind() aggregation.Kind { return aggregation.LastValueKind } -func (te *testErrSum) Sum() (otel.Number, error) { +func (te *testErrSum) Sum() (number.Number, error) { return 0, te.err } func (te *testErrSum) Kind() aggregation.Kind { return aggregation.SumKind } -func (te *testErrMinMaxSumCount) Min() (otel.Number, error) { +func (te *testErrMinMaxSumCount) Min() (number.Number, error) { return 0, te.err } -func (te *testErrMinMaxSumCount) Max() (otel.Number, error) { +func (te *testErrMinMaxSumCount) Max() (number.Number, error) { return 0, te.err } @@ -318,14 +329,14 @@ var _ aggregation.MinMaxSumCount = &testErrMinMaxSumCount{} func TestRecordAggregatorIncompatibleErrors(t *testing.T) { makeMpb := func(kind aggregation.Kind, agg aggregation.Aggregation) (*metricpb.Metric, error) { - desc := otel.NewDescriptor("things", otel.CounterInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("things", metric.CounterInstrumentKind, number.Int64Kind) labels := label.NewSet() res := resource.Empty() test := &testAgg{ kind: kind, agg: agg, } - return Record(export.NewRecord(&desc, &labels, res, test, intervalStart, intervalEnd)) + return Record(export.CumulativeExportKindSelector(), export.NewRecord(&desc, &labels, res, test, intervalStart, intervalEnd)) } mpb, err := makeMpb(aggregation.SumKind, &lastvalue.New(1)[0]) @@ -355,10 +366,10 @@ func TestRecordAggregatorIncompatibleErrors(t *testing.T) { func TestRecordAggregatorUnexpectedErrors(t *testing.T) { makeMpb := func(kind aggregation.Kind, agg aggregation.Aggregation) (*metricpb.Metric, error) { - desc := otel.NewDescriptor("things", otel.CounterInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("things", metric.CounterInstrumentKind, number.Int64Kind) labels := label.NewSet() res := resource.Empty() - return Record(export.NewRecord(&desc, &labels, res, agg, intervalStart, intervalEnd)) + return Record(export.CumulativeExportKindSelector(), export.NewRecord(&desc, &labels, res, agg, intervalStart, intervalEnd)) } errEx := fmt.Errorf("timeout") diff --git a/exporters/otlp/internal/transform/span.go b/exporters/otlp/internal/transform/span.go index 8066f2d2def..78420739c45 100644 --- a/exporters/otlp/internal/transform/span.go +++ b/exporters/otlp/internal/transform/span.go @@ -15,13 +15,13 @@ package transform import ( - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" tracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/trace/v1" "go.opentelemetry.io/otel/label" export "go.opentelemetry.io/otel/sdk/export/trace" "go.opentelemetry.io/otel/sdk/instrumentation" + "go.opentelemetry.io/otel/trace" ) const ( @@ -140,7 +140,7 @@ func status(status codes.Code, message string) *tracepb.Status { } // links transforms span Links to OTLP span links. -func links(links []otel.Link) []*tracepb.Span_Link { +func links(links []trace.Link) []*tracepb.Span_Link { if len(links) == 0 { return nil } @@ -193,17 +193,17 @@ func spanEvents(es []export.Event) []*tracepb.Span_Event { } // spanKind transforms a SpanKind to an OTLP span kind. -func spanKind(kind otel.SpanKind) tracepb.Span_SpanKind { +func spanKind(kind trace.SpanKind) tracepb.Span_SpanKind { switch kind { - case otel.SpanKindInternal: + case trace.SpanKindInternal: return tracepb.Span_SPAN_KIND_INTERNAL - case otel.SpanKindClient: + case trace.SpanKindClient: return tracepb.Span_SPAN_KIND_CLIENT - case otel.SpanKindServer: + case trace.SpanKindServer: return tracepb.Span_SPAN_KIND_SERVER - case otel.SpanKindProducer: + case trace.SpanKindProducer: return tracepb.Span_SPAN_KIND_PRODUCER - case otel.SpanKindConsumer: + case trace.SpanKindConsumer: return tracepb.Span_SPAN_KIND_CONSUMER default: return tracepb.Span_SPAN_KIND_UNSPECIFIED diff --git a/exporters/otlp/internal/transform/span_test.go b/exporters/otlp/internal/transform/span_test.go index f8bd5e5e145..8a339d7427c 100644 --- a/exporters/otlp/internal/transform/span_test.go +++ b/exporters/otlp/internal/transform/span_test.go @@ -24,9 +24,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" tracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/trace/v1" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/codes" export "go.opentelemetry.io/otel/sdk/export/trace" @@ -36,31 +36,31 @@ import ( func TestSpanKind(t *testing.T) { for _, test := range []struct { - kind otel.SpanKind + kind trace.SpanKind expected tracepb.Span_SpanKind }{ { - otel.SpanKindInternal, + trace.SpanKindInternal, tracepb.Span_SPAN_KIND_INTERNAL, }, { - otel.SpanKindClient, + trace.SpanKindClient, tracepb.Span_SPAN_KIND_CLIENT, }, { - otel.SpanKindServer, + trace.SpanKindServer, tracepb.Span_SPAN_KIND_SERVER, }, { - otel.SpanKindProducer, + trace.SpanKindProducer, tracepb.Span_SPAN_KIND_PRODUCER, }, { - otel.SpanKindConsumer, + trace.SpanKindConsumer, tracepb.Span_SPAN_KIND_CONSUMER, }, { - otel.SpanKind(-1), + trace.SpanKind(-1), tracepb.Span_SPAN_KIND_UNSPECIFIED, }, } { @@ -117,15 +117,15 @@ func TestNilLinks(t *testing.T) { } func TestEmptyLinks(t *testing.T) { - assert.Nil(t, links([]otel.Link{})) + assert.Nil(t, links([]trace.Link{})) } func TestLinks(t *testing.T) { attrs := []label.KeyValue{label.Int("one", 1), label.Int("two", 2)} - l := []otel.Link{ + l := []trace.Link{ {}, { - SpanContext: otel.SpanContext{}, + SpanContext: trace.SpanContext{}, Attributes: attrs, }, } @@ -200,12 +200,12 @@ func TestSpanData(t *testing.T) { startTime := time.Unix(1585674086, 1234) endTime := startTime.Add(10 * time.Second) spanData := &export.SpanData{ - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }, - SpanKind: otel.SpanKindServer, - ParentSpanID: otel.SpanID{0xEF, 0xEE, 0xED, 0xEC, 0xEB, 0xEA, 0xE9, 0xE8}, + SpanKind: trace.SpanKindServer, + ParentSpanID: trace.SpanID{0xEF, 0xEE, 0xED, 0xEC, 0xEB, 0xEA, 0xE9, 0xE8}, Name: "span data to span data", StartTime: startTime, EndTime: endTime, @@ -221,11 +221,11 @@ func TestSpanData(t *testing.T) { }, }, }, - Links: []otel.Link{ + Links: []trace.Link{ { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, - SpanID: otel.SpanID{0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF}, + SpanID: trace.SpanID{0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7}, TraceFlags: 0, }, Attributes: []label.KeyValue{ @@ -233,9 +233,9 @@ func TestSpanData(t *testing.T) { }, }, { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF}, - SpanID: otel.SpanID{0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF}, + SpanID: trace.SpanID{0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7}, TraceFlags: 0, }, Attributes: []label.KeyValue{ diff --git a/exporters/otlp/options.go b/exporters/otlp/options.go index 9cd375005f4..737f56b8c08 100644 --- a/exporters/otlp/options.go +++ b/exporters/otlp/options.go @@ -19,6 +19,8 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/credentials" + + metricsdk "go.opentelemetry.io/otel/sdk/export/metric" ) const ( @@ -83,6 +85,7 @@ type config struct { headers map[string]string clientCredentials credentials.TransportCredentials numWorkers uint + exportKindSelector metricsdk.ExportKindSelector } // WorkerCount sets the number of Goroutines to use when processing telemetry. @@ -165,3 +168,11 @@ func WithGRPCDialOption(opts ...grpc.DialOption) ExporterOption { cfg.grpcDialOptions = opts } } + +// WithMetricExportKindSelector defines the ExportKindSelector used for selecting +// AggregationTemporality (i.e., Cumulative vs. Delta aggregation). +func WithMetricExportKindSelector(selector metricsdk.ExportKindSelector) ExporterOption { + return func(cfg *config) { + cfg.exportKindSelector = selector + } +} diff --git a/exporters/otlp/otlp.go b/exporters/otlp/otlp.go index 3cd43ca0a9f..8c60aeb8e5f 100644 --- a/exporters/otlp/otlp.go +++ b/exporters/otlp/otlp.go @@ -27,11 +27,10 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/metadata" - "go.opentelemetry.io/otel" colmetricpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/collector/metrics/v1" coltracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/collector/trace/v1" - "go.opentelemetry.io/otel/exporters/otlp/internal/transform" + "go.opentelemetry.io/otel/metric" metricsdk "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" tracesdk "go.opentelemetry.io/otel/sdk/export/trace" @@ -70,6 +69,11 @@ func newConfig(opts ...ExporterOption) config { cfg := config{ numWorkers: DefaultNumWorkers, grpcServiceConfig: DefaultGRPCServiceConfig, + + // Note: the default ExportKindSelector is specified + // as Cumulative: + // https://github.com/open-telemetry/opentelemetry-specification/issues/731 + exportKindSelector: metricsdk.CumulativeExportKindSelector(), } for _, opt := range opts { opt(&cfg) @@ -93,9 +97,6 @@ func NewUnstartedExporter(opts ...ExporterOption) *Exporter { if len(e.c.headers) > 0 { e.metadata = metadata.New(e.c.headers) } - - // TODO (rghetia): add resources - return e } @@ -286,9 +287,9 @@ func (e *Exporter) Export(parent context.Context, cps metricsdk.CheckpointSet) e } // ExportKindFor reports back to the OpenTelemetry SDK sending this Exporter -// metric telemetry that it needs to be provided in a pass-through format. -func (e *Exporter) ExportKindFor(*otel.Descriptor, aggregation.Kind) metricsdk.ExportKind { - return metricsdk.PassThroughExporter +// metric telemetry that it needs to be provided in a cumulative format. +func (e *Exporter) ExportKindFor(desc *metric.Descriptor, kind aggregation.Kind) metricsdk.ExportKind { + return e.c.exportKindSelector.ExportKindFor(desc, kind) } // ExportSpans exports a batch of SpanData. diff --git a/exporters/otlp/otlp_integration_test.go b/exporters/otlp/otlp_integration_test.go index 84a0f3e8d87..70f32c46571 100644 --- a/exporters/otlp/otlp_integration_test.go +++ b/exporters/otlp/otlp_integration_test.go @@ -25,11 +25,11 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/exporters/otlp" commonpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/common/v1" "go.opentelemetry.io/otel/label" - - "go.opentelemetry.io/otel/exporters/otlp" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" metricsdk "go.opentelemetry.io/otel/sdk/export/metric" exporttrace "go.opentelemetry.io/otel/sdk/export/trace" "go.opentelemetry.io/otel/sdk/metric/controller/push" @@ -120,7 +120,7 @@ func newExporterEndToEndTest(t *testing.T, additionalOpts []otlp.ExporterOption) } selector := simple.NewWithInexpensiveDistribution() - processor := processor.New(selector, metricsdk.PassThroughExporter) + processor := processor.New(selector, metricsdk.StatelessExportKindSelector()) pusher := push.New(processor, exp) pusher.Start() @@ -129,52 +129,52 @@ func newExporterEndToEndTest(t *testing.T, additionalOpts []otlp.ExporterOption) labels := []label.KeyValue{label.Bool("test", true)} type data struct { - iKind otel.InstrumentKind - nKind otel.NumberKind + iKind metric.InstrumentKind + nKind number.Kind val int64 } instruments := map[string]data{ - "test-int64-counter": {otel.CounterInstrumentKind, otel.Int64NumberKind, 1}, - "test-float64-counter": {otel.CounterInstrumentKind, otel.Float64NumberKind, 1}, - "test-int64-valuerecorder": {otel.ValueRecorderInstrumentKind, otel.Int64NumberKind, 2}, - "test-float64-valuerecorder": {otel.ValueRecorderInstrumentKind, otel.Float64NumberKind, 2}, - "test-int64-valueobserver": {otel.ValueObserverInstrumentKind, otel.Int64NumberKind, 3}, - "test-float64-valueobserver": {otel.ValueObserverInstrumentKind, otel.Float64NumberKind, 3}, + "test-int64-counter": {metric.CounterInstrumentKind, number.Int64Kind, 1}, + "test-float64-counter": {metric.CounterInstrumentKind, number.Float64Kind, 1}, + "test-int64-valuerecorder": {metric.ValueRecorderInstrumentKind, number.Int64Kind, 2}, + "test-float64-valuerecorder": {metric.ValueRecorderInstrumentKind, number.Float64Kind, 2}, + "test-int64-valueobserver": {metric.ValueObserverInstrumentKind, number.Int64Kind, 3}, + "test-float64-valueobserver": {metric.ValueObserverInstrumentKind, number.Float64Kind, 3}, } for name, data := range instruments { data := data switch data.iKind { - case otel.CounterInstrumentKind: + case metric.CounterInstrumentKind: switch data.nKind { - case otel.Int64NumberKind: - otel.Must(meter).NewInt64Counter(name).Add(ctx, data.val, labels...) - case otel.Float64NumberKind: - otel.Must(meter).NewFloat64Counter(name).Add(ctx, float64(data.val), labels...) + case number.Int64Kind: + metric.Must(meter).NewInt64Counter(name).Add(ctx, data.val, labels...) + case number.Float64Kind: + metric.Must(meter).NewFloat64Counter(name).Add(ctx, float64(data.val), labels...) default: assert.Failf(t, "unsupported number testing kind", data.nKind.String()) } - case otel.ValueRecorderInstrumentKind: + case metric.ValueRecorderInstrumentKind: switch data.nKind { - case otel.Int64NumberKind: - otel.Must(meter).NewInt64ValueRecorder(name).Record(ctx, data.val, labels...) - case otel.Float64NumberKind: - otel.Must(meter).NewFloat64ValueRecorder(name).Record(ctx, float64(data.val), labels...) + case number.Int64Kind: + metric.Must(meter).NewInt64ValueRecorder(name).Record(ctx, data.val, labels...) + case number.Float64Kind: + metric.Must(meter).NewFloat64ValueRecorder(name).Record(ctx, float64(data.val), labels...) default: assert.Failf(t, "unsupported number testing kind", data.nKind.String()) } - case otel.ValueObserverInstrumentKind: + case metric.ValueObserverInstrumentKind: switch data.nKind { - case otel.Int64NumberKind: - otel.Must(meter).NewInt64ValueObserver(name, - func(_ context.Context, result otel.Int64ObserverResult) { + case number.Int64Kind: + metric.Must(meter).NewInt64ValueObserver(name, + func(_ context.Context, result metric.Int64ObserverResult) { result.Observe(data.val, labels...) }, ) - case otel.Float64NumberKind: - callback := func(v float64) otel.Float64ObserverFunc { - return otel.Float64ObserverFunc(func(_ context.Context, result otel.Float64ObserverResult) { result.Observe(v, labels...) }) + case number.Float64Kind: + callback := func(v float64) metric.Float64ObserverFunc { + return metric.Float64ObserverFunc(func(_ context.Context, result metric.Float64ObserverResult) { result.Observe(v, labels...) }) }(float64(data.val)) - otel.Must(meter).NewFloat64ValueObserver(name, callback) + metric.Must(meter).NewFloat64ValueObserver(name, callback) default: assert.Failf(t, "unsupported number testing kind", data.nKind.String()) } @@ -244,42 +244,42 @@ func newExporterEndToEndTest(t *testing.T, additionalOpts []otlp.ExporterOption) seen[m.Name] = struct{}{} switch data.iKind { - case otel.CounterInstrumentKind: + case metric.CounterInstrumentKind: switch data.nKind { - case otel.Int64NumberKind: + case number.Int64Kind: if dp := m.GetIntSum().DataPoints; assert.Len(t, dp, 1) { assert.Equal(t, data.val, dp[0].Value, "invalid value for %q", m.Name) } - case otel.Float64NumberKind: + case number.Float64Kind: if dp := m.GetDoubleSum().DataPoints; assert.Len(t, dp, 1) { assert.Equal(t, float64(data.val), dp[0].Value, "invalid value for %q", m.Name) } default: assert.Failf(t, "invalid number kind", data.nKind.String()) } - case otel.ValueObserverInstrumentKind: + case metric.ValueObserverInstrumentKind: switch data.nKind { - case otel.Int64NumberKind: + case number.Int64Kind: if dp := m.GetIntGauge().DataPoints; assert.Len(t, dp, 1) { assert.Equal(t, data.val, dp[0].Value, "invalid value for %q", m.Name) } - case otel.Float64NumberKind: + case number.Float64Kind: if dp := m.GetDoubleGauge().DataPoints; assert.Len(t, dp, 1) { assert.Equal(t, float64(data.val), dp[0].Value, "invalid value for %q", m.Name) } default: assert.Failf(t, "invalid number kind", data.nKind.String()) } - case otel.ValueRecorderInstrumentKind: + case metric.ValueRecorderInstrumentKind: switch data.nKind { - case otel.Int64NumberKind: + case number.Int64Kind: assert.NotNil(t, m.GetIntHistogram()) if dp := m.GetIntHistogram().DataPoints; assert.Len(t, dp, 1) { count := dp[0].Count assert.Equal(t, uint64(1), count, "invalid count for %q", m.Name) assert.Equal(t, int64(data.val*int64(count)), dp[0].Sum, "invalid sum for %q (value %d)", m.Name, data.val) } - case otel.Float64NumberKind: + case number.Float64Kind: assert.NotNil(t, m.GetDoubleHistogram()) if dp := m.GetDoubleHistogram().DataPoints; assert.Len(t, dp, 1) { count := dp[0].Count @@ -509,7 +509,7 @@ func TestNewExporter_withMultipleAttributeTypes(t *testing.T) { span.End() selector := simple.NewWithInexpensiveDistribution() - processor := processor.New(selector, metricsdk.PassThroughExporter) + processor := processor.New(selector, metricsdk.StatelessExportKindSelector()) pusher := push.New(processor, exp) pusher.Start() diff --git a/exporters/otlp/otlp_metric_test.go b/exporters/otlp/otlp_metric_test.go index c82b605edf0..c4ebca4c905 100644 --- a/exporters/otlp/otlp_metric_test.go +++ b/exporters/otlp/otlp_metric_test.go @@ -23,13 +23,13 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" colmetricpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/collector/metrics/v1" commonpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/common/v1" metricpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/metrics/v1" resourcepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/resource/v1" - "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" metricsdk "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/export/metric/metrictest" @@ -93,10 +93,10 @@ func (m *checkpointSet) ForEach(_ metricsdk.ExportKindSelector, fn func(metricsd type record struct { name string - iKind otel.InstrumentKind - nKind otel.NumberKind + iKind metric.InstrumentKind + nKind number.Kind resource *resource.Resource - opts []otel.InstrumentOption + opts []metric.InstrumentOption labels []label.KeyValue } @@ -159,19 +159,20 @@ var ( func TestNoGroupingExport(t *testing.T) { runMetricExportTests( t, + nil, []record{ { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, nil, nil, append(baseKeyValues, cpuKey.Int(1)), }, { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, nil, nil, append(baseKeyValues, cpuKey.Int(2)), @@ -217,8 +218,8 @@ func TestNoGroupingExport(t *testing.T) { func TestValuerecorderMetricGroupingExport(t *testing.T) { r := record{ "valuerecorder", - otel.ValueRecorderInstrumentKind, - otel.Int64NumberKind, + metric.ValueRecorderInstrumentKind, + number.Int64Kind, nil, nil, append(baseKeyValues, cpuKey.Int(1)), @@ -280,20 +281,21 @@ func TestValuerecorderMetricGroupingExport(t *testing.T) { }, }, } - runMetricExportTests(t, []record{r, r}, expected) + runMetricExportTests(t, nil, []record{r, r}, expected) } func TestCountInt64MetricGroupingExport(t *testing.T) { r := record{ "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, nil, nil, append(baseKeyValues, cpuKey.Int(1)), } runMetricExportTests( t, + nil, []record{r, r}, []metricpb.ResourceMetrics{ { @@ -335,14 +337,15 @@ func TestCountInt64MetricGroupingExport(t *testing.T) { func TestCountFloat64MetricGroupingExport(t *testing.T) { r := record{ "float64-count", - otel.CounterInstrumentKind, - otel.Float64NumberKind, + metric.CounterInstrumentKind, + number.Float64Kind, nil, nil, append(baseKeyValues, cpuKey.Int(1)), } runMetricExportTests( t, + nil, []record{r, r}, []metricpb.ResourceMetrics{ { @@ -402,35 +405,36 @@ func TestCountFloat64MetricGroupingExport(t *testing.T) { func TestResourceMetricGroupingExport(t *testing.T) { runMetricExportTests( t, + nil, []record{ { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, testInstA, nil, append(baseKeyValues, cpuKey.Int(1)), }, { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, testInstA, nil, append(baseKeyValues, cpuKey.Int(1)), }, { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, testInstA, nil, append(baseKeyValues, cpuKey.Int(2)), }, { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, testInstB, nil, append(baseKeyValues, cpuKey.Int(1)), @@ -506,64 +510,65 @@ func TestResourceMetricGroupingExport(t *testing.T) { } func TestResourceInstLibMetricGroupingExport(t *testing.T) { - countingLib1 := []otel.InstrumentOption{ - otel.WithInstrumentationName("counting-lib"), - otel.WithInstrumentationVersion("v1"), + countingLib1 := []metric.InstrumentOption{ + metric.WithInstrumentationName("counting-lib"), + metric.WithInstrumentationVersion("v1"), } - countingLib2 := []otel.InstrumentOption{ - otel.WithInstrumentationName("counting-lib"), - otel.WithInstrumentationVersion("v2"), + countingLib2 := []metric.InstrumentOption{ + metric.WithInstrumentationName("counting-lib"), + metric.WithInstrumentationVersion("v2"), } - summingLib := []otel.InstrumentOption{ - otel.WithInstrumentationName("summing-lib"), + summingLib := []metric.InstrumentOption{ + metric.WithInstrumentationName("summing-lib"), } runMetricExportTests( t, + nil, []record{ { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, testInstA, countingLib1, append(baseKeyValues, cpuKey.Int(1)), }, { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, testInstA, countingLib2, append(baseKeyValues, cpuKey.Int(1)), }, { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, testInstA, countingLib1, append(baseKeyValues, cpuKey.Int(1)), }, { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, testInstA, countingLib1, append(baseKeyValues, cpuKey.Int(2)), }, { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, testInstA, summingLib, append(baseKeyValues, cpuKey.Int(1)), }, { "int64-count", - otel.CounterInstrumentKind, - otel.Int64NumberKind, + metric.CounterInstrumentKind, + number.Int64Kind, testInstB, countingLib1, append(baseKeyValues, cpuKey.Int(1)), @@ -695,13 +700,78 @@ func TestResourceInstLibMetricGroupingExport(t *testing.T) { ) } +func TestStatelessExportKind(t *testing.T) { + type testcase struct { + name string + instrumentKind metric.InstrumentKind + aggTemporality metricpb.AggregationTemporality + monotonic bool + } + + for _, k := range []testcase{ + {"counter", metric.CounterInstrumentKind, metricpb.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA, true}, + {"updowncounter", metric.UpDownCounterInstrumentKind, metricpb.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA, false}, + {"sumobserver", metric.SumObserverInstrumentKind, metricpb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE, true}, + {"updownsumobserver", metric.UpDownSumObserverInstrumentKind, metricpb.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE, false}, + } { + t.Run(k.name, func(t *testing.T) { + runMetricExportTests( + t, + []ExporterOption{ + WithMetricExportKindSelector( + metricsdk.StatelessExportKindSelector(), + ), + }, + []record{ + { + "instrument", + k.instrumentKind, + number.Int64Kind, + testInstA, + nil, + append(baseKeyValues, cpuKey.Int(1)), + }, + }, + []metricpb.ResourceMetrics{ + { + Resource: testerAResource, + InstrumentationLibraryMetrics: []*metricpb.InstrumentationLibraryMetrics{ + { + Metrics: []*metricpb.Metric{ + { + Name: "instrument", + Data: &metricpb.Metric_IntSum{ + IntSum: &metricpb.IntSum{ + IsMonotonic: k.monotonic, + AggregationTemporality: k.aggTemporality, + DataPoints: []*metricpb.IntDataPoint{ + { + Value: 11, + Labels: cpu1Labels, + StartTimeUnixNano: startTime(), + TimeUnixNano: pointTime(), + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + ) + }) + } +} + // What works single-threaded should work multi-threaded -func runMetricExportTests(t *testing.T, rs []record, expected []metricpb.ResourceMetrics) { +func runMetricExportTests(t *testing.T, opts []ExporterOption, rs []record, expected []metricpb.ResourceMetrics) { t.Run("1 goroutine", func(t *testing.T) { - runMetricExportTest(t, NewUnstartedExporter(WorkerCount(1)), rs, expected) + runMetricExportTest(t, NewUnstartedExporter(append(opts[:len(opts):len(opts)], WorkerCount(1))...), rs, expected) }) t.Run("20 goroutines", func(t *testing.T) { - runMetricExportTest(t, NewUnstartedExporter(WorkerCount(20)), rs, expected) + runMetricExportTest(t, NewUnstartedExporter(append(opts[:len(opts):len(opts)], WorkerCount(20))...), rs, expected) }) } @@ -713,27 +783,41 @@ func runMetricExportTest(t *testing.T, exp *Exporter, rs []record, expected []me recs := map[label.Distinct][]metricsdk.Record{} resources := map[label.Distinct]*resource.Resource{} for _, r := range rs { - desc := otel.NewDescriptor(r.name, r.iKind, r.nKind, r.opts...) - labs := label.NewSet(r.labels...) + lcopy := make([]label.KeyValue, len(r.labels)) + copy(lcopy, r.labels) + desc := metric.NewDescriptor(r.name, r.iKind, r.nKind, r.opts...) + labs := label.NewSet(lcopy...) var agg, ckpt metricsdk.Aggregator - switch r.iKind { - case otel.CounterInstrumentKind: + if r.iKind.Adding() { agg, ckpt = metrictest.Unslice2(sum.New(2)) - default: + } else { agg, ckpt = metrictest.Unslice2(histogram.New(2, &desc, testHistogramBoundaries)) } ctx := context.Background() - switch r.nKind { - case otel.Int64NumberKind: - require.NoError(t, agg.Update(ctx, otel.NewInt64Number(1), &desc)) - require.NoError(t, agg.Update(ctx, otel.NewInt64Number(10), &desc)) - case otel.Float64NumberKind: - require.NoError(t, agg.Update(ctx, otel.NewFloat64Number(1), &desc)) - require.NoError(t, agg.Update(ctx, otel.NewFloat64Number(10), &desc)) - default: - t.Fatalf("invalid number kind: %v", r.nKind) + if r.iKind.Synchronous() { + // For synchronous instruments, perform two updates: 1 and 10 + switch r.nKind { + case number.Int64Kind: + require.NoError(t, agg.Update(ctx, number.NewInt64Number(1), &desc)) + require.NoError(t, agg.Update(ctx, number.NewInt64Number(10), &desc)) + case number.Float64Kind: + require.NoError(t, agg.Update(ctx, number.NewFloat64Number(1), &desc)) + require.NoError(t, agg.Update(ctx, number.NewFloat64Number(10), &desc)) + default: + t.Fatalf("invalid number kind: %v", r.nKind) + } + } else { + // For asynchronous instruments, perform a single update: 11 + switch r.nKind { + case number.Int64Kind: + require.NoError(t, agg.Update(ctx, number.NewInt64Number(11), &desc)) + case number.Float64Kind: + require.NoError(t, agg.Update(ctx, number.NewFloat64Number(11), &desc)) + default: + t.Fatalf("invalid number kind: %v", r.nKind) + } } require.NoError(t, agg.SynchronizedMove(ckpt, &desc)) @@ -787,14 +871,38 @@ func runMetricExportTest(t *testing.T, exp *Exporter, rs []record, expected []me case *metricpb.Metric_IntGauge: assert.ElementsMatch(t, expected.GetIntGauge().DataPoints, g[i].GetIntGauge().DataPoints) case *metricpb.Metric_IntHistogram: + assert.Equal(t, + expected.GetIntHistogram().GetAggregationTemporality(), + g[i].GetIntHistogram().GetAggregationTemporality(), + ) assert.ElementsMatch(t, expected.GetIntHistogram().DataPoints, g[i].GetIntHistogram().DataPoints) case *metricpb.Metric_IntSum: + assert.Equal(t, + expected.GetIntSum().GetAggregationTemporality(), + g[i].GetIntSum().GetAggregationTemporality(), + ) + assert.Equal(t, + expected.GetIntSum().GetIsMonotonic(), + g[i].GetIntSum().GetIsMonotonic(), + ) assert.ElementsMatch(t, expected.GetIntSum().DataPoints, g[i].GetIntSum().DataPoints) case *metricpb.Metric_DoubleGauge: assert.ElementsMatch(t, expected.GetDoubleGauge().DataPoints, g[i].GetDoubleGauge().DataPoints) case *metricpb.Metric_DoubleHistogram: + assert.Equal(t, + expected.GetDoubleHistogram().GetAggregationTemporality(), + g[i].GetDoubleHistogram().GetAggregationTemporality(), + ) assert.ElementsMatch(t, expected.GetDoubleHistogram().DataPoints, g[i].GetDoubleHistogram().DataPoints) case *metricpb.Metric_DoubleSum: + assert.Equal(t, + expected.GetDoubleSum().GetAggregationTemporality(), + g[i].GetDoubleSum().GetAggregationTemporality(), + ) + assert.Equal(t, + expected.GetDoubleSum().GetIsMonotonic(), + g[i].GetDoubleSum().GetIsMonotonic(), + ) assert.ElementsMatch(t, expected.GetDoubleSum().DataPoints, g[i].GetDoubleSum().DataPoints) default: assert.Failf(t, "unknown data type", g[i].Name) diff --git a/exporters/otlp/otlp_span_test.go b/exporters/otlp/otlp_span_test.go index 27b75055454..2e0e71b3462 100644 --- a/exporters/otlp/otlp_span_test.go +++ b/exporters/otlp/otlp_span_test.go @@ -22,13 +22,13 @@ import ( "github.com/stretchr/testify/assert" "google.golang.org/grpc" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" coltracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/collector/trace/v1" commonpb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/common/v1" resourcepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/resource/v1" tracepb "go.opentelemetry.io/otel/exporters/otlp/internal/opentelemetry-proto-gen/trace/v1" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" tracesdk "go.opentelemetry.io/otel/sdk/export/trace" "go.opentelemetry.io/otel/sdk/instrumentation" @@ -82,12 +82,12 @@ func TestExportSpans(t *testing.T) { { []*tracesdk.SpanData{ { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}), - SpanID: otel.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}), + SpanID: trace.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), TraceFlags: byte(1), }, - SpanKind: otel.SpanKindServer, + SpanKind: trace.SpanKindServer, Name: "parent process", StartTime: startTime, EndTime: endTime, @@ -104,12 +104,12 @@ func TestExportSpans(t *testing.T) { }, }, { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}), - SpanID: otel.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}), + SpanID: trace.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), TraceFlags: byte(1), }, - SpanKind: otel.SpanKindServer, + SpanKind: trace.SpanKindServer, Name: "secondary parent process", StartTime: startTime, EndTime: endTime, @@ -126,13 +126,13 @@ func TestExportSpans(t *testing.T) { }, }, { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}), - SpanID: otel.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 2}), + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}), + SpanID: trace.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 2}), TraceFlags: byte(1), }, - ParentSpanID: otel.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), - SpanKind: otel.SpanKindInternal, + ParentSpanID: trace.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), + SpanKind: trace.SpanKindInternal, Name: "internal process", StartTime: startTime, EndTime: endTime, @@ -149,12 +149,12 @@ func TestExportSpans(t *testing.T) { }, }, { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}), - SpanID: otel.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID([16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}), + SpanID: trace.SpanID([8]byte{0, 0, 0, 0, 0, 0, 0, 1}), TraceFlags: byte(1), }, - SpanKind: otel.SpanKindServer, + SpanKind: trace.SpanKindServer, Name: "parent process", StartTime: startTime, EndTime: endTime, diff --git a/exporters/stdout/example_test.go b/exporters/stdout/example_test.go index 21b30d2348e..21a061ba2c0 100644 --- a/exporters/stdout/example_test.go +++ b/exporters/stdout/example_test.go @@ -18,10 +18,11 @@ import ( "context" "log" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/stdout" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/trace" ) const ( @@ -32,16 +33,16 @@ const ( var ( tracer = global.TracerProvider().Tracer( instrumentationName, - otel.WithInstrumentationVersion(instrumentationVersion), + trace.WithInstrumentationVersion(instrumentationVersion), ) meter = global.MeterProvider().Meter( instrumentationName, - otel.WithInstrumentationVersion(instrumentationVersion), + metric.WithInstrumentationVersion(instrumentationVersion), ) - loopCounter = otel.Must(meter).NewInt64Counter("function.loops") - paramValue = otel.Must(meter).NewInt64ValueRecorder("function.param") + loopCounter = metric.Must(meter).NewInt64Counter("function.loops") + paramValue = metric.Must(meter).NewInt64ValueRecorder("function.param") nameKey = label.Key("function.name") ) @@ -49,7 +50,7 @@ var ( func add(ctx context.Context, x, y int64) int64 { nameKV := nameKey.String("add") - var span otel.Span + var span trace.Span ctx, span = tracer.Start(ctx, "Addition") defer span.End() @@ -63,7 +64,7 @@ func add(ctx context.Context, x, y int64) int64 { func multiply(ctx context.Context, x, y int64) int64 { nameKV := nameKey.String("multiply") - var span otel.Span + var span trace.Span ctx, span = tracer.Start(ctx, "Multiplication") defer span.End() diff --git a/exporters/stdout/exporter.go b/exporters/stdout/exporter.go index 56f1aaa15d9..493a71a525a 100644 --- a/exporters/stdout/exporter.go +++ b/exporters/stdout/exporter.go @@ -15,7 +15,6 @@ package stdout // import "go.opentelemetry.io/otel/exporters/stdout" import ( - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/sdk/export/metric" exporttrace "go.opentelemetry.io/otel/sdk/export/trace" @@ -23,6 +22,7 @@ import ( "go.opentelemetry.io/otel/sdk/metric/processor/basic" "go.opentelemetry.io/otel/sdk/metric/selector/simple" sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" ) type Exporter struct { @@ -50,7 +50,7 @@ func NewExporter(options ...Option) (*Exporter, error) { // NewExportPipeline creates a complete export pipeline with the default // selectors, processors, and trace registration. It is the responsibility // of the caller to stop the returned push Controller. -func NewExportPipeline(exportOpts []Option, pushOpts []push.Option) (otel.TracerProvider, *push.Controller, error) { +func NewExportPipeline(exportOpts []Option, pushOpts []push.Option) (trace.TracerProvider, *push.Controller, error) { exporter, err := NewExporter(exportOpts...) if err != nil { return nil, nil, err diff --git a/exporters/stdout/metric.go b/exporters/stdout/metric.go index 91f6876a209..725d3abf795 100644 --- a/exporters/stdout/metric.go +++ b/exporters/stdout/metric.go @@ -21,8 +21,8 @@ import ( "strings" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" exportmetric "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" ) @@ -52,8 +52,8 @@ type quantile struct { Value interface{} `json:"Value"` } -func (e *metricExporter) ExportKindFor(*otel.Descriptor, aggregation.Kind) exportmetric.ExportKind { - return exportmetric.PassThroughExporter +func (e *metricExporter) ExportKindFor(desc *metric.Descriptor, kind aggregation.Kind) exportmetric.ExportKind { + return exportmetric.StatelessExportKindSelector().ExportKindFor(desc, kind) } func (e *metricExporter) Export(_ context.Context, checkpointSet exportmetric.CheckpointSet) error { diff --git a/exporters/stdout/metric_test.go b/exporters/stdout/metric_test.go index 33c2c02e58a..07378fbb4d9 100644 --- a/exporters/stdout/metric_test.go +++ b/exporters/stdout/metric_test.go @@ -26,9 +26,10 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/stdout" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/export/metric/metrictest" @@ -99,11 +100,11 @@ func TestStdoutTimestamp(t *testing.T) { checkpointSet := metrictest.NewCheckpointSet(testResource) ctx := context.Background() - desc := otel.NewDescriptor("test.name", otel.ValueObserverInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("test.name", metric.ValueObserverInstrumentKind, number.Int64Kind) lvagg, ckpt := metrictest.Unslice2(lastvalue.New(2)) - aggregatortest.CheckedUpdate(t, lvagg, otel.NewInt64Number(321), &desc) + aggregatortest.CheckedUpdate(t, lvagg, number.NewInt64Number(321), &desc) require.NoError(t, lvagg.SynchronizedMove(ckpt, &desc)) checkpointSet.Add(&desc, ckpt) @@ -138,11 +139,11 @@ func TestStdoutCounterFormat(t *testing.T) { checkpointSet := metrictest.NewCheckpointSet(testResource) - desc := otel.NewDescriptor("test.name", otel.CounterInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("test.name", metric.CounterInstrumentKind, number.Int64Kind) cagg, ckpt := metrictest.Unslice2(sum.New(2)) - aggregatortest.CheckedUpdate(fix.t, cagg, otel.NewInt64Number(123), &desc) + aggregatortest.CheckedUpdate(fix.t, cagg, number.NewInt64Number(123), &desc) require.NoError(t, cagg.SynchronizedMove(ckpt, &desc)) checkpointSet.Add(&desc, ckpt, label.String("A", "B"), label.String("C", "D")) @@ -157,10 +158,10 @@ func TestStdoutLastValueFormat(t *testing.T) { checkpointSet := metrictest.NewCheckpointSet(testResource) - desc := otel.NewDescriptor("test.name", otel.ValueObserverInstrumentKind, otel.Float64NumberKind) + desc := metric.NewDescriptor("test.name", metric.ValueObserverInstrumentKind, number.Float64Kind) lvagg, ckpt := metrictest.Unslice2(lastvalue.New(2)) - aggregatortest.CheckedUpdate(fix.t, lvagg, otel.NewFloat64Number(123.456), &desc) + aggregatortest.CheckedUpdate(fix.t, lvagg, number.NewFloat64Number(123.456), &desc) require.NoError(t, lvagg.SynchronizedMove(ckpt, &desc)) checkpointSet.Add(&desc, ckpt, label.String("A", "B"), label.String("C", "D")) @@ -175,12 +176,12 @@ func TestStdoutMinMaxSumCount(t *testing.T) { checkpointSet := metrictest.NewCheckpointSet(testResource) - desc := otel.NewDescriptor("test.name", otel.ValueRecorderInstrumentKind, otel.Float64NumberKind) + desc := metric.NewDescriptor("test.name", metric.ValueRecorderInstrumentKind, number.Float64Kind) magg, ckpt := metrictest.Unslice2(minmaxsumcount.New(2, &desc)) - aggregatortest.CheckedUpdate(fix.t, magg, otel.NewFloat64Number(123.456), &desc) - aggregatortest.CheckedUpdate(fix.t, magg, otel.NewFloat64Number(876.543), &desc) + aggregatortest.CheckedUpdate(fix.t, magg, number.NewFloat64Number(123.456), &desc) + aggregatortest.CheckedUpdate(fix.t, magg, number.NewFloat64Number(876.543), &desc) require.NoError(t, magg.SynchronizedMove(ckpt, &desc)) checkpointSet.Add(&desc, ckpt, label.String("A", "B"), label.String("C", "D")) @@ -195,11 +196,11 @@ func TestStdoutValueRecorderFormat(t *testing.T) { checkpointSet := metrictest.NewCheckpointSet(testResource) - desc := otel.NewDescriptor("test.name", otel.ValueRecorderInstrumentKind, otel.Float64NumberKind) + desc := metric.NewDescriptor("test.name", metric.ValueRecorderInstrumentKind, number.Float64Kind) aagg, ckpt := metrictest.Unslice2(array.New(2)) for i := 0; i < 1000; i++ { - aggregatortest.CheckedUpdate(fix.t, aagg, otel.NewFloat64Number(float64(i)+0.5), &desc) + aggregatortest.CheckedUpdate(fix.t, aagg, number.NewFloat64Number(float64(i)+0.5), &desc) } require.NoError(t, aagg.SynchronizedMove(ckpt, &desc)) @@ -234,7 +235,7 @@ func TestStdoutValueRecorderFormat(t *testing.T) { } func TestStdoutNoData(t *testing.T) { - desc := otel.NewDescriptor("test.name", otel.ValueRecorderInstrumentKind, otel.Float64NumberKind) + desc := metric.NewDescriptor("test.name", metric.ValueRecorderInstrumentKind, number.Float64Kind) runTwoAggs := func(agg, ckpt export.Aggregator) { t.Run(fmt.Sprintf("%T", agg), func(t *testing.T) { @@ -263,7 +264,7 @@ func TestStdoutLastValueNotSet(t *testing.T) { checkpointSet := metrictest.NewCheckpointSet(testResource) - desc := otel.NewDescriptor("test.name", otel.ValueObserverInstrumentKind, otel.Float64NumberKind) + desc := metric.NewDescriptor("test.name", metric.ValueObserverInstrumentKind, number.Float64Kind) lvagg, ckpt := metrictest.Unslice2(lastvalue.New(2)) require.NoError(t, lvagg.SynchronizedMove(ckpt, &desc)) @@ -314,10 +315,10 @@ func TestStdoutResource(t *testing.T) { checkpointSet := metrictest.NewCheckpointSet(tc.res) - desc := otel.NewDescriptor("test.name", otel.ValueObserverInstrumentKind, otel.Float64NumberKind) + desc := metric.NewDescriptor("test.name", metric.ValueObserverInstrumentKind, number.Float64Kind) lvagg, ckpt := metrictest.Unslice2(lastvalue.New(2)) - aggregatortest.CheckedUpdate(fix.t, lvagg, otel.NewFloat64Number(123.456), &desc) + aggregatortest.CheckedUpdate(fix.t, lvagg, number.NewFloat64Number(123.456), &desc) require.NoError(t, lvagg.SynchronizedMove(ckpt, &desc)) checkpointSet.Add(&desc, ckpt, tc.attrs...) diff --git a/exporters/stdout/trace_test.go b/exporters/stdout/trace_test.go index 2a1665545a2..83df6fe4ab4 100644 --- a/exporters/stdout/trace_test.go +++ b/exporters/stdout/trace_test.go @@ -22,12 +22,12 @@ import ( "testing" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/exporters/stdout" "go.opentelemetry.io/otel/label" export "go.opentelemetry.io/otel/sdk/export/trace" "go.opentelemetry.io/otel/sdk/resource" + "go.opentelemetry.io/otel/trace" ) func TestExporter_ExportSpan(t *testing.T) { @@ -40,14 +40,14 @@ func TestExporter_ExportSpan(t *testing.T) { // setup test span now := time.Now() - traceID, _ := otel.TraceIDFromHex("0102030405060708090a0b0c0d0e0f10") - spanID, _ := otel.SpanIDFromHex("0102030405060708") + traceID, _ := trace.TraceIDFromHex("0102030405060708090a0b0c0d0e0f10") + spanID, _ := trace.SpanIDFromHex("0102030405060708") keyValue := "value" doubleValue := 123.456 resource := resource.NewWithAttributes(label.String("rk1", "rv11")) testSpan := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: traceID, SpanID: spanID, }, @@ -62,7 +62,7 @@ func TestExporter_ExportSpan(t *testing.T) { {Name: "foo", Attributes: []label.KeyValue{label.String("key", keyValue)}, Time: now}, {Name: "bar", Attributes: []label.KeyValue{label.Float64("double", doubleValue)}, Time: now}, }, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, StatusCode: codes.Error, StatusMessage: "interesting", Resource: resource, diff --git a/exporters/trace/jaeger/jaeger.go b/exporters/trace/jaeger/jaeger.go index d6557c63aab..05df3cd5df2 100644 --- a/exporters/trace/jaeger/jaeger.go +++ b/exporters/trace/jaeger/jaeger.go @@ -22,13 +22,13 @@ import ( "google.golang.org/api/support/bundler" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" gen "go.opentelemetry.io/otel/exporters/trace/jaeger/internal/gen-go/jaeger" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" export "go.opentelemetry.io/otel/sdk/export/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" ) const ( @@ -151,14 +151,14 @@ func NewRawExporter(endpointOption EndpointOption, opts ...Option) (*Exporter, e // NewExportPipeline sets up a complete export pipeline // with the recommended setup for trace provider -func NewExportPipeline(endpointOption EndpointOption, opts ...Option) (otel.TracerProvider, func(), error) { +func NewExportPipeline(endpointOption EndpointOption, opts ...Option) (trace.TracerProvider, func(), error) { o := options{} opts = append(opts, WithDisabledFromEnv()) for _, opt := range opts { opt(&o) } if o.Disabled { - return otel.NewNoopTracerProvider(), func() {}, nil + return trace.NewNoopTracerProvider(), func() {}, nil } exporter, err := NewRawExporter(endpointOption, opts...) diff --git a/exporters/trace/jaeger/jaeger_test.go b/exporters/trace/jaeger/jaeger_test.go index 2eaef9d045d..7c2eaeb6ffd 100644 --- a/exporters/trace/jaeger/jaeger_test.go +++ b/exporters/trace/jaeger/jaeger_test.go @@ -28,7 +28,6 @@ import ( "github.com/stretchr/testify/require" "google.golang.org/api/support/bundler" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" gen "go.opentelemetry.io/otel/exporters/trace/jaeger/internal/gen-go/jaeger" "go.opentelemetry.io/otel/global" @@ -38,6 +37,7 @@ import ( "go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" ) const ( @@ -50,7 +50,7 @@ func TestInstallNewPipeline(t *testing.T) { name string endpoint EndpointOption options []Option - expectedProvider otel.TracerProvider + expectedProvider trace.TracerProvider }{ { name: "simple pipeline", @@ -68,7 +68,7 @@ func TestInstallNewPipeline(t *testing.T) { options: []Option{ WithDisabled(true), }, - expectedProvider: otel.NewNoopTracerProvider(), + expectedProvider: trace.NewNoopTracerProvider(), }, } @@ -93,7 +93,7 @@ func TestNewExportPipeline(t *testing.T) { name string endpoint EndpointOption options []Option - expectedProviderType otel.TracerProvider + expectedProviderType trace.TracerProvider testSpanSampling, spanShouldBeSampled bool }{ { @@ -107,7 +107,7 @@ func TestNewExportPipeline(t *testing.T) { options: []Option{ WithDisabled(true), }, - expectedProviderType: otel.NewNoopTracerProvider(), + expectedProviderType: trace.NewNoopTracerProvider(), }, { name: "always on", @@ -172,7 +172,7 @@ func TestNewExportPipelineWithDisabledFromEnv(t *testing.T) { ) defer fn() assert.NoError(t, err) - assert.IsType(t, otel.NewNoopTracerProvider(), tp) + assert.IsType(t, trace.NewNoopTracerProvider(), tp) } func TestNewRawExporter(t *testing.T) { @@ -355,11 +355,11 @@ func TestExporter_ExportSpan(t *testing.T) { func Test_spanDataToThrift(t *testing.T) { now := time.Now() - traceID, _ := otel.TraceIDFromHex("0102030405060708090a0b0c0d0e0f10") - spanID, _ := otel.SpanIDFromHex("0102030405060708") + traceID, _ := trace.TraceIDFromHex("0102030405060708090a0b0c0d0e0f10") + spanID, _ := trace.SpanIDFromHex("0102030405060708") - linkTraceID, _ := otel.TraceIDFromHex("0102030405060709090a0b0c0d0e0f11") - linkSpanID, _ := otel.SpanIDFromHex("0102030405060709") + linkTraceID, _ := trace.TraceIDFromHex("0102030405060709090a0b0c0d0e0f11") + linkSpanID, _ := trace.SpanIDFromHex("0102030405060709") eventNameValue := "event-test" keyValue := "value" @@ -382,16 +382,16 @@ func Test_spanDataToThrift(t *testing.T) { { name: "no parent", data: &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: traceID, SpanID: spanID, }, Name: "/foo", StartTime: now, EndTime: now, - Links: []otel.Link{ + Links: []trace.Link{ { - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: linkTraceID, SpanID: linkSpanID, }, @@ -408,7 +408,7 @@ func Test_spanDataToThrift(t *testing.T) { }, StatusCode: codes.Error, StatusMessage: statusMessage, - SpanKind: otel.SpanKindClient, + SpanKind: trace.SpanKindClient, Resource: resource.NewWithAttributes(label.String("rk1", rv1), label.Int64("rk2", rv2)), InstrumentationLibrary: instrumentation.Library{ Name: instrLibName, diff --git a/exporters/trace/zipkin/model.go b/exporters/trace/zipkin/model.go index 4070c64fe2b..e9d264b68aa 100644 --- a/exporters/trace/zipkin/model.go +++ b/exporters/trace/zipkin/model.go @@ -21,9 +21,9 @@ import ( zkmodel "github.com/openzipkin/zipkin-go/model" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" export "go.opentelemetry.io/otel/sdk/export/trace" + "go.opentelemetry.io/otel/trace" ) const ( @@ -67,18 +67,18 @@ func toZipkinSpanContext(data *export.SpanData) zkmodel.SpanContext { } } -func toZipkinTraceID(traceID otel.TraceID) zkmodel.TraceID { +func toZipkinTraceID(traceID trace.TraceID) zkmodel.TraceID { return zkmodel.TraceID{ High: binary.BigEndian.Uint64(traceID[:8]), Low: binary.BigEndian.Uint64(traceID[8:]), } } -func toZipkinID(spanID otel.SpanID) zkmodel.ID { +func toZipkinID(spanID trace.SpanID) zkmodel.ID { return zkmodel.ID(binary.BigEndian.Uint64(spanID[:])) } -func toZipkinParentID(spanID otel.SpanID) *zkmodel.ID { +func toZipkinParentID(spanID trace.SpanID) *zkmodel.ID { if spanID.IsValid() { id := toZipkinID(spanID) return &id @@ -86,21 +86,21 @@ func toZipkinParentID(spanID otel.SpanID) *zkmodel.ID { return nil } -func toZipkinKind(kind otel.SpanKind) zkmodel.Kind { +func toZipkinKind(kind trace.SpanKind) zkmodel.Kind { switch kind { - case otel.SpanKindUnspecified: + case trace.SpanKindUnspecified: return zkmodel.Undetermined - case otel.SpanKindInternal: + case trace.SpanKindInternal: // The spec says we should set the kind to nil, but // the model does not allow that. return zkmodel.Undetermined - case otel.SpanKindServer: + case trace.SpanKindServer: return zkmodel.Server - case otel.SpanKindClient: + case trace.SpanKindClient: return zkmodel.Client - case otel.SpanKindProducer: + case trace.SpanKindProducer: return zkmodel.Producer - case otel.SpanKindConsumer: + case trace.SpanKindConsumer: return zkmodel.Consumer } return zkmodel.Undetermined diff --git a/exporters/trace/zipkin/model_test.go b/exporters/trace/zipkin/model_test.go index edb45f9b670..ef0123341c8 100644 --- a/exporters/trace/zipkin/model_test.go +++ b/exporters/trace/zipkin/model_test.go @@ -24,23 +24,23 @@ import ( zkmodel "github.com/openzipkin/zipkin-go/model" "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/label" export "go.opentelemetry.io/otel/sdk/export/trace" "go.opentelemetry.io/otel/sdk/instrumentation" + "go.opentelemetry.io/otel/trace" ) func TestModelConversion(t *testing.T) { inputBatch := []*export.SpanData{ // typical span data { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }, - ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, - SpanKind: otel.SpanKindServer, + ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, + SpanKind: trace.SpanKindServer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), @@ -68,12 +68,12 @@ func TestModelConversion(t *testing.T) { // span data with no parent (same as typical, but has // invalid parent) { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }, - ParentSpanID: otel.SpanID{}, - SpanKind: otel.SpanKindServer, + ParentSpanID: trace.SpanID{}, + SpanKind: trace.SpanKindServer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), @@ -100,12 +100,12 @@ func TestModelConversion(t *testing.T) { }, // span data of unspecified kind { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }, - ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, - SpanKind: otel.SpanKindUnspecified, + ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, + SpanKind: trace.SpanKindUnspecified, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), @@ -132,12 +132,12 @@ func TestModelConversion(t *testing.T) { }, // span data of internal kind { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }, - ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, - SpanKind: otel.SpanKindInternal, + ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, + SpanKind: trace.SpanKindInternal, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), @@ -164,12 +164,12 @@ func TestModelConversion(t *testing.T) { }, // span data of client kind { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }, - ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, - SpanKind: otel.SpanKindClient, + ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, + SpanKind: trace.SpanKindClient, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), @@ -196,12 +196,12 @@ func TestModelConversion(t *testing.T) { }, // span data of producer kind { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }, - ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, - SpanKind: otel.SpanKindProducer, + ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, + SpanKind: trace.SpanKindProducer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), @@ -228,12 +228,12 @@ func TestModelConversion(t *testing.T) { }, // span data of consumer kind { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }, - ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, - SpanKind: otel.SpanKindConsumer, + ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, + SpanKind: trace.SpanKindConsumer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), @@ -260,12 +260,12 @@ func TestModelConversion(t *testing.T) { }, // span data with no events { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }, - ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, - SpanKind: otel.SpanKindServer, + ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, + SpanKind: trace.SpanKindServer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), @@ -279,12 +279,12 @@ func TestModelConversion(t *testing.T) { }, // span data with an "error" attribute set to "false" { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }, - ParentSpanID: otel.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, - SpanKind: otel.SpanKindServer, + ParentSpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, + SpanKind: trace.SpanKindServer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), diff --git a/exporters/trace/zipkin/zipkin_test.go b/exporters/trace/zipkin/zipkin_test.go index 5bd3b4e39b5..a8d45a56036 100644 --- a/exporters/trace/zipkin/zipkin_test.go +++ b/exporters/trace/zipkin/zipkin_test.go @@ -30,11 +30,11 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/global" export "go.opentelemetry.io/otel/sdk/export/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" ) const ( @@ -241,12 +241,12 @@ func TestExportSpans(t *testing.T) { spans := []*export.SpanData{ // parent { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }, - ParentSpanID: otel.SpanID{}, - SpanKind: otel.SpanKindServer, + ParentSpanID: trace.SpanID{}, + SpanKind: trace.SpanKindServer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), @@ -257,12 +257,12 @@ func TestExportSpans(t *testing.T) { }, // child { - SpanContext: otel.SpanContext{ - TraceID: otel.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, - SpanID: otel.SpanID{0xDF, 0xDE, 0xDD, 0xDC, 0xDB, 0xDA, 0xD9, 0xD8}, + SpanContext: trace.SpanContext{ + TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, + SpanID: trace.SpanID{0xDF, 0xDE, 0xDD, 0xDC, 0xDB, 0xDA, 0xD9, 0xD8}, }, - ParentSpanID: otel.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, - SpanKind: otel.SpanKindServer, + ParentSpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, + SpanKind: trace.SpanKindServer, Name: "bar", StartTime: time.Date(2020, time.March, 11, 19, 24, 15, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), diff --git a/global/internal/meter.go b/global/internal/meter.go index 1549059bfbb..afe0f41835f 100644 --- a/global/internal/meter.go +++ b/global/internal/meter.go @@ -20,9 +20,10 @@ import ( "sync/atomic" "unsafe" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" - "go.opentelemetry.io/otel/registry" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" + "go.opentelemetry.io/otel/metric/registry" ) // This file contains the forwarding implementation of MeterProvider used as @@ -51,7 +52,7 @@ type meterKey struct { } type meterProvider struct { - delegate otel.MeterProvider + delegate metric.MeterProvider // lock protects `delegate` and `meters`. lock sync.Mutex @@ -62,7 +63,7 @@ type meterProvider struct { } type meterImpl struct { - delegate unsafe.Pointer // (*otel.MeterImpl) + delegate unsafe.Pointer // (*metric.MeterImpl) lock sync.Mutex syncInsts []*syncImpl @@ -70,42 +71,42 @@ type meterImpl struct { } type meterEntry struct { - unique otel.MeterImpl + unique metric.MeterImpl impl meterImpl } type instrument struct { - descriptor otel.Descriptor + descriptor metric.Descriptor } type syncImpl struct { - delegate unsafe.Pointer // (*otel.SyncImpl) + delegate unsafe.Pointer // (*metric.SyncImpl) instrument } type asyncImpl struct { - delegate unsafe.Pointer // (*otel.AsyncImpl) + delegate unsafe.Pointer // (*metric.AsyncImpl) instrument - runner otel.AsyncRunner + runner metric.AsyncRunner } // SyncImpler is implemented by all of the sync metric // instruments. type SyncImpler interface { - SyncImpl() otel.SyncImpl + SyncImpl() metric.SyncImpl } // AsyncImpler is implemented by all of the async // metric instruments. type AsyncImpler interface { - AsyncImpl() otel.AsyncImpl + AsyncImpl() metric.AsyncImpl } type syncHandle struct { - delegate unsafe.Pointer // (*otel.HandleImpl) + delegate unsafe.Pointer // (*metric.BoundInstrumentImpl) inst *syncImpl labels []label.KeyValue @@ -113,13 +114,13 @@ type syncHandle struct { initialize sync.Once } -var _ otel.MeterProvider = &meterProvider{} -var _ otel.MeterImpl = &meterImpl{} -var _ otel.InstrumentImpl = &syncImpl{} -var _ otel.BoundSyncImpl = &syncHandle{} -var _ otel.AsyncImpl = &asyncImpl{} +var _ metric.MeterProvider = &meterProvider{} +var _ metric.MeterImpl = &meterImpl{} +var _ metric.InstrumentImpl = &syncImpl{} +var _ metric.BoundSyncImpl = &syncHandle{} +var _ metric.AsyncImpl = &asyncImpl{} -func (inst *instrument) Descriptor() otel.Descriptor { +func (inst *instrument) Descriptor() metric.Descriptor { return inst.descriptor } @@ -131,7 +132,7 @@ func newMeterProvider() *meterProvider { } } -func (p *meterProvider) setDelegate(provider otel.MeterProvider) { +func (p *meterProvider) setDelegate(provider metric.MeterProvider) { p.lock.Lock() defer p.lock.Unlock() @@ -142,7 +143,7 @@ func (p *meterProvider) setDelegate(provider otel.MeterProvider) { p.meters = nil } -func (p *meterProvider) Meter(instrumentationName string, opts ...otel.MeterOption) otel.Meter { +func (p *meterProvider) Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { p.lock.Lock() defer p.lock.Unlock() @@ -152,7 +153,7 @@ func (p *meterProvider) Meter(instrumentationName string, opts ...otel.MeterOpti key := meterKey{ Name: instrumentationName, - Version: otel.NewMeterConfig(opts...).InstrumentationVersion, + Version: metric.NewMeterConfig(opts...).InstrumentationVersion, } entry, ok := p.meters[key] if !ok { @@ -161,17 +162,17 @@ func (p *meterProvider) Meter(instrumentationName string, opts ...otel.MeterOpti p.meters[key] = entry } - return otel.WrapMeterImpl(entry.unique, key.Name, otel.WithInstrumentationVersion(key.Version)) + return metric.WrapMeterImpl(entry.unique, key.Name, metric.WithInstrumentationVersion(key.Version)) } // Meter interface and delegation -func (m *meterImpl) setDelegate(name, version string, provider otel.MeterProvider) { +func (m *meterImpl) setDelegate(name, version string, provider metric.MeterProvider) { m.lock.Lock() defer m.lock.Unlock() - d := new(otel.MeterImpl) - *d = provider.Meter(name, otel.WithInstrumentationVersion(version)).MeterImpl() + d := new(metric.MeterImpl) + *d = provider.Meter(name, metric.WithInstrumentationVersion(version)).MeterImpl() m.delegate = unsafe.Pointer(d) for _, inst := range m.syncInsts { @@ -184,11 +185,11 @@ func (m *meterImpl) setDelegate(name, version string, provider otel.MeterProvide m.asyncInsts = nil } -func (m *meterImpl) NewSyncInstrument(desc otel.Descriptor) (otel.SyncImpl, error) { +func (m *meterImpl) NewSyncInstrument(desc metric.Descriptor) (metric.SyncImpl, error) { m.lock.Lock() defer m.lock.Unlock() - if meterPtr := (*otel.MeterImpl)(atomic.LoadPointer(&m.delegate)); meterPtr != nil { + if meterPtr := (*metric.MeterImpl)(atomic.LoadPointer(&m.delegate)); meterPtr != nil { return (*meterPtr).NewSyncInstrument(desc) } @@ -203,8 +204,8 @@ func (m *meterImpl) NewSyncInstrument(desc otel.Descriptor) (otel.SyncImpl, erro // Synchronous delegation -func (inst *syncImpl) setDelegate(d otel.MeterImpl) { - implPtr := new(otel.SyncImpl) +func (inst *syncImpl) setDelegate(d metric.MeterImpl) { + implPtr := new(metric.SyncImpl) var err error *implPtr, err = d.NewSyncInstrument(inst.descriptor) @@ -221,14 +222,14 @@ func (inst *syncImpl) setDelegate(d otel.MeterImpl) { } func (inst *syncImpl) Implementation() interface{} { - if implPtr := (*otel.SyncImpl)(atomic.LoadPointer(&inst.delegate)); implPtr != nil { + if implPtr := (*metric.SyncImpl)(atomic.LoadPointer(&inst.delegate)); implPtr != nil { return (*implPtr).Implementation() } return inst } -func (inst *syncImpl) Bind(labels []label.KeyValue) otel.BoundSyncImpl { - if implPtr := (*otel.SyncImpl)(atomic.LoadPointer(&inst.delegate)); implPtr != nil { +func (inst *syncImpl) Bind(labels []label.KeyValue) metric.BoundSyncImpl { + if implPtr := (*metric.SyncImpl)(atomic.LoadPointer(&inst.delegate)); implPtr != nil { return (*implPtr).Bind(labels) } return &syncHandle{ @@ -240,7 +241,7 @@ func (inst *syncImpl) Bind(labels []label.KeyValue) otel.BoundSyncImpl { func (bound *syncHandle) Unbind() { bound.initialize.Do(func() {}) - implPtr := (*otel.BoundSyncImpl)(atomic.LoadPointer(&bound.delegate)) + implPtr := (*metric.BoundSyncImpl)(atomic.LoadPointer(&bound.delegate)) if implPtr == nil { return @@ -252,14 +253,14 @@ func (bound *syncHandle) Unbind() { // Async delegation func (m *meterImpl) NewAsyncInstrument( - desc otel.Descriptor, - runner otel.AsyncRunner, -) (otel.AsyncImpl, error) { + desc metric.Descriptor, + runner metric.AsyncRunner, +) (metric.AsyncImpl, error) { m.lock.Lock() defer m.lock.Unlock() - if meterPtr := (*otel.MeterImpl)(atomic.LoadPointer(&m.delegate)); meterPtr != nil { + if meterPtr := (*metric.MeterImpl)(atomic.LoadPointer(&m.delegate)); meterPtr != nil { return (*meterPtr).NewAsyncInstrument(desc, runner) } @@ -274,14 +275,14 @@ func (m *meterImpl) NewAsyncInstrument( } func (obs *asyncImpl) Implementation() interface{} { - if implPtr := (*otel.AsyncImpl)(atomic.LoadPointer(&obs.delegate)); implPtr != nil { + if implPtr := (*metric.AsyncImpl)(atomic.LoadPointer(&obs.delegate)); implPtr != nil { return (*implPtr).Implementation() } return obs } -func (obs *asyncImpl) setDelegate(d otel.MeterImpl) { - implPtr := new(otel.AsyncImpl) +func (obs *asyncImpl) setDelegate(d metric.MeterImpl) { + implPtr := new(metric.AsyncImpl) var err error *implPtr, err = d.NewAsyncInstrument(obs.descriptor, obs.runner) @@ -299,33 +300,33 @@ func (obs *asyncImpl) setDelegate(d otel.MeterImpl) { // Metric updates -func (m *meterImpl) RecordBatch(ctx context.Context, labels []label.KeyValue, measurements ...otel.Measurement) { - if delegatePtr := (*otel.MeterImpl)(atomic.LoadPointer(&m.delegate)); delegatePtr != nil { +func (m *meterImpl) RecordBatch(ctx context.Context, labels []label.KeyValue, measurements ...metric.Measurement) { + if delegatePtr := (*metric.MeterImpl)(atomic.LoadPointer(&m.delegate)); delegatePtr != nil { (*delegatePtr).RecordBatch(ctx, labels, measurements...) } } -func (inst *syncImpl) RecordOne(ctx context.Context, number otel.Number, labels []label.KeyValue) { - if instPtr := (*otel.SyncImpl)(atomic.LoadPointer(&inst.delegate)); instPtr != nil { +func (inst *syncImpl) RecordOne(ctx context.Context, number number.Number, labels []label.KeyValue) { + if instPtr := (*metric.SyncImpl)(atomic.LoadPointer(&inst.delegate)); instPtr != nil { (*instPtr).RecordOne(ctx, number, labels) } } // Bound instrument initialization -func (bound *syncHandle) RecordOne(ctx context.Context, number otel.Number) { - instPtr := (*otel.SyncImpl)(atomic.LoadPointer(&bound.inst.delegate)) +func (bound *syncHandle) RecordOne(ctx context.Context, number number.Number) { + instPtr := (*metric.SyncImpl)(atomic.LoadPointer(&bound.inst.delegate)) if instPtr == nil { return } - var implPtr *otel.BoundSyncImpl + var implPtr *metric.BoundSyncImpl bound.initialize.Do(func() { - implPtr = new(otel.BoundSyncImpl) + implPtr = new(metric.BoundSyncImpl) *implPtr = (*instPtr).Bind(bound.labels) atomic.StorePointer(&bound.delegate, unsafe.Pointer(implPtr)) }) if implPtr == nil { - implPtr = (*otel.BoundSyncImpl)(atomic.LoadPointer(&bound.delegate)) + implPtr = (*metric.BoundSyncImpl)(atomic.LoadPointer(&bound.delegate)) } // This may still be nil if instrument was created and bound // without a delegate, then the instrument was set to have a diff --git a/global/internal/meter_test.go b/global/internal/meter_test.go index 7c7b887c217..70147d0dc4c 100644 --- a/global/internal/meter_test.go +++ b/global/internal/meter_test.go @@ -21,23 +21,24 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/global/internal" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/oteltest" ) -var Must = otel.Must +var Must = metric.Must -var asInt = otel.NewInt64Number -var asFloat = otel.NewFloat64Number +var asInt = number.NewInt64Number +var asFloat = number.NewFloat64Number func TestDirect(t *testing.T) { internal.ResetForTest() ctx := context.Background() - meter1 := global.Meter("test1", otel.WithInstrumentationVersion("semver:v1.0.0")) + meter1 := global.Meter("test1", metric.WithInstrumentationVersion("semver:v1.0.0")) meter2 := global.Meter("test2") labels1 := []label.KeyValue{label.String("A", "B")} labels2 := []label.KeyValue{label.String("C", "D")} @@ -51,12 +52,12 @@ func TestDirect(t *testing.T) { valuerecorder.Record(ctx, 1, labels1...) valuerecorder.Record(ctx, 2, labels1...) - _ = Must(meter1).NewFloat64ValueObserver("test.valueobserver.float", func(_ context.Context, result otel.Float64ObserverResult) { + _ = Must(meter1).NewFloat64ValueObserver("test.valueobserver.float", func(_ context.Context, result metric.Float64ObserverResult) { result.Observe(1., labels1...) result.Observe(2., labels2...) }) - _ = Must(meter1).NewInt64ValueObserver("test.valueobserver.int", func(_ context.Context, result otel.Int64ObserverResult) { + _ = Must(meter1).NewInt64ValueObserver("test.valueobserver.int", func(_ context.Context, result metric.Int64ObserverResult) { result.Observe(1, labels1...) result.Observe(2, labels2...) }) @@ -213,19 +214,19 @@ func TestUnbindThenRecordOne(t *testing.T) { } type meterProviderWithConstructorError struct { - otel.MeterProvider + metric.MeterProvider } type meterWithConstructorError struct { - otel.MeterImpl + metric.MeterImpl } -func (m *meterProviderWithConstructorError) Meter(iName string, opts ...otel.MeterOption) otel.Meter { - return otel.WrapMeterImpl(&meterWithConstructorError{m.MeterProvider.Meter(iName, opts...).MeterImpl()}, iName, opts...) +func (m *meterProviderWithConstructorError) Meter(iName string, opts ...metric.MeterOption) metric.Meter { + return metric.WrapMeterImpl(&meterWithConstructorError{m.MeterProvider.Meter(iName, opts...).MeterImpl()}, iName, opts...) } -func (m *meterWithConstructorError) NewSyncInstrument(_ otel.Descriptor) (otel.SyncImpl, error) { - return otel.NoopSync{}, errors.New("constructor error") +func (m *meterWithConstructorError) NewSyncInstrument(_ metric.Descriptor) (metric.SyncImpl, error) { + return metric.NoopSync{}, errors.New("constructor error") } func TestErrorInDeferredConstructor(t *testing.T) { @@ -269,7 +270,7 @@ func TestImplementationIndirection(t *testing.T) { // Async: no SDK yet valueobserver := Must(meter1).NewFloat64ValueObserver( "interface.valueobserver", - func(_ context.Context, result otel.Float64ObserverResult) {}, + func(_ context.Context, result metric.Float64ObserverResult) {}, ) ival = valueobserver.AsyncImpl().Implementation() diff --git a/global/internal/registry_test.go b/global/internal/registry_test.go index 42f0aec00e3..ba67eba984e 100644 --- a/global/internal/registry_test.go +++ b/global/internal/registry_test.go @@ -21,48 +21,48 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/registry" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/registry" ) type ( - newFunc func(name, libraryName string) (otel.InstrumentImpl, error) + newFunc func(name, libraryName string) (metric.InstrumentImpl, error) ) var ( allNew = map[string]newFunc{ - "counter.int64": func(name, libraryName string) (otel.InstrumentImpl, error) { + "counter.int64": func(name, libraryName string) (metric.InstrumentImpl, error) { return unwrap(MeterProvider().Meter(libraryName).NewInt64Counter(name)) }, - "counter.float64": func(name, libraryName string) (otel.InstrumentImpl, error) { + "counter.float64": func(name, libraryName string) (metric.InstrumentImpl, error) { return unwrap(MeterProvider().Meter(libraryName).NewFloat64Counter(name)) }, - "valuerecorder.int64": func(name, libraryName string) (otel.InstrumentImpl, error) { + "valuerecorder.int64": func(name, libraryName string) (metric.InstrumentImpl, error) { return unwrap(MeterProvider().Meter(libraryName).NewInt64ValueRecorder(name)) }, - "valuerecorder.float64": func(name, libraryName string) (otel.InstrumentImpl, error) { + "valuerecorder.float64": func(name, libraryName string) (metric.InstrumentImpl, error) { return unwrap(MeterProvider().Meter(libraryName).NewFloat64ValueRecorder(name)) }, - "valueobserver.int64": func(name, libraryName string) (otel.InstrumentImpl, error) { - return unwrap(MeterProvider().Meter(libraryName).NewInt64ValueObserver(name, func(context.Context, otel.Int64ObserverResult) {})) + "valueobserver.int64": func(name, libraryName string) (metric.InstrumentImpl, error) { + return unwrap(MeterProvider().Meter(libraryName).NewInt64ValueObserver(name, func(context.Context, metric.Int64ObserverResult) {})) }, - "valueobserver.float64": func(name, libraryName string) (otel.InstrumentImpl, error) { - return unwrap(MeterProvider().Meter(libraryName).NewFloat64ValueObserver(name, func(context.Context, otel.Float64ObserverResult) {})) + "valueobserver.float64": func(name, libraryName string) (metric.InstrumentImpl, error) { + return unwrap(MeterProvider().Meter(libraryName).NewFloat64ValueObserver(name, func(context.Context, metric.Float64ObserverResult) {})) }, } ) -func unwrap(impl interface{}, err error) (otel.InstrumentImpl, error) { +func unwrap(impl interface{}, err error) (metric.InstrumentImpl, error) { if impl == nil { return nil, err } if s, ok := impl.(interface { - SyncImpl() otel.SyncImpl + SyncImpl() metric.SyncImpl }); ok { return s.SyncImpl(), err } if a, ok := impl.(interface { - AsyncImpl() otel.AsyncImpl + AsyncImpl() metric.AsyncImpl }); ok { return a.AsyncImpl(), err } diff --git a/global/internal/state.go b/global/internal/state.go index 7248664978a..8f6cc1590b6 100644 --- a/global/internal/state.go +++ b/global/internal/state.go @@ -19,15 +19,17 @@ import ( "sync/atomic" "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/trace" ) type ( tracerProviderHolder struct { - tp otel.TracerProvider + tp trace.TracerProvider } meterProviderHolder struct { - mp otel.MeterProvider + mp metric.MeterProvider } propagatorsHolder struct { @@ -46,12 +48,12 @@ var ( ) // TracerProvider is the internal implementation for global.TracerProvider. -func TracerProvider() otel.TracerProvider { +func TracerProvider() trace.TracerProvider { return globalTracer.Load().(tracerProviderHolder).tp } // SetTracerProvider is the internal implementation for global.SetTracerProvider. -func SetTracerProvider(tp otel.TracerProvider) { +func SetTracerProvider(tp trace.TracerProvider) { delegateTraceOnce.Do(func() { current := TracerProvider() if current == tp { @@ -68,12 +70,12 @@ func SetTracerProvider(tp otel.TracerProvider) { } // MeterProvider is the internal implementation for global.MeterProvider. -func MeterProvider() otel.MeterProvider { +func MeterProvider() metric.MeterProvider { return globalMeter.Load().(meterProviderHolder).mp } // SetMeterProvider is the internal implementation for global.SetMeterProvider. -func SetMeterProvider(mp otel.MeterProvider) { +func SetMeterProvider(mp metric.MeterProvider) { delegateMeterOnce.Do(func() { current := MeterProvider() diff --git a/global/internal/trace.go b/global/internal/trace.go index d74966c0465..c60828e8a44 100644 --- a/global/internal/trace.go +++ b/global/internal/trace.go @@ -35,8 +35,8 @@ import ( "context" "sync" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/internal/trace/noop" + "go.opentelemetry.io/otel/trace" ) // tracerProvider is a placeholder for a configured SDK TracerProvider. @@ -47,12 +47,12 @@ type tracerProvider struct { mtx sync.Mutex tracers []*tracer - delegate otel.TracerProvider + delegate trace.TracerProvider } // Compile-time guarantee that tracerProvider implements the TracerProvider // interface. -var _ otel.TracerProvider = &tracerProvider{} +var _ trace.TracerProvider = &tracerProvider{} // setDelegate configures p to delegate all TracerProvider functionality to // provider. @@ -62,7 +62,7 @@ var _ otel.TracerProvider = &tracerProvider{} // // Delegation only happens on the first call to this method. All subsequent // calls result in no delegation changes. -func (p *tracerProvider) setDelegate(provider otel.TracerProvider) { +func (p *tracerProvider) setDelegate(provider trace.TracerProvider) { if p.delegate != nil { return } @@ -79,7 +79,7 @@ func (p *tracerProvider) setDelegate(provider otel.TracerProvider) { } // Tracer implements TracerProvider. -func (p *tracerProvider) Tracer(name string, opts ...otel.TracerOption) otel.Tracer { +func (p *tracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer { p.mtx.Lock() defer p.mtx.Unlock() @@ -92,20 +92,20 @@ func (p *tracerProvider) Tracer(name string, opts ...otel.TracerOption) otel.Tra return t } -// tracer is a placeholder for a otel.Tracer. +// tracer is a placeholder for a trace.Tracer. // // All Tracer functionality is forwarded to a delegate once configured. // Otherwise, all functionality is forwarded to a NoopTracer. type tracer struct { once sync.Once name string - opts []otel.TracerOption + opts []trace.TracerOption - delegate otel.Tracer + delegate trace.Tracer } -// Compile-time guarantee that tracer implements the otel.Tracer interface. -var _ otel.Tracer = &tracer{} +// Compile-time guarantee that tracer implements the trace.Tracer interface. +var _ trace.Tracer = &tracer{} // setDelegate configures t to delegate all Tracer functionality to Tracers // created by provider. @@ -114,13 +114,13 @@ var _ otel.Tracer = &tracer{} // // Delegation only happens on the first call to this method. All subsequent // calls result in no delegation changes. -func (t *tracer) setDelegate(provider otel.TracerProvider) { +func (t *tracer) setDelegate(provider trace.TracerProvider) { t.once.Do(func() { t.delegate = provider.Tracer(t.name, t.opts...) }) } -// Start implements otel.Tracer by forwarding the call to t.delegate if +// Start implements trace.Tracer by forwarding the call to t.delegate if // set, otherwise it forwards the call to a NoopTracer. -func (t *tracer) Start(ctx context.Context, name string, opts ...otel.SpanOption) (context.Context, otel.Span) { +func (t *tracer) Start(ctx context.Context, name string, opts ...trace.SpanOption) (context.Context, trace.Span) { if t.delegate != nil { return t.delegate.Start(ctx, name, opts...) } diff --git a/global/metric.go b/global/metric.go index d4169c8e51c..d569d73f86d 100644 --- a/global/metric.go +++ b/global/metric.go @@ -15,8 +15,8 @@ package global // import "go.opentelemetry.io/otel/global" import ( - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global/internal" + "go.opentelemetry.io/otel/metric" ) // Meter creates an implementation of the Meter interface from the global @@ -27,7 +27,7 @@ import ( // will be used instead. // // This is short for MeterProvider().Meter(name) -func Meter(instrumentationName string, opts ...otel.MeterOption) otel.Meter { +func Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { return MeterProvider().Meter(instrumentationName, opts...) } @@ -39,11 +39,11 @@ func Meter(instrumentationName string, opts ...otel.MeterOption) otel.Meter { // meter := global.MeterProvider().Meter("example.com/foo") // or // meter := global.Meter("example.com/foo") -func MeterProvider() otel.MeterProvider { +func MeterProvider() metric.MeterProvider { return internal.MeterProvider() } // SetMeterProvider registers `mp` as the global meter provider. -func SetMeterProvider(mp otel.MeterProvider) { +func SetMeterProvider(mp metric.MeterProvider) { internal.SetMeterProvider(mp) } diff --git a/global/metric_test.go b/global/metric_test.go index bd768b59d74..aeb4ebe25ce 100644 --- a/global/metric_test.go +++ b/global/metric_test.go @@ -17,21 +17,21 @@ package global_test import ( "testing" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" + "go.opentelemetry.io/otel/metric" ) type testMeterProvider struct{} -var _ otel.MeterProvider = &testMeterProvider{} +var _ metric.MeterProvider = &testMeterProvider{} -func (*testMeterProvider) Meter(_ string, _ ...otel.MeterOption) otel.Meter { - return otel.Meter{} +func (*testMeterProvider) Meter(_ string, _ ...metric.MeterOption) metric.Meter { + return metric.Meter{} } func TestMultipleGlobalMeterProvider(t *testing.T) { p1 := testMeterProvider{} - p2 := otel.NoopMeterProvider{} + p2 := metric.NoopMeterProvider{} global.SetMeterProvider(&p1) global.SetMeterProvider(&p2) diff --git a/global/trace.go b/global/trace.go index c0410e178d8..97660fbac5d 100644 --- a/global/trace.go +++ b/global/trace.go @@ -15,15 +15,15 @@ package global // import "go.opentelemetry.io/otel/global" import ( - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global/internal" + "go.opentelemetry.io/otel/trace" ) // Tracer creates a named tracer that implements Tracer interface. // If the name is an empty string then provider uses default name. // // This is short for TracerProvider().Tracer(name) -func Tracer(name string) otel.Tracer { +func Tracer(name string) trace.Tracer { return TracerProvider().Tracer(name) } @@ -34,11 +34,11 @@ func Tracer(name string) otel.Tracer { // tracer := global.TracerProvider().Tracer("example.com/foo") // or // tracer := global.Tracer("example.com/foo") -func TracerProvider() otel.TracerProvider { +func TracerProvider() trace.TracerProvider { return internal.TracerProvider() } // SetTracerProvider registers `tp` as the global trace provider. -func SetTracerProvider(tp otel.TracerProvider) { +func SetTracerProvider(tp trace.TracerProvider) { internal.SetTracerProvider(tp) } diff --git a/global/trace_test.go b/global/trace_test.go index cbcbeef74e2..0c6bd385896 100644 --- a/global/trace_test.go +++ b/global/trace_test.go @@ -17,22 +17,22 @@ package global_test import ( "testing" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/internal/trace/noop" + "go.opentelemetry.io/otel/trace" ) type testTracerProvider struct{} -var _ otel.TracerProvider = &testTracerProvider{} +var _ trace.TracerProvider = &testTracerProvider{} -func (*testTracerProvider) Tracer(_ string, _ ...otel.TracerOption) otel.Tracer { +func (*testTracerProvider) Tracer(_ string, _ ...trace.TracerOption) trace.Tracer { return noop.Tracer } func TestMultipleGlobalTracerProvider(t *testing.T) { p1 := testTracerProvider{} - p2 := otel.NewNoopTracerProvider() + p2 := trace.NewNoopTracerProvider() global.SetTracerProvider(&p1) global.SetTracerProvider(p2) diff --git a/internal/metric/async.go b/internal/metric/async.go index fa1b2ead1a2..8b1a2b3742a 100644 --- a/internal/metric/async.go +++ b/internal/metric/async.go @@ -20,9 +20,9 @@ import ( "fmt" "sync" - api "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" ) var ErrInvalidAsyncRunner = errors.New("unknown async runner type") @@ -32,7 +32,7 @@ var ErrInvalidAsyncRunner = errors.New("unknown async runner type") // the SDK to provide support for running observer callbacks. type AsyncCollector interface { // CollectAsync passes a batch of observations to the MeterImpl. - CollectAsync(labels []label.KeyValue, observation ...api.Observation) + CollectAsync(labels []label.KeyValue, observation ...metric.Observation) } // AsyncInstrumentState manages an ordered set of asynchronous @@ -60,18 +60,18 @@ type AsyncInstrumentState struct { // instruments maintains the set of instruments in the order // they were registered. - instruments []api.AsyncImpl + instruments []metric.AsyncImpl } // asyncRunnerPair is a map entry for Observer callback runners. type asyncRunnerPair struct { // runner is used as a map key here. The API ensures // that all callbacks are pointers for this reason. - runner api.AsyncRunner + runner metric.AsyncRunner // inst refers to a non-nil instrument when `runner` is a // AsyncSingleRunner. - inst api.AsyncImpl + inst metric.AsyncImpl } // NewAsyncInstrumentState returns a new *AsyncInstrumentState, for @@ -86,7 +86,7 @@ func NewAsyncInstrumentState() *AsyncInstrumentState { // Instruments returns the asynchronous instruments managed by this // object, the set that should be checkpointed after observers are // run. -func (a *AsyncInstrumentState) Instruments() []api.AsyncImpl { +func (a *AsyncInstrumentState) Instruments() []metric.AsyncImpl { a.lock.Lock() defer a.lock.Unlock() return a.instruments @@ -96,7 +96,7 @@ func (a *AsyncInstrumentState) Instruments() []api.AsyncImpl { // object. This should be called during NewAsyncInstrument() and // assumes that errors (e.g., duplicate registration) have already // been checked. -func (a *AsyncInstrumentState) Register(inst api.AsyncImpl, runner api.AsyncRunner) { +func (a *AsyncInstrumentState) Register(inst metric.AsyncImpl, runner metric.AsyncRunner) { a.lock.Lock() defer a.lock.Unlock() @@ -110,7 +110,7 @@ func (a *AsyncInstrumentState) Register(inst api.AsyncImpl, runner api.AsyncRunn rp := asyncRunnerPair{ runner: runner, } - if _, ok := runner.(api.AsyncSingleRunner); ok { + if _, ok := runner.(metric.AsyncSingleRunner); ok { rp.inst = inst } @@ -131,12 +131,12 @@ func (a *AsyncInstrumentState) Run(ctx context.Context, collector AsyncCollector // other implementations are possible because the // interface has un-exported methods. - if singleRunner, ok := rp.runner.(api.AsyncSingleRunner); ok { + if singleRunner, ok := rp.runner.(metric.AsyncSingleRunner); ok { singleRunner.Run(ctx, rp.inst, collector.CollectAsync) continue } - if multiRunner, ok := rp.runner.(api.AsyncBatchRunner); ok { + if multiRunner, ok := rp.runner.(metric.AsyncBatchRunner); ok { multiRunner.Run(ctx, collector.CollectAsync) continue } diff --git a/internal/tools/go.mod b/internal/tools/go.mod index f6ace6f8014..2c6a978ade3 100644 --- a/internal/tools/go.mod +++ b/internal/tools/go.mod @@ -4,7 +4,7 @@ go 1.14 require ( github.com/client9/misspell v0.3.4 - github.com/golangci/golangci-lint v1.32.1 + github.com/golangci/golangci-lint v1.32.2 github.com/itchyny/gojq v0.11.2 golang.org/x/tools v0.0.0-20201013201025-64a9e34f3752 ) diff --git a/internal/tools/go.sum b/internal/tools/go.sum index b0e3cacb88c..f548d3eae5c 100644 --- a/internal/tools/go.sum +++ b/internal/tools/go.sum @@ -59,6 +59,8 @@ github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s= github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU= +github.com/fatih/color v1.10.0 h1:s36xzo75JdqLaaWoiEHk767eHiwo0598uUxyfiPkDsg= +github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= @@ -131,8 +133,8 @@ github.com/golangci/gocyclo v0.0.0-20180528144436-0a533e8fa43d h1:pXTK/gkVNs7Zyy github.com/golangci/gocyclo v0.0.0-20180528144436-0a533e8fa43d/go.mod h1:ozx7R9SIwqmqf5pRP90DhR2Oay2UIjGuKheCBCNwAYU= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a h1:iR3fYXUjHCR97qWS8ch1y9zPNsgXThGwjKPrYfqMPks= github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a/go.mod h1:9qCChq59u/eW8im404Q2WWTrnBUQKjpNYKMbU4M7EFU= -github.com/golangci/golangci-lint v1.32.1 h1:XaDrjRo5VmoAwhCTKKlE2EpjWmrAoK2qaJ3xoooqFmw= -github.com/golangci/golangci-lint v1.32.1/go.mod h1:8lqePWOtRXUYRU0BpoPyp+uZCYKMWxxCLEPBMto6HUg= +github.com/golangci/golangci-lint v1.32.2 h1:CgIeFWTLJ3Nt1w/WU1RO351j/CjN6LIVjppbJfI9nMk= +github.com/golangci/golangci-lint v1.32.2/go.mod h1:ydr+IqtIVyAh72L16aK0bNdNg/YGa+AEgdbKj9MluzI= github.com/golangci/ineffassign v0.0.0-20190609212857-42439a7714cc h1:gLLhTLMk2/SutryVJ6D4VZCU3CUqr8YloG7FPIBWFpI= github.com/golangci/ineffassign v0.0.0-20190609212857-42439a7714cc/go.mod h1:e5tpTHCfVze+7EpLEozzMB3eafxo2KT5veNg1k6byQU= github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0 h1:MfyDlzVjl1hoaPzPD4Gpb/QgoRfSBR0jdhwGyAWwMSA= @@ -164,7 +166,7 @@ github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm4 github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= -github.com/gookit/color v1.2.5/go.mod h1:AhIE+pS6D4Ql0SQWbBeXPHw7gY0/sjHoA4s/n1KB7xg= +github.com/gookit/color v1.3.1/go.mod h1:R3ogXq2B9rTbXoSHJ1HyUVAZ3poOJHpd9nQmyGZsfvQ= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= @@ -304,11 +306,13 @@ github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= -github.com/onsi/ginkgo v1.13.0 h1:M76yO2HkZASFjXL0HSoZJ1AYEmQxNJmY41Jx1zNUq1Y= -github.com/onsi/ginkgo v1.13.0/go.mod h1:+REjRxOmWfHCjfv9TTWB1jD1Frx4XydAD3zm1lskyM0= +github.com/onsi/ginkgo v1.14.1 h1:jMU0WaQrP0a/YAEq8eJmJKjBoMs+pClEr1vDMlM/Do4= +github.com/onsi/ginkgo v1.14.1/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/onsi/gomega v1.10.2 h1:aY/nuoWlKJud2J6U0E3NWsjlg+0GtwXxgEqthRdzlcs= +github.com/onsi/gomega v1.10.2/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= @@ -349,10 +353,9 @@ github.com/ryancurrah/gomodguard v1.1.0/go.mod h1:4O8tr7hBODaGE6VIhfJDHcwzh5GUcc github.com/ryanrolds/sqlclosecheck v0.3.0 h1:AZx+Bixh8zdUBxUA1NxbxVAS78vTPq4rCb8OUZI9xFw= github.com/ryanrolds/sqlclosecheck v0.3.0/go.mod h1:1gREqxyTGR3lVtpngyFo3hZAgk0KCtEdgEkHwDbigdA= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= -github.com/sclevine/agouti v3.0.0+incompatible/go.mod h1:b4WX9W9L1sfQKXeJf1mUTLZKJ48R1S7H23Ji7oFO5Bw= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/securego/gosec/v2 v2.4.0 h1:ivAoWcY5DMs9n04Abc1VkqZBO0FL0h4ShTcVsC53lCE= -github.com/securego/gosec/v2 v2.4.0/go.mod h1:0/Q4cjmlFDfDUj1+Fib61sc+U5IQb2w+Iv9/C3wPVko= +github.com/securego/gosec/v2 v2.5.0 h1:kjfXLeKdk98gBe2+eYRFMpC4+mxmQQtbidpiiOQ69Qc= +github.com/securego/gosec/v2 v2.5.0/go.mod h1:L/CDXVntIff5ypVHIkqPXbtRpJiNCh6c6Amn68jXDjo= github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c h1:W65qqJCIOVP4jpqPQ0YvHYKwcMEMVWIzWC5iNQQfBTU= github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c/go.mod h1:/PevMnwAxekIXwN8qQyfc5gl2NlkB3CQlkizAbOkeBs= github.com/shirou/gopsutil v0.0.0-20190901111213-e4ec7b275ada/go.mod h1:WWnYX4lzhCH5h/3YBfyVA3VbLYjlMZZAQcW9ojMexNc= @@ -574,7 +577,6 @@ golang.org/x/tools v0.0.0-20200422022333-3d57cf2e726e/go.mod h1:EkVYQZoAsY45+roY golang.org/x/tools v0.0.0-20200426102838-f3a5411a4c3b/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200624225443-88f3c62a19ff/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200625211823-6506e20df31f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= -golang.org/x/tools v0.0.0-20200701041122-1837592efa10/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305 h1:yaM5S0KcY0lIoZo7Fl+oi91b/DdlU2zuWpfHrpWbCS0= golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200731060945-b5fad4ed8dd6/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= @@ -583,6 +585,7 @@ golang.org/x/tools v0.0.0-20200812195022-5ae4c3c160a0/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200831203904-5a2aa26beb65/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= golang.org/x/tools v0.0.0-20201001104356-43ebab892c4c/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20201002184944-ecd9fd270d5d/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= +golang.org/x/tools v0.0.0-20201007032633-0806396f153e/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20201011145850-ed2f50202694/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= golang.org/x/tools v0.0.0-20201013201025-64a9e34f3752 h1:2ntEwh02rqo2jSsrYmp4yKHHjh0CbXP3ZtSUetSB+q8= golang.org/x/tools v0.0.0-20201013201025-64a9e34f3752/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= diff --git a/internal/trace/noop/noop.go b/internal/trace/noop/noop.go index bfca48381a1..765c21a289c 100644 --- a/internal/trace/noop/noop.go +++ b/internal/trace/noop/noop.go @@ -18,18 +18,18 @@ package noop import ( "context" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" ) var ( // Tracer is a noop tracer that starts noop spans. - Tracer otel.Tracer + Tracer trace.Tracer // Span is a noop Span. - Span otel.Span + Span trace.Span ) func init() { - Tracer = otel.NewNoopTracerProvider().Tracer("") + Tracer = trace.NewNoopTracerProvider().Tracer("") _, Span = Tracer.Start(context.Background(), "") } diff --git a/internal/trace/parent/parent.go b/internal/trace/parent/parent.go index 27d65579a6a..0529265108d 100644 --- a/internal/trace/parent/parent.go +++ b/internal/trace/parent/parent.go @@ -17,19 +17,19 @@ package parent import ( "context" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" ) -func GetSpanContextAndLinks(ctx context.Context, ignoreContext bool) (otel.SpanContext, bool, []otel.Link) { - lsctx := otel.SpanContextFromContext(ctx) - rsctx := otel.RemoteSpanContextFromContext(ctx) +func GetSpanContextAndLinks(ctx context.Context, ignoreContext bool) (trace.SpanContext, bool, []trace.Link) { + lsctx := trace.SpanContextFromContext(ctx) + rsctx := trace.RemoteSpanContextFromContext(ctx) if ignoreContext { links := addLinkIfValid(nil, lsctx, "current") links = addLinkIfValid(links, rsctx, "remote") - return otel.SpanContext{}, false, links + return trace.SpanContext{}, false, links } if lsctx.IsValid() { return lsctx, false, nil @@ -37,14 +37,14 @@ func GetSpanContextAndLinks(ctx context.Context, ignoreContext bool) (otel.SpanC if rsctx.IsValid() { return rsctx, true, nil } - return otel.SpanContext{}, false, nil + return trace.SpanContext{}, false, nil } -func addLinkIfValid(links []otel.Link, sc otel.SpanContext, kind string) []otel.Link { +func addLinkIfValid(links []trace.Link, sc trace.SpanContext, kind string) []trace.Link { if !sc.IsValid() { return links } - return append(links, otel.Link{ + return append(links, trace.Link{ SpanContext: sc, Attributes: []label.KeyValue{ label.String("ignored-on-demand", kind), diff --git a/alignment_test.go b/metric/alignment_test.go similarity index 98% rename from alignment_test.go rename to metric/alignment_test.go index 7059c63d609..3dc469907f0 100644 --- a/alignment_test.go +++ b/metric/alignment_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel +package metric import ( "os" diff --git a/metric/config.go b/metric/config.go new file mode 100644 index 00000000000..02f0ff8e0cb --- /dev/null +++ b/metric/config.go @@ -0,0 +1,128 @@ +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package metric // import "go.opentelemetry.io/otel/metric" + +import ( + "go.opentelemetry.io/otel/unit" +) + +// InstrumentConfig contains options for metric instrument descriptors. +type InstrumentConfig struct { + // Description describes the instrument in human-readable terms. + Description string + // Unit describes the measurement unit for a instrument. + Unit unit.Unit + // InstrumentationName is the name of the library providing + // instrumentation. + InstrumentationName string + // InstrumentationVersion is the version of the library providing + // instrumentation. + InstrumentationVersion string +} + +// InstrumentOption is an interface for applying metric instrument options. +type InstrumentOption interface { + // ApplyMeter is used to set a InstrumentOption value of a + // InstrumentConfig. + ApplyInstrument(*InstrumentConfig) +} + +// NewInstrumentConfig creates a new InstrumentConfig +// and applies all the given options. +func NewInstrumentConfig(opts ...InstrumentOption) InstrumentConfig { + var config InstrumentConfig + for _, o := range opts { + o.ApplyInstrument(&config) + } + return config +} + +// WithDescription applies provided description. +func WithDescription(desc string) InstrumentOption { + return descriptionOption(desc) +} + +type descriptionOption string + +func (d descriptionOption) ApplyInstrument(config *InstrumentConfig) { + config.Description = string(d) +} + +// WithUnit applies provided unit. +func WithUnit(unit unit.Unit) InstrumentOption { + return unitOption(unit) +} + +type unitOption unit.Unit + +func (u unitOption) ApplyInstrument(config *InstrumentConfig) { + config.Unit = unit.Unit(u) +} + +// WithInstrumentationName sets the instrumentation name. +func WithInstrumentationName(name string) InstrumentOption { + return instrumentationNameOption(name) +} + +type instrumentationNameOption string + +func (i instrumentationNameOption) ApplyInstrument(config *InstrumentConfig) { + config.InstrumentationName = string(i) +} + +// MeterConfig contains options for Meters. +type MeterConfig struct { + // InstrumentationVersion is the version of the library providing + // instrumentation. + InstrumentationVersion string +} + +// MeterOption is an interface for applying Meter options. +type MeterOption interface { + // ApplyMeter is used to set a MeterOption value of a MeterConfig. + ApplyMeter(*MeterConfig) +} + +// NewMeterConfig creates a new MeterConfig and applies +// all the given options. +func NewMeterConfig(opts ...MeterOption) MeterConfig { + var config MeterConfig + for _, o := range opts { + o.ApplyMeter(&config) + } + return config +} + +// InstrumentationOption is an interface for applying instrumentation specific +// options. +type InstrumentationOption interface { + InstrumentOption + MeterOption +} + +// WithInstrumentationVersion sets the instrumentation version. +func WithInstrumentationVersion(version string) InstrumentationOption { + return instrumentationVersionOption(version) +} + +type instrumentationVersionOption string + +func (i instrumentationVersionOption) ApplyMeter(config *MeterConfig) { + config.InstrumentationVersion = string(i) +} + +func (i instrumentationVersionOption) ApplyInstrument(config *InstrumentConfig) { + config.InstrumentationVersion = string(i) +} diff --git a/instrumentkind_string.go b/metric/instrumentkind_string.go similarity index 98% rename from instrumentkind_string.go rename to metric/instrumentkind_string.go index e0bfc22d46b..2805e22500c 100644 --- a/instrumentkind_string.go +++ b/metric/instrumentkind_string.go @@ -1,6 +1,6 @@ // Code generated by "stringer -type=InstrumentKind"; DO NOT EDIT. -package otel +package metric import "strconv" diff --git a/metric.go b/metric/metric.go similarity index 92% rename from metric.go rename to metric/metric.go index b06ae8dbe05..0b988abba88 100644 --- a/metric.go +++ b/metric/metric.go @@ -12,12 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel // import "go.opentelemetry.io/otel" +package metric // import "go.opentelemetry.io/otel/metric" import ( "context" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/unit" ) @@ -63,7 +64,7 @@ func (m Meter) NewBatchObserver(callback BatchObserverFunc) BatchObserver { // duplicate registration). func (m Meter) NewInt64Counter(name string, options ...InstrumentOption) (Int64Counter, error) { return wrapInt64CounterInstrument( - m.newSync(name, CounterInstrumentKind, Int64NumberKind, options)) + m.newSync(name, CounterInstrumentKind, number.Int64Kind, options)) } // NewFloat64Counter creates a new floating point Counter with the @@ -72,7 +73,7 @@ func (m Meter) NewInt64Counter(name string, options ...InstrumentOption) (Int64C // duplicate registration). func (m Meter) NewFloat64Counter(name string, options ...InstrumentOption) (Float64Counter, error) { return wrapFloat64CounterInstrument( - m.newSync(name, CounterInstrumentKind, Float64NumberKind, options)) + m.newSync(name, CounterInstrumentKind, number.Float64Kind, options)) } // NewInt64UpDownCounter creates a new integer UpDownCounter instrument with the @@ -81,7 +82,7 @@ func (m Meter) NewFloat64Counter(name string, options ...InstrumentOption) (Floa // duplicate registration). func (m Meter) NewInt64UpDownCounter(name string, options ...InstrumentOption) (Int64UpDownCounter, error) { return wrapInt64UpDownCounterInstrument( - m.newSync(name, UpDownCounterInstrumentKind, Int64NumberKind, options)) + m.newSync(name, UpDownCounterInstrumentKind, number.Int64Kind, options)) } // NewFloat64UpDownCounter creates a new floating point UpDownCounter with the @@ -90,7 +91,7 @@ func (m Meter) NewInt64UpDownCounter(name string, options ...InstrumentOption) ( // duplicate registration). func (m Meter) NewFloat64UpDownCounter(name string, options ...InstrumentOption) (Float64UpDownCounter, error) { return wrapFloat64UpDownCounterInstrument( - m.newSync(name, UpDownCounterInstrumentKind, Float64NumberKind, options)) + m.newSync(name, UpDownCounterInstrumentKind, number.Float64Kind, options)) } // NewInt64ValueRecorder creates a new integer ValueRecorder instrument with the @@ -99,7 +100,7 @@ func (m Meter) NewFloat64UpDownCounter(name string, options ...InstrumentOption) // duplicate registration). func (m Meter) NewInt64ValueRecorder(name string, opts ...InstrumentOption) (Int64ValueRecorder, error) { return wrapInt64ValueRecorderInstrument( - m.newSync(name, ValueRecorderInstrumentKind, Int64NumberKind, opts)) + m.newSync(name, ValueRecorderInstrumentKind, number.Int64Kind, opts)) } // NewFloat64ValueRecorder creates a new floating point ValueRecorder with the @@ -108,7 +109,7 @@ func (m Meter) NewInt64ValueRecorder(name string, opts ...InstrumentOption) (Int // duplicate registration). func (m Meter) NewFloat64ValueRecorder(name string, opts ...InstrumentOption) (Float64ValueRecorder, error) { return wrapFloat64ValueRecorderInstrument( - m.newSync(name, ValueRecorderInstrumentKind, Float64NumberKind, opts)) + m.newSync(name, ValueRecorderInstrumentKind, number.Float64Kind, opts)) } // NewInt64ValueObserver creates a new integer ValueObserver instrument @@ -120,7 +121,7 @@ func (m Meter) NewInt64ValueObserver(name string, callback Int64ObserverFunc, op return wrapInt64ValueObserverInstrument(NoopAsync{}, nil) } return wrapInt64ValueObserverInstrument( - m.newAsync(name, ValueObserverInstrumentKind, Int64NumberKind, opts, + m.newAsync(name, ValueObserverInstrumentKind, number.Int64Kind, opts, newInt64AsyncRunner(callback))) } @@ -133,7 +134,7 @@ func (m Meter) NewFloat64ValueObserver(name string, callback Float64ObserverFunc return wrapFloat64ValueObserverInstrument(NoopAsync{}, nil) } return wrapFloat64ValueObserverInstrument( - m.newAsync(name, ValueObserverInstrumentKind, Float64NumberKind, opts, + m.newAsync(name, ValueObserverInstrumentKind, number.Float64Kind, opts, newFloat64AsyncRunner(callback))) } @@ -146,7 +147,7 @@ func (m Meter) NewInt64SumObserver(name string, callback Int64ObserverFunc, opts return wrapInt64SumObserverInstrument(NoopAsync{}, nil) } return wrapInt64SumObserverInstrument( - m.newAsync(name, SumObserverInstrumentKind, Int64NumberKind, opts, + m.newAsync(name, SumObserverInstrumentKind, number.Int64Kind, opts, newInt64AsyncRunner(callback))) } @@ -159,7 +160,7 @@ func (m Meter) NewFloat64SumObserver(name string, callback Float64ObserverFunc, return wrapFloat64SumObserverInstrument(NoopAsync{}, nil) } return wrapFloat64SumObserverInstrument( - m.newAsync(name, SumObserverInstrumentKind, Float64NumberKind, opts, + m.newAsync(name, SumObserverInstrumentKind, number.Float64Kind, opts, newFloat64AsyncRunner(callback))) } @@ -172,7 +173,7 @@ func (m Meter) NewInt64UpDownSumObserver(name string, callback Int64ObserverFunc return wrapInt64UpDownSumObserverInstrument(NoopAsync{}, nil) } return wrapInt64UpDownSumObserverInstrument( - m.newAsync(name, UpDownSumObserverInstrumentKind, Int64NumberKind, opts, + m.newAsync(name, UpDownSumObserverInstrumentKind, number.Int64Kind, opts, newInt64AsyncRunner(callback))) } @@ -185,7 +186,7 @@ func (m Meter) NewFloat64UpDownSumObserver(name string, callback Float64Observer return wrapFloat64UpDownSumObserverInstrument(NoopAsync{}, nil) } return wrapFloat64UpDownSumObserverInstrument( - m.newAsync(name, UpDownSumObserverInstrumentKind, Float64NumberKind, opts, + m.newAsync(name, UpDownSumObserverInstrumentKind, number.Float64Kind, opts, newFloat64AsyncRunner(callback))) } @@ -198,7 +199,7 @@ func (b BatchObserver) NewInt64ValueObserver(name string, opts ...InstrumentOpti return wrapInt64ValueObserverInstrument(NoopAsync{}, nil) } return wrapInt64ValueObserverInstrument( - b.meter.newAsync(name, ValueObserverInstrumentKind, Int64NumberKind, opts, b.runner)) + b.meter.newAsync(name, ValueObserverInstrumentKind, number.Int64Kind, opts, b.runner)) } // NewFloat64ValueObserver creates a new floating point ValueObserver with @@ -210,7 +211,7 @@ func (b BatchObserver) NewFloat64ValueObserver(name string, opts ...InstrumentOp return wrapFloat64ValueObserverInstrument(NoopAsync{}, nil) } return wrapFloat64ValueObserverInstrument( - b.meter.newAsync(name, ValueObserverInstrumentKind, Float64NumberKind, opts, + b.meter.newAsync(name, ValueObserverInstrumentKind, number.Float64Kind, opts, b.runner)) } @@ -223,7 +224,7 @@ func (b BatchObserver) NewInt64SumObserver(name string, opts ...InstrumentOption return wrapInt64SumObserverInstrument(NoopAsync{}, nil) } return wrapInt64SumObserverInstrument( - b.meter.newAsync(name, SumObserverInstrumentKind, Int64NumberKind, opts, b.runner)) + b.meter.newAsync(name, SumObserverInstrumentKind, number.Int64Kind, opts, b.runner)) } // NewFloat64SumObserver creates a new floating point SumObserver with @@ -235,7 +236,7 @@ func (b BatchObserver) NewFloat64SumObserver(name string, opts ...InstrumentOpti return wrapFloat64SumObserverInstrument(NoopAsync{}, nil) } return wrapFloat64SumObserverInstrument( - b.meter.newAsync(name, SumObserverInstrumentKind, Float64NumberKind, opts, + b.meter.newAsync(name, SumObserverInstrumentKind, number.Float64Kind, opts, b.runner)) } @@ -248,7 +249,7 @@ func (b BatchObserver) NewInt64UpDownSumObserver(name string, opts ...Instrument return wrapInt64UpDownSumObserverInstrument(NoopAsync{}, nil) } return wrapInt64UpDownSumObserverInstrument( - b.meter.newAsync(name, UpDownSumObserverInstrumentKind, Int64NumberKind, opts, b.runner)) + b.meter.newAsync(name, UpDownSumObserverInstrumentKind, number.Int64Kind, opts, b.runner)) } // NewFloat64UpDownSumObserver creates a new floating point UpDownSumObserver with @@ -260,7 +261,7 @@ func (b BatchObserver) NewFloat64UpDownSumObserver(name string, opts ...Instrume return wrapFloat64UpDownSumObserverInstrument(NoopAsync{}, nil) } return wrapFloat64UpDownSumObserverInstrument( - b.meter.newAsync(name, UpDownSumObserverInstrumentKind, Float64NumberKind, opts, + b.meter.newAsync(name, UpDownSumObserverInstrumentKind, number.Float64Kind, opts, b.runner)) } @@ -273,7 +274,7 @@ func (m Meter) MeterImpl() MeterImpl { func (m Meter) newAsync( name string, mkind InstrumentKind, - nkind NumberKind, + nkind number.Kind, opts []InstrumentOption, runner AsyncRunner, ) ( @@ -293,7 +294,7 @@ func (m Meter) newAsync( func (m Meter) newSync( name string, metricKind InstrumentKind, - numberKind NumberKind, + numberKind number.Kind, opts []InstrumentOption, ) ( SyncImpl, @@ -521,12 +522,12 @@ func (bm BatchObserverMust) NewFloat64UpDownSumObserver(name string, oos ...Inst type Descriptor struct { name string instrumentKind InstrumentKind - numberKind NumberKind + numberKind number.Kind config InstrumentConfig } // NewDescriptor returns a Descriptor with the given contents. -func NewDescriptor(name string, ikind InstrumentKind, nkind NumberKind, opts ...InstrumentOption) Descriptor { +func NewDescriptor(name string, ikind InstrumentKind, nkind number.Kind, opts ...InstrumentOption) Descriptor { return Descriptor{ name: name, instrumentKind: ikind, @@ -559,7 +560,7 @@ func (d Descriptor) Unit() unit.Unit { // NumberKind returns whether this instrument is declared over int64, // float64, or uint64 values. -func (d Descriptor) NumberKind() NumberKind { +func (d Descriptor) NumberKind() number.Kind { return d.numberKind } diff --git a/metric_instrument.go b/metric/metric_instrument.go similarity index 94% rename from metric_instrument.go rename to metric/metric_instrument.go index a9f75646f39..6e2f9ce9552 100644 --- a/metric_instrument.go +++ b/metric/metric_instrument.go @@ -14,13 +14,14 @@ //go:generate stringer -type=InstrumentKind -package otel // import "go.opentelemetry.io/otel" +package metric // import "go.opentelemetry.io/otel/metric" import ( "context" "errors" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric/number" ) // ErrSDKReturnedNilImpl is returned when a new `MeterImpl` returns nil. @@ -94,7 +95,7 @@ func (k InstrumentKind) PrecomputedSum() bool { // instruments (e.g., Int64ValueObserver.Observation()). type Observation struct { // number needs to be aligned for 64-bit atomic operations. - number Number + number number.Number instrument AsyncImpl } @@ -136,7 +137,7 @@ type BatchObserverResult struct { func (ir Int64ObserverResult) Observe(value int64, labels ...label.KeyValue) { ir.function(labels, Observation{ instrument: ir.instrument, - number: NewInt64Number(value), + number: number.NewInt64Number(value), }) } @@ -145,7 +146,7 @@ func (ir Int64ObserverResult) Observe(value int64, labels ...label.KeyValue) { func (fr Float64ObserverResult) Observe(value float64, labels ...label.KeyValue) { fr.function(labels, Observation{ instrument: fr.instrument, - number: NewFloat64Number(value), + number: number.NewFloat64Number(value), }) } @@ -323,7 +324,7 @@ type Float64UpDownSumObserver struct { // users should not refer to this. func (i Int64ValueObserver) Observation(v int64) Observation { return Observation{ - number: NewInt64Number(v), + number: number.NewInt64Number(v), instrument: i.instrument, } } @@ -334,7 +335,7 @@ func (i Int64ValueObserver) Observation(v int64) Observation { // users should not refer to this. func (f Float64ValueObserver) Observation(v float64) Observation { return Observation{ - number: NewFloat64Number(v), + number: number.NewFloat64Number(v), instrument: f.instrument, } } @@ -345,7 +346,7 @@ func (f Float64ValueObserver) Observation(v float64) Observation { // users should not refer to this. func (i Int64SumObserver) Observation(v int64) Observation { return Observation{ - number: NewInt64Number(v), + number: number.NewInt64Number(v), instrument: i.instrument, } } @@ -356,7 +357,7 @@ func (i Int64SumObserver) Observation(v int64) Observation { // users should not refer to this. func (f Float64SumObserver) Observation(v float64) Observation { return Observation{ - number: NewFloat64Number(v), + number: number.NewFloat64Number(v), instrument: f.instrument, } } @@ -367,7 +368,7 @@ func (f Float64SumObserver) Observation(v float64) Observation { // users should not refer to this. func (i Int64UpDownSumObserver) Observation(v int64) Observation { return Observation{ - number: NewInt64Number(v), + number: number.NewInt64Number(v), instrument: i.instrument, } } @@ -378,7 +379,7 @@ func (i Int64UpDownSumObserver) Observation(v int64) Observation { // users should not refer to this. func (f Float64UpDownSumObserver) Observation(v float64) Observation { return Observation{ - number: NewFloat64Number(v), + number: number.NewFloat64Number(v), instrument: f.instrument, } } @@ -388,7 +389,7 @@ func (f Float64UpDownSumObserver) Observation(v float64) Observation { // instruments (e.g., Int64Counter.Measurement()). type Measurement struct { // number needs to be aligned for 64-bit atomic operations. - number Number + number number.Number instrument SyncImpl } @@ -415,7 +416,7 @@ func (m Measurement) SyncImpl() SyncImpl { } // Number returns a number recorded in this measurement. -func (m Measurement) Number() Number { +func (m Measurement) Number() number.Number { return m.number } @@ -427,7 +428,7 @@ func (m Observation) AsyncImpl() AsyncImpl { } // Number returns a number recorded in this observation. -func (m Observation) Number() Number { +func (m Observation) Number() number.Number { return m.number } @@ -446,18 +447,18 @@ func (s syncInstrument) bind(labels []label.KeyValue) syncBoundInstrument { } func (s syncInstrument) float64Measurement(value float64) Measurement { - return newMeasurement(s.instrument, NewFloat64Number(value)) + return newMeasurement(s.instrument, number.NewFloat64Number(value)) } func (s syncInstrument) int64Measurement(value int64) Measurement { - return newMeasurement(s.instrument, NewInt64Number(value)) + return newMeasurement(s.instrument, number.NewInt64Number(value)) } -func (s syncInstrument) directRecord(ctx context.Context, number Number, labels []label.KeyValue) { +func (s syncInstrument) directRecord(ctx context.Context, number number.Number, labels []label.KeyValue) { s.instrument.RecordOne(ctx, number, labels) } -func (h syncBoundInstrument) directRecord(ctx context.Context, number Number) { +func (h syncBoundInstrument) directRecord(ctx context.Context, number number.Number) { h.boundInstrument.RecordOne(ctx, number) } @@ -507,7 +508,7 @@ func newSyncBoundInstrument(boundInstrument BoundSyncImpl) syncBoundInstrument { } } -func newMeasurement(instrument SyncImpl, number Number) Measurement { +func newMeasurement(instrument SyncImpl, number number.Number) Measurement { return Measurement{ instrument: instrument, number: number, @@ -603,25 +604,25 @@ func (c Int64Counter) Measurement(value int64) Measurement { // Add adds the value to the counter's sum. The labels should contain // the keys and values to be associated with this value. func (c Float64Counter) Add(ctx context.Context, value float64, labels ...label.KeyValue) { - c.directRecord(ctx, NewFloat64Number(value), labels) + c.directRecord(ctx, number.NewFloat64Number(value), labels) } // Add adds the value to the counter's sum. The labels should contain // the keys and values to be associated with this value. func (c Int64Counter) Add(ctx context.Context, value int64, labels ...label.KeyValue) { - c.directRecord(ctx, NewInt64Number(value), labels) + c.directRecord(ctx, number.NewInt64Number(value), labels) } // Add adds the value to the counter's sum using the labels // previously bound to this counter via Bind() func (b BoundFloat64Counter) Add(ctx context.Context, value float64) { - b.directRecord(ctx, NewFloat64Number(value)) + b.directRecord(ctx, number.NewFloat64Number(value)) } // Add adds the value to the counter's sum using the labels // previously bound to this counter via Bind() func (b BoundInt64Counter) Add(ctx context.Context, value int64) { - b.directRecord(ctx, NewInt64Number(value)) + b.directRecord(ctx, number.NewInt64Number(value)) } // Float64UpDownCounter is a metric instrument that sums floating @@ -678,25 +679,25 @@ func (c Int64UpDownCounter) Measurement(value int64) Measurement { // Add adds the value to the counter's sum. The labels should contain // the keys and values to be associated with this value. func (c Float64UpDownCounter) Add(ctx context.Context, value float64, labels ...label.KeyValue) { - c.directRecord(ctx, NewFloat64Number(value), labels) + c.directRecord(ctx, number.NewFloat64Number(value), labels) } // Add adds the value to the counter's sum. The labels should contain // the keys and values to be associated with this value. func (c Int64UpDownCounter) Add(ctx context.Context, value int64, labels ...label.KeyValue) { - c.directRecord(ctx, NewInt64Number(value), labels) + c.directRecord(ctx, number.NewInt64Number(value), labels) } // Add adds the value to the counter's sum using the labels // previously bound to this counter via Bind() func (b BoundFloat64UpDownCounter) Add(ctx context.Context, value float64) { - b.directRecord(ctx, NewFloat64Number(value)) + b.directRecord(ctx, number.NewFloat64Number(value)) } // Add adds the value to the counter's sum using the labels // previously bound to this counter via Bind() func (b BoundInt64UpDownCounter) Add(ctx context.Context, value int64) { - b.directRecord(ctx, NewInt64Number(value)) + b.directRecord(ctx, number.NewInt64Number(value)) } // Float64ValueRecorder is a metric that records float64 values. @@ -753,24 +754,24 @@ func (c Int64ValueRecorder) Measurement(value int64) Measurement { // labels should contain the keys and values to be associated with // this value. func (c Float64ValueRecorder) Record(ctx context.Context, value float64, labels ...label.KeyValue) { - c.directRecord(ctx, NewFloat64Number(value), labels) + c.directRecord(ctx, number.NewFloat64Number(value), labels) } // Record adds a new value to the ValueRecorder's distribution. The // labels should contain the keys and values to be associated with // this value. func (c Int64ValueRecorder) Record(ctx context.Context, value int64, labels ...label.KeyValue) { - c.directRecord(ctx, NewInt64Number(value), labels) + c.directRecord(ctx, number.NewInt64Number(value), labels) } // Record adds a new value to the ValueRecorder's distribution using the labels // previously bound to the ValueRecorder via Bind(). func (b BoundFloat64ValueRecorder) Record(ctx context.Context, value float64) { - b.directRecord(ctx, NewFloat64Number(value)) + b.directRecord(ctx, number.NewFloat64Number(value)) } // Record adds a new value to the ValueRecorder's distribution using the labels // previously bound to the ValueRecorder via Bind(). func (b BoundInt64ValueRecorder) Record(ctx context.Context, value int64) { - b.directRecord(ctx, NewInt64Number(value)) + b.directRecord(ctx, number.NewInt64Number(value)) } diff --git a/metric_noop.go b/metric/metric_noop.go similarity index 84% rename from metric_noop.go rename to metric/metric_noop.go index 03273a9cf29..5cf26fc249f 100644 --- a/metric_noop.go +++ b/metric/metric_noop.go @@ -12,12 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel // import "go.opentelemetry.io/otel" +package metric // import "go.opentelemetry.io/otel/metric" import ( "context" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric/number" ) type NoopMeterProvider struct{} @@ -44,7 +45,7 @@ func (noopInstrument) Descriptor() Descriptor { return Descriptor{} } -func (noopBoundInstrument) RecordOne(context.Context, Number) { +func (noopBoundInstrument) RecordOne(context.Context, number.Number) { } func (noopBoundInstrument) Unbind() { @@ -54,5 +55,5 @@ func (NoopSync) Bind([]label.KeyValue) BoundSyncImpl { return noopBoundInstrument{} } -func (NoopSync) RecordOne(context.Context, Number, []label.KeyValue) { +func (NoopSync) RecordOne(context.Context, number.Number, []label.KeyValue) { } diff --git a/metric_sdkapi.go b/metric/metric_sdkapi.go similarity index 92% rename from metric_sdkapi.go rename to metric/metric_sdkapi.go index 73375f30958..77d6adb173b 100644 --- a/metric_sdkapi.go +++ b/metric/metric_sdkapi.go @@ -12,12 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel // import "go.opentelemetry.io/otel" +package metric // import "go.opentelemetry.io/otel/metric" import ( "context" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric/number" ) // MeterImpl is the interface an SDK must implement to supply a Meter @@ -62,7 +63,7 @@ type SyncImpl interface { Bind(labels []label.KeyValue) BoundSyncImpl // RecordOne captures a single synchronous metric event. - RecordOne(ctx context.Context, number Number, labels []label.KeyValue) + RecordOne(ctx context.Context, number number.Number, labels []label.KeyValue) } // BoundSyncImpl is the implementation-level interface to a @@ -70,7 +71,7 @@ type SyncImpl interface { type BoundSyncImpl interface { // RecordOne captures a single synchronous metric event. - RecordOne(ctx context.Context, number Number) + RecordOne(ctx context.Context, number number.Number) // Unbind frees the resources associated with this bound instrument. It // does not affect the metric this bound instrument was created through. diff --git a/metric_test.go b/metric/metric_test.go similarity index 69% rename from metric_test.go rename to metric/metric_test.go index 3995a7b1bd1..3250f0e1588 100644 --- a/metric_test.go +++ b/metric/metric_test.go @@ -12,15 +12,16 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel_test +package metric_test import ( "context" "errors" "testing" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/oteltest" "go.opentelemetry.io/otel/unit" @@ -29,52 +30,52 @@ import ( "github.com/stretchr/testify/require" ) -var Must = otel.Must +var Must = metric.Must var ( - syncKinds = []otel.InstrumentKind{ - otel.ValueRecorderInstrumentKind, - otel.CounterInstrumentKind, - otel.UpDownCounterInstrumentKind, + syncKinds = []metric.InstrumentKind{ + metric.ValueRecorderInstrumentKind, + metric.CounterInstrumentKind, + metric.UpDownCounterInstrumentKind, } - asyncKinds = []otel.InstrumentKind{ - otel.ValueObserverInstrumentKind, - otel.SumObserverInstrumentKind, - otel.UpDownSumObserverInstrumentKind, + asyncKinds = []metric.InstrumentKind{ + metric.ValueObserverInstrumentKind, + metric.SumObserverInstrumentKind, + metric.UpDownSumObserverInstrumentKind, } - addingKinds = []otel.InstrumentKind{ - otel.CounterInstrumentKind, - otel.UpDownCounterInstrumentKind, - otel.SumObserverInstrumentKind, - otel.UpDownSumObserverInstrumentKind, + addingKinds = []metric.InstrumentKind{ + metric.CounterInstrumentKind, + metric.UpDownCounterInstrumentKind, + metric.SumObserverInstrumentKind, + metric.UpDownSumObserverInstrumentKind, } - groupingKinds = []otel.InstrumentKind{ - otel.ValueRecorderInstrumentKind, - otel.ValueObserverInstrumentKind, + groupingKinds = []metric.InstrumentKind{ + metric.ValueRecorderInstrumentKind, + metric.ValueObserverInstrumentKind, } - monotonicKinds = []otel.InstrumentKind{ - otel.CounterInstrumentKind, - otel.SumObserverInstrumentKind, + monotonicKinds = []metric.InstrumentKind{ + metric.CounterInstrumentKind, + metric.SumObserverInstrumentKind, } - nonMonotonicKinds = []otel.InstrumentKind{ - otel.UpDownCounterInstrumentKind, - otel.UpDownSumObserverInstrumentKind, - otel.ValueRecorderInstrumentKind, - otel.ValueObserverInstrumentKind, + nonMonotonicKinds = []metric.InstrumentKind{ + metric.UpDownCounterInstrumentKind, + metric.UpDownSumObserverInstrumentKind, + metric.ValueRecorderInstrumentKind, + metric.ValueObserverInstrumentKind, } - precomputedSumKinds = []otel.InstrumentKind{ - otel.SumObserverInstrumentKind, - otel.UpDownSumObserverInstrumentKind, + precomputedSumKinds = []metric.InstrumentKind{ + metric.SumObserverInstrumentKind, + metric.UpDownSumObserverInstrumentKind, } - nonPrecomputedSumKinds = []otel.InstrumentKind{ - otel.CounterInstrumentKind, - otel.UpDownCounterInstrumentKind, - otel.ValueRecorderInstrumentKind, - otel.ValueObserverInstrumentKind, + nonPrecomputedSumKinds = []metric.InstrumentKind{ + metric.CounterInstrumentKind, + metric.UpDownCounterInstrumentKind, + metric.ValueRecorderInstrumentKind, + metric.ValueObserverInstrumentKind, } ) @@ -118,7 +119,7 @@ func TestPrecomputedSum(t *testing.T) { } } -func checkSyncBatches(ctx context.Context, t *testing.T, labels []label.KeyValue, mock *oteltest.MeterImpl, nkind otel.NumberKind, mkind otel.InstrumentKind, instrument otel.InstrumentImpl, expected ...float64) { +func checkSyncBatches(ctx context.Context, t *testing.T, labels []label.KeyValue, mock *oteltest.MeterImpl, nkind number.Kind, mkind metric.InstrumentKind, instrument metric.InstrumentImpl, expected ...float64) { t.Helper() batchesCount := len(mock.MeasurementBatches) @@ -148,7 +149,7 @@ func checkSyncBatches(ctx context.Context, t *testing.T, labels []label.KeyValue func TestOptions(t *testing.T) { type testcase struct { name string - opts []otel.InstrumentOption + opts []metric.InstrumentOption desc string unit unit.Unit } @@ -161,34 +162,34 @@ func TestOptions(t *testing.T) { }, { name: "description", - opts: []otel.InstrumentOption{ - otel.WithDescription("stuff"), + opts: []metric.InstrumentOption{ + metric.WithDescription("stuff"), }, desc: "stuff", unit: "", }, { name: "description override", - opts: []otel.InstrumentOption{ - otel.WithDescription("stuff"), - otel.WithDescription("things"), + opts: []metric.InstrumentOption{ + metric.WithDescription("stuff"), + metric.WithDescription("things"), }, desc: "things", unit: "", }, { name: "unit", - opts: []otel.InstrumentOption{ - otel.WithUnit("s"), + opts: []metric.InstrumentOption{ + metric.WithUnit("s"), }, desc: "", unit: "s", }, { name: "unit override", - opts: []otel.InstrumentOption{ - otel.WithUnit("s"), - otel.WithUnit("h"), + opts: []metric.InstrumentOption{ + metric.WithUnit("s"), + metric.WithUnit("h"), }, desc: "", unit: "h", @@ -196,7 +197,7 @@ func TestOptions(t *testing.T) { } for idx, tt := range testcases { t.Logf("Testing counter case %s (%d)", tt.name, idx) - if diff := cmp.Diff(otel.NewInstrumentConfig(tt.opts...), otel.InstrumentConfig{ + if diff := cmp.Diff(metric.NewInstrumentConfig(tt.opts...), metric.InstrumentConfig{ Description: tt.desc, Unit: tt.unit, }); diff != "" { @@ -217,7 +218,7 @@ func TestCounter(t *testing.T) { boundInstrument := c.Bind(labels...) boundInstrument.Add(ctx, -742) meter.RecordBatch(ctx, labels, c.Measurement(42)) - checkSyncBatches(ctx, t, labels, mockSDK, otel.Float64NumberKind, otel.CounterInstrumentKind, c.SyncImpl(), + checkSyncBatches(ctx, t, labels, mockSDK, number.Float64Kind, metric.CounterInstrumentKind, c.SyncImpl(), 1994.1, -742, 42, ) }) @@ -230,7 +231,7 @@ func TestCounter(t *testing.T) { boundInstrument := c.Bind(labels...) boundInstrument.Add(ctx, 4200) meter.RecordBatch(ctx, labels, c.Measurement(420000)) - checkSyncBatches(ctx, t, labels, mockSDK, otel.Int64NumberKind, otel.CounterInstrumentKind, c.SyncImpl(), + checkSyncBatches(ctx, t, labels, mockSDK, number.Int64Kind, metric.CounterInstrumentKind, c.SyncImpl(), 42, 4200, 420000, ) @@ -244,7 +245,7 @@ func TestCounter(t *testing.T) { boundInstrument := c.Bind(labels...) boundInstrument.Add(ctx, -100) meter.RecordBatch(ctx, labels, c.Measurement(42)) - checkSyncBatches(ctx, t, labels, mockSDK, otel.Int64NumberKind, otel.UpDownCounterInstrumentKind, c.SyncImpl(), + checkSyncBatches(ctx, t, labels, mockSDK, number.Int64Kind, metric.UpDownCounterInstrumentKind, c.SyncImpl(), 100, -100, 42, ) }) @@ -257,7 +258,7 @@ func TestCounter(t *testing.T) { boundInstrument := c.Bind(labels...) boundInstrument.Add(ctx, -76) meter.RecordBatch(ctx, labels, c.Measurement(-100.1)) - checkSyncBatches(ctx, t, labels, mockSDK, otel.Float64NumberKind, otel.UpDownCounterInstrumentKind, c.SyncImpl(), + checkSyncBatches(ctx, t, labels, mockSDK, number.Float64Kind, metric.UpDownCounterInstrumentKind, c.SyncImpl(), 100.1, -76, -100.1, ) }) @@ -273,7 +274,7 @@ func TestValueRecorder(t *testing.T) { boundInstrument := m.Bind(labels...) boundInstrument.Record(ctx, 0) meter.RecordBatch(ctx, labels, m.Measurement(-100.5)) - checkSyncBatches(ctx, t, labels, mockSDK, otel.Float64NumberKind, otel.ValueRecorderInstrumentKind, m.SyncImpl(), + checkSyncBatches(ctx, t, labels, mockSDK, number.Float64Kind, metric.ValueRecorderInstrumentKind, m.SyncImpl(), 42, 0, -100.5, ) }) @@ -286,7 +287,7 @@ func TestValueRecorder(t *testing.T) { boundInstrument := m.Bind(labels...) boundInstrument.Record(ctx, 80) meter.RecordBatch(ctx, labels, m.Measurement(0)) - checkSyncBatches(ctx, t, labels, mockSDK, otel.Int64NumberKind, otel.ValueRecorderInstrumentKind, m.SyncImpl(), + checkSyncBatches(ctx, t, labels, mockSDK, number.Int64Kind, metric.ValueRecorderInstrumentKind, m.SyncImpl(), 173, 80, 0, ) }) @@ -296,66 +297,66 @@ func TestObserverInstruments(t *testing.T) { t.Run("float valueobserver", func(t *testing.T) { labels := []label.KeyValue{label.String("O", "P")} mockSDK, meter := oteltest.NewMeter() - o := Must(meter).NewFloat64ValueObserver("test.valueobserver.float", func(_ context.Context, result otel.Float64ObserverResult) { + o := Must(meter).NewFloat64ValueObserver("test.valueobserver.float", func(_ context.Context, result metric.Float64ObserverResult) { result.Observe(42.1, labels...) }) mockSDK.RunAsyncInstruments() - checkObserverBatch(t, labels, mockSDK, otel.Float64NumberKind, otel.ValueObserverInstrumentKind, o.AsyncImpl(), + checkObserverBatch(t, labels, mockSDK, number.Float64Kind, metric.ValueObserverInstrumentKind, o.AsyncImpl(), 42.1, ) }) t.Run("int valueobserver", func(t *testing.T) { labels := []label.KeyValue{} mockSDK, meter := oteltest.NewMeter() - o := Must(meter).NewInt64ValueObserver("test.observer.int", func(_ context.Context, result otel.Int64ObserverResult) { + o := Must(meter).NewInt64ValueObserver("test.observer.int", func(_ context.Context, result metric.Int64ObserverResult) { result.Observe(-142, labels...) }) mockSDK.RunAsyncInstruments() - checkObserverBatch(t, labels, mockSDK, otel.Int64NumberKind, otel.ValueObserverInstrumentKind, o.AsyncImpl(), + checkObserverBatch(t, labels, mockSDK, number.Int64Kind, metric.ValueObserverInstrumentKind, o.AsyncImpl(), -142, ) }) t.Run("float sumobserver", func(t *testing.T) { labels := []label.KeyValue{label.String("O", "P")} mockSDK, meter := oteltest.NewMeter() - o := Must(meter).NewFloat64SumObserver("test.sumobserver.float", func(_ context.Context, result otel.Float64ObserverResult) { + o := Must(meter).NewFloat64SumObserver("test.sumobserver.float", func(_ context.Context, result metric.Float64ObserverResult) { result.Observe(42.1, labels...) }) mockSDK.RunAsyncInstruments() - checkObserverBatch(t, labels, mockSDK, otel.Float64NumberKind, otel.SumObserverInstrumentKind, o.AsyncImpl(), + checkObserverBatch(t, labels, mockSDK, number.Float64Kind, metric.SumObserverInstrumentKind, o.AsyncImpl(), 42.1, ) }) t.Run("int sumobserver", func(t *testing.T) { labels := []label.KeyValue{} mockSDK, meter := oteltest.NewMeter() - o := Must(meter).NewInt64SumObserver("test.observer.int", func(_ context.Context, result otel.Int64ObserverResult) { + o := Must(meter).NewInt64SumObserver("test.observer.int", func(_ context.Context, result metric.Int64ObserverResult) { result.Observe(-142, labels...) }) mockSDK.RunAsyncInstruments() - checkObserverBatch(t, labels, mockSDK, otel.Int64NumberKind, otel.SumObserverInstrumentKind, o.AsyncImpl(), + checkObserverBatch(t, labels, mockSDK, number.Int64Kind, metric.SumObserverInstrumentKind, o.AsyncImpl(), -142, ) }) t.Run("float updownsumobserver", func(t *testing.T) { labels := []label.KeyValue{label.String("O", "P")} mockSDK, meter := oteltest.NewMeter() - o := Must(meter).NewFloat64UpDownSumObserver("test.updownsumobserver.float", func(_ context.Context, result otel.Float64ObserverResult) { + o := Must(meter).NewFloat64UpDownSumObserver("test.updownsumobserver.float", func(_ context.Context, result metric.Float64ObserverResult) { result.Observe(42.1, labels...) }) mockSDK.RunAsyncInstruments() - checkObserverBatch(t, labels, mockSDK, otel.Float64NumberKind, otel.UpDownSumObserverInstrumentKind, o.AsyncImpl(), + checkObserverBatch(t, labels, mockSDK, number.Float64Kind, metric.UpDownSumObserverInstrumentKind, o.AsyncImpl(), 42.1, ) }) t.Run("int updownsumobserver", func(t *testing.T) { labels := []label.KeyValue{} mockSDK, meter := oteltest.NewMeter() - o := Must(meter).NewInt64UpDownSumObserver("test.observer.int", func(_ context.Context, result otel.Int64ObserverResult) { + o := Must(meter).NewInt64UpDownSumObserver("test.observer.int", func(_ context.Context, result metric.Int64ObserverResult) { result.Observe(-142, labels...) }) mockSDK.RunAsyncInstruments() - checkObserverBatch(t, labels, mockSDK, otel.Int64NumberKind, otel.UpDownSumObserverInstrumentKind, o.AsyncImpl(), + checkObserverBatch(t, labels, mockSDK, number.Int64Kind, metric.UpDownSumObserverInstrumentKind, o.AsyncImpl(), -142, ) }) @@ -364,8 +365,8 @@ func TestObserverInstruments(t *testing.T) { func TestBatchObserverInstruments(t *testing.T) { mockSDK, meter := oteltest.NewMeter() - var obs1 otel.Int64ValueObserver - var obs2 otel.Float64ValueObserver + var obs1 metric.Int64ValueObserver + var obs2 metric.Float64ValueObserver labels := []label.KeyValue{ label.String("A", "B"), @@ -373,7 +374,7 @@ func TestBatchObserverInstruments(t *testing.T) { } cb := Must(meter).NewBatchObserver( - func(_ context.Context, result otel.BatchObserverResult) { + func(_ context.Context, result metric.BatchObserverResult) { result.Observe(labels, obs1.Observation(42), obs2.Observation(42.0), @@ -399,14 +400,14 @@ func TestBatchObserverInstruments(t *testing.T) { m1 := got.Measurements[0] require.Equal(t, impl1, m1.Instrument.Implementation().(*oteltest.Async)) - require.Equal(t, 0, m1.Number.CompareNumber(otel.Int64NumberKind, oteltest.ResolveNumberByKind(t, otel.Int64NumberKind, 42))) + require.Equal(t, 0, m1.Number.CompareNumber(number.Int64Kind, oteltest.ResolveNumberByKind(t, number.Int64Kind, 42))) m2 := got.Measurements[1] require.Equal(t, impl2, m2.Instrument.Implementation().(*oteltest.Async)) - require.Equal(t, 0, m2.Number.CompareNumber(otel.Float64NumberKind, oteltest.ResolveNumberByKind(t, otel.Float64NumberKind, 42))) + require.Equal(t, 0, m2.Number.CompareNumber(number.Float64Kind, oteltest.ResolveNumberByKind(t, number.Float64Kind, 42))) } -func checkObserverBatch(t *testing.T, labels []label.KeyValue, mock *oteltest.MeterImpl, nkind otel.NumberKind, mkind otel.InstrumentKind, observer otel.AsyncImpl, expected float64) { +func checkObserverBatch(t *testing.T, labels []label.KeyValue, mock *oteltest.MeterImpl, nkind number.Kind, mkind metric.InstrumentKind, observer metric.AsyncImpl, expected float64) { t.Helper() assert.Len(t, mock.MeasurementBatches, 1) if len(mock.MeasurementBatches) < 1 { @@ -432,29 +433,29 @@ func checkObserverBatch(t *testing.T, labels []label.KeyValue, mock *oteltest.Me type testWrappedMeter struct { } -var _ otel.MeterImpl = testWrappedMeter{} +var _ metric.MeterImpl = testWrappedMeter{} -func (testWrappedMeter) RecordBatch(context.Context, []label.KeyValue, ...otel.Measurement) { +func (testWrappedMeter) RecordBatch(context.Context, []label.KeyValue, ...metric.Measurement) { } -func (testWrappedMeter) NewSyncInstrument(_ otel.Descriptor) (otel.SyncImpl, error) { +func (testWrappedMeter) NewSyncInstrument(_ metric.Descriptor) (metric.SyncImpl, error) { return nil, nil } -func (testWrappedMeter) NewAsyncInstrument(_ otel.Descriptor, _ otel.AsyncRunner) (otel.AsyncImpl, error) { +func (testWrappedMeter) NewAsyncInstrument(_ metric.Descriptor, _ metric.AsyncRunner) (metric.AsyncImpl, error) { return nil, errors.New("Test wrap error") } func TestWrappedInstrumentError(t *testing.T) { impl := &testWrappedMeter{} - meter := otel.WrapMeterImpl(impl, "test") + meter := metric.WrapMeterImpl(impl, "test") valuerecorder, err := meter.NewInt64ValueRecorder("test.valuerecorder") - require.Equal(t, err, otel.ErrSDKReturnedNilImpl) + require.Equal(t, err, metric.ErrSDKReturnedNilImpl) require.NotNil(t, valuerecorder.SyncImpl()) - observer, err := meter.NewInt64ValueObserver("test.observer", func(_ context.Context, result otel.Int64ObserverResult) {}) + observer, err := meter.NewInt64ValueObserver("test.observer", func(_ context.Context, result metric.Int64ObserverResult) {}) require.NotNil(t, err) require.NotNil(t, observer.AsyncImpl()) @@ -466,6 +467,6 @@ func TestNilCallbackObserverNoop(t *testing.T) { observer := Must(meter).NewInt64ValueObserver("test.observer", nil) - _, ok := observer.AsyncImpl().(otel.NoopAsync) + _, ok := observer.AsyncImpl().(metric.NoopAsync) require.True(t, ok) } diff --git a/metric/number/kind_string.go b/metric/number/kind_string.go new file mode 100644 index 00000000000..6288c7ea295 --- /dev/null +++ b/metric/number/kind_string.go @@ -0,0 +1,24 @@ +// Code generated by "stringer -type=Kind"; DO NOT EDIT. + +package number + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[Int64Kind-0] + _ = x[Float64Kind-1] +} + +const _Kind_name = "Int64KindFloat64Kind" + +var _Kind_index = [...]uint8{0, 9, 20} + +func (i Kind) String() string { + if i < 0 || i >= Kind(len(_Kind_index)-1) { + return "Kind(" + strconv.FormatInt(int64(i), 10) + ")" + } + return _Kind_name[_Kind_index[i]:_Kind_index[i+1]] +} diff --git a/number.go b/metric/number/number.go similarity index 85% rename from number.go rename to metric/number/number.go index 411bfcf7237..3ec95e2014d 100644 --- a/number.go +++ b/metric/number/number.go @@ -12,9 +12,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel // import "go.opentelemetry.io/otel" +package number // import "go.opentelemetry.io/otel/metric/number" -//go:generate stringer -type=NumberKind +//go:generate stringer -type=Kind import ( "fmt" @@ -24,22 +24,22 @@ import ( "go.opentelemetry.io/otel/internal" ) -// NumberKind describes the data type of the Number. -type NumberKind int8 +// Kind describes the data type of the Number. +type Kind int8 const ( - // Int64NumberKind means that the Number stores int64. - Int64NumberKind NumberKind = iota - // Float64NumberKind means that the Number stores float64. - Float64NumberKind + // Int64Kind means that the Number stores int64. + Int64Kind Kind = iota + // Float64Kind means that the Number stores float64. + Float64Kind ) -// Zero returns a zero value for a given NumberKind -func (k NumberKind) Zero() Number { +// Zero returns a zero value for a given Kind +func (k Kind) Zero() Number { switch k { - case Int64NumberKind: + case Int64Kind: return NewInt64Number(0) - case Float64NumberKind: + case Float64Kind: return NewFloat64Number(0.) default: return Number(0) @@ -47,12 +47,12 @@ func (k NumberKind) Zero() Number { } // Minimum returns the minimum representable value -// for a given NumberKind -func (k NumberKind) Minimum() Number { +// for a given Kind +func (k Kind) Minimum() Number { switch k { - case Int64NumberKind: + case Int64Kind: return NewInt64Number(math.MinInt64) - case Float64NumberKind: + case Float64Kind: return NewFloat64Number(-1. * math.MaxFloat64) default: return Number(0) @@ -60,12 +60,12 @@ func (k NumberKind) Minimum() Number { } // Maximum returns the maximum representable value -// for a given NumberKind -func (k NumberKind) Maximum() Number { +// for a given Kind +func (k Kind) Maximum() Number { switch k { - case Int64NumberKind: + case Int64Kind: return NewInt64Number(math.MaxInt64) - case Float64NumberKind: + case Float64Kind: return NewFloat64Number(math.MaxFloat64) default: return Number(0) @@ -73,7 +73,7 @@ func (k NumberKind) Maximum() Number { } // Number represents either an integral or a floating point value. It -// needs to be accompanied with a source of NumberKind that describes +// needs to be accompanied with a source of Kind that describes // the actual type of the value stored within Number. type Number uint64 @@ -96,13 +96,11 @@ func NewFloat64Number(f float64) Number { // NewNumberSignChange returns a number with the same magnitude and // the opposite sign. `kind` must describe the kind of number in `nn`. -// -// Does not change Uint64NumberKind values. -func NewNumberSignChange(kind NumberKind, nn Number) Number { +func NewNumberSignChange(kind Kind, nn Number) Number { switch kind { - case Int64NumberKind: + case Int64Kind: return NewInt64Number(-nn.AsInt64()) - case Float64NumberKind: + case Float64Kind: return NewFloat64Number(-nn.AsFloat64()) } return nn @@ -182,11 +180,11 @@ func (n *Number) AsFloat64Ptr() *float64 { // CoerceToInt64 casts the number to int64. May result in // data/precision loss. -func (n *Number) CoerceToInt64(kind NumberKind) int64 { +func (n *Number) CoerceToInt64(kind Kind) int64 { switch kind { - case Int64NumberKind: + case Int64Kind: return n.AsInt64() - case Float64NumberKind: + case Float64Kind: return int64(n.AsFloat64()) default: // you get what you deserve @@ -196,11 +194,11 @@ func (n *Number) CoerceToInt64(kind NumberKind) int64 { // CoerceToFloat64 casts the number to float64. May result in // data/precision loss. -func (n *Number) CoerceToFloat64(kind NumberKind) float64 { +func (n *Number) CoerceToFloat64(kind Kind) float64 { switch kind { - case Int64NumberKind: + case Int64Kind: return float64(n.AsInt64()) - case Float64NumberKind: + case Float64Kind: return n.AsFloat64() default: // you get what you deserve @@ -330,18 +328,18 @@ func (n *Number) SwapFloat64Atomic(f float64) float64 { // AddNumber assumes that this and the passed number are of the passed // kind and adds the passed number to this number. -func (n *Number) AddNumber(kind NumberKind, nn Number) { +func (n *Number) AddNumber(kind Kind, nn Number) { switch kind { - case Int64NumberKind: + case Int64Kind: n.AddInt64(nn.AsInt64()) - case Float64NumberKind: + case Float64Kind: n.AddFloat64(nn.AsFloat64()) } } // AddRaw assumes that this number and the passed raw value are of the // passed kind and adds the passed raw value to this number. -func (n *Number) AddRaw(kind NumberKind, r uint64) { +func (n *Number) AddRaw(kind Kind, r uint64) { n.AddNumber(kind, NewNumberFromRaw(r)) } @@ -361,11 +359,11 @@ func (n *Number) AddFloat64(f float64) { // AddNumberAtomic assumes that this and the passed number are of the // passed kind and adds the passed number to this number atomically. -func (n *Number) AddNumberAtomic(kind NumberKind, nn Number) { +func (n *Number) AddNumberAtomic(kind Kind, nn Number) { switch kind { - case Int64NumberKind: + case Int64Kind: n.AddInt64Atomic(nn.AsInt64()) - case Float64NumberKind: + case Float64Kind: n.AddFloat64Atomic(nn.AsFloat64()) } } @@ -373,7 +371,7 @@ func (n *Number) AddNumberAtomic(kind NumberKind, nn Number) { // AddRawAtomic assumes that this number and the passed raw value are // of the passed kind and adds the passed raw value to this number // atomically. -func (n *Number) AddRawAtomic(kind NumberKind, r uint64) { +func (n *Number) AddRawAtomic(kind Kind, r uint64) { n.AddNumberAtomic(kind, NewNumberFromRaw(r)) } @@ -429,11 +427,11 @@ func (n *Number) CompareAndSwapFloat64(of, nf float64) bool { // 0 if the numbers are equal // -1 if the subject `n` is less than the argument `nn` // +1 if the subject `n` is greater than the argument `nn` -func (n *Number) CompareNumber(kind NumberKind, nn Number) int { +func (n *Number) CompareNumber(kind Kind, nn Number) int { switch kind { - case Int64NumberKind: + case Int64Kind: return n.CompareInt64(nn.AsInt64()) - case Float64NumberKind: + case Float64Kind: return n.CompareFloat64(nn.AsFloat64()) default: // you get what you deserve @@ -443,7 +441,7 @@ func (n *Number) CompareNumber(kind NumberKind, nn Number) int { // CompareRaw compares two numbers, where one is input as a raw // uint64, interpreting both values as a `kind` of number. -func (n *Number) CompareRaw(kind NumberKind, r uint64) int { +func (n *Number) CompareRaw(kind Kind, r uint64) int { return n.CompareNumber(kind, NewNumberFromRaw(r)) } @@ -482,17 +480,17 @@ func (n *Number) CompareFloat64(f float64) int { // - relations to zero // IsPositive returns true if the actual value is greater than zero. -func (n *Number) IsPositive(kind NumberKind) bool { +func (n *Number) IsPositive(kind Kind) bool { return n.compareWithZero(kind) > 0 } // IsNegative returns true if the actual value is less than zero. -func (n *Number) IsNegative(kind NumberKind) bool { +func (n *Number) IsNegative(kind Kind) bool { return n.compareWithZero(kind) < 0 } // IsZero returns true if the actual value is equal to zero. -func (n *Number) IsZero(kind NumberKind) bool { +func (n *Number) IsZero(kind Kind) bool { return n.compareWithZero(kind) == 0 } @@ -501,11 +499,11 @@ func (n *Number) IsZero(kind NumberKind) bool { // Emit returns a string representation of the raw value of the // Number. A %d is used for integral values, %f for floating point // values. -func (n *Number) Emit(kind NumberKind) string { +func (n *Number) Emit(kind Kind) string { switch kind { - case Int64NumberKind: + case Int64Kind: return fmt.Sprintf("%d", n.AsInt64()) - case Float64NumberKind: + case Float64Kind: return fmt.Sprintf("%f", n.AsFloat64()) default: return "" @@ -513,12 +511,12 @@ func (n *Number) Emit(kind NumberKind) string { } // AsInterface returns the number as an interface{}, typically used -// for NumberKind-correct JSON conversion. -func (n *Number) AsInterface(kind NumberKind) interface{} { +// for Kind-correct JSON conversion. +func (n *Number) AsInterface(kind Kind) interface{} { switch kind { - case Int64NumberKind: + case Int64Kind: return n.AsInt64() - case Float64NumberKind: + case Float64Kind: return n.AsFloat64() default: return math.NaN() @@ -527,11 +525,11 @@ func (n *Number) AsInterface(kind NumberKind) interface{} { // - private stuff -func (n *Number) compareWithZero(kind NumberKind) int { +func (n *Number) compareWithZero(kind Kind) int { switch kind { - case Int64NumberKind: + case Int64Kind: return n.CompareInt64(0) - case Float64NumberKind: + case Float64Kind: return n.CompareFloat64(0.) default: // you get what you deserve diff --git a/number_test.go b/metric/number/number_test.go similarity index 79% rename from number_test.go rename to metric/number/number_test.go index 6c11e95a5f6..e8d675c7fc3 100644 --- a/number_test.go +++ b/metric/number/number_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel +package number import ( "math" @@ -31,7 +31,7 @@ func TestNumber(t *testing.T) { for idx, i := range []int64{-42, 0, 42} { n := i64Numbers[idx] if got := n.AsInt64(); got != i { - t.Errorf("Number %#v (%s) int64 check failed, expected %d, got %d", n, n.Emit(Int64NumberKind), i, got) + t.Errorf("Number %#v (%s) int64 check failed, expected %d, got %d", n, n.Emit(Int64Kind), i, got) } } @@ -51,7 +51,7 @@ func TestNumber(t *testing.T) { for idx, f := range []float64{-42., 0., 42.} { n := f64Numbers[idx] if got := n.AsFloat64(); got != f { - t.Errorf("Number %#v (%s) float64 check failed, expected %f, got %f", n, n.Emit(Int64NumberKind), f, got) + t.Errorf("Number %#v (%s) float64 check failed, expected %f, got %f", n, n.Emit(Int64Kind), f, got) } } @@ -72,7 +72,7 @@ func TestNumber(t *testing.T) { n Number // nums needs to be aligned for 64-bit atomic operations. nums [3]Number - kind NumberKind + kind Kind pos bool zero bool neg bool @@ -81,7 +81,7 @@ func TestNumber(t *testing.T) { testcases := []testcase{ { n: iNeg, - kind: Int64NumberKind, + kind: Int64Kind, pos: false, zero: false, neg: true, @@ -90,7 +90,7 @@ func TestNumber(t *testing.T) { }, { n: iZero, - kind: Int64NumberKind, + kind: Int64Kind, pos: false, zero: true, neg: false, @@ -99,7 +99,7 @@ func TestNumber(t *testing.T) { }, { n: iPos, - kind: Int64NumberKind, + kind: Int64Kind, pos: true, zero: false, neg: false, @@ -108,7 +108,7 @@ func TestNumber(t *testing.T) { }, { n: fNeg, - kind: Float64NumberKind, + kind: Float64Kind, pos: false, zero: false, neg: true, @@ -117,7 +117,7 @@ func TestNumber(t *testing.T) { }, { n: fZero, - kind: Float64NumberKind, + kind: Float64Kind, pos: false, zero: true, neg: false, @@ -126,7 +126,7 @@ func TestNumber(t *testing.T) { }, { n: fPos, - kind: Float64NumberKind, + kind: Float64Kind, pos: true, zero: false, neg: false, @@ -165,8 +165,8 @@ func TestNumberZero(t *testing.T) { func TestNumberAsInterface(t *testing.T) { i64 := NewInt64Number(10) f64 := NewFloat64Number(11.11) - require.Equal(t, int64(10), (&i64).AsInterface(Int64NumberKind).(int64)) - require.Equal(t, 11.11, (&f64).AsInterface(Float64NumberKind).(float64)) + require.Equal(t, int64(10), (&i64).AsInterface(Int64Kind).(int64)) + require.Equal(t, 11.11, (&f64).AsInterface(Float64Kind).(float64)) } func TestNumberSignChange(t *testing.T) { @@ -174,39 +174,39 @@ func TestNumberSignChange(t *testing.T) { posInt := NewInt64Number(10) negInt := NewInt64Number(-10) - require.Equal(t, posInt, NewNumberSignChange(Int64NumberKind, negInt)) - require.Equal(t, negInt, NewNumberSignChange(Int64NumberKind, posInt)) + require.Equal(t, posInt, NewNumberSignChange(Int64Kind, negInt)) + require.Equal(t, negInt, NewNumberSignChange(Int64Kind, posInt)) }) t.Run("Float64", func(t *testing.T) { posFloat := NewFloat64Number(10) negFloat := NewFloat64Number(-10) - require.Equal(t, posFloat, NewNumberSignChange(Float64NumberKind, negFloat)) - require.Equal(t, negFloat, NewNumberSignChange(Float64NumberKind, posFloat)) + require.Equal(t, posFloat, NewNumberSignChange(Float64Kind, negFloat)) + require.Equal(t, negFloat, NewNumberSignChange(Float64Kind, posFloat)) }) t.Run("Float64Zero", func(t *testing.T) { posFloat := NewFloat64Number(0) negFloat := NewFloat64Number(math.Copysign(0, -1)) - require.Equal(t, posFloat, NewNumberSignChange(Float64NumberKind, negFloat)) - require.Equal(t, negFloat, NewNumberSignChange(Float64NumberKind, posFloat)) + require.Equal(t, posFloat, NewNumberSignChange(Float64Kind, negFloat)) + require.Equal(t, negFloat, NewNumberSignChange(Float64Kind, posFloat)) }) t.Run("Float64Inf", func(t *testing.T) { posFloat := NewFloat64Number(math.Inf(+1)) negFloat := NewFloat64Number(math.Inf(-1)) - require.Equal(t, posFloat, NewNumberSignChange(Float64NumberKind, negFloat)) - require.Equal(t, negFloat, NewNumberSignChange(Float64NumberKind, posFloat)) + require.Equal(t, posFloat, NewNumberSignChange(Float64Kind, negFloat)) + require.Equal(t, negFloat, NewNumberSignChange(Float64Kind, posFloat)) }) t.Run("Float64NaN", func(t *testing.T) { posFloat := NewFloat64Number(math.NaN()) negFloat := NewFloat64Number(math.Copysign(math.NaN(), -1)) - require.Equal(t, posFloat, NewNumberSignChange(Float64NumberKind, negFloat)) - require.Equal(t, negFloat, NewNumberSignChange(Float64NumberKind, posFloat)) + require.Equal(t, posFloat, NewNumberSignChange(Float64Kind, negFloat)) + require.Equal(t, negFloat, NewNumberSignChange(Float64Kind, posFloat)) }) } diff --git a/registry/registry.go b/metric/registry/registry.go similarity index 71% rename from registry/registry.go rename to metric/registry/registry.go index 3e845e70254..f1d9819c319 100644 --- a/registry/registry.go +++ b/metric/registry/registry.go @@ -12,34 +12,34 @@ // See the License for the specific language governing permissions and // limitations under the License. -package registry // import "go.opentelemetry.io/otel/registry" +package registry // import "go.opentelemetry.io/otel/metric/registry" import ( "context" "fmt" "sync" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" ) // MeterProvider is a standard MeterProvider for wrapping `MeterImpl` type MeterProvider struct { - impl otel.MeterImpl + impl metric.MeterImpl } -var _ otel.MeterProvider = (*MeterProvider)(nil) +var _ metric.MeterProvider = (*MeterProvider)(nil) -// uniqueInstrumentMeterImpl implements the otel.MeterImpl interface, adding +// uniqueInstrumentMeterImpl implements the metric.MeterImpl interface, adding // uniqueness checking for instrument descriptors. Use NewUniqueInstrumentMeter // to wrap an implementation with uniqueness checking. type uniqueInstrumentMeterImpl struct { lock sync.Mutex - impl otel.MeterImpl - state map[key]otel.InstrumentImpl + impl metric.MeterImpl + state map[key]metric.InstrumentImpl } -var _ otel.MeterImpl = (*uniqueInstrumentMeterImpl)(nil) +var _ metric.MeterImpl = (*uniqueInstrumentMeterImpl)(nil) type key struct { instrumentName string @@ -49,15 +49,15 @@ type key struct { // NewMeterProvider returns a new provider that implements instrument // name-uniqueness checking. -func NewMeterProvider(impl otel.MeterImpl) *MeterProvider { +func NewMeterProvider(impl metric.MeterImpl) *MeterProvider { return &MeterProvider{ impl: NewUniqueInstrumentMeterImpl(impl), } } // Meter implements MeterProvider. -func (p *MeterProvider) Meter(instrumentationName string, opts ...otel.MeterOption) otel.Meter { - return otel.WrapMeterImpl(p.impl, instrumentationName, opts...) +func (p *MeterProvider) Meter(instrumentationName string, opts ...metric.MeterOption) metric.Meter { + return metric.WrapMeterImpl(p.impl, instrumentationName, opts...) } // ErrMetricKindMismatch is the standard error for mismatched metric @@ -65,21 +65,21 @@ func (p *MeterProvider) Meter(instrumentationName string, opts ...otel.MeterOpti var ErrMetricKindMismatch = fmt.Errorf( "A metric was already registered by this name with another kind or number type") -// NewUniqueInstrumentMeterImpl returns a wrapped otel.MeterImpl with +// NewUniqueInstrumentMeterImpl returns a wrapped metric.MeterImpl with // the addition of uniqueness checking. -func NewUniqueInstrumentMeterImpl(impl otel.MeterImpl) otel.MeterImpl { +func NewUniqueInstrumentMeterImpl(impl metric.MeterImpl) metric.MeterImpl { return &uniqueInstrumentMeterImpl{ impl: impl, - state: map[key]otel.InstrumentImpl{}, + state: map[key]metric.InstrumentImpl{}, } } -// RecordBatch implements otel.MeterImpl. -func (u *uniqueInstrumentMeterImpl) RecordBatch(ctx context.Context, labels []label.KeyValue, ms ...otel.Measurement) { +// RecordBatch implements metric.MeterImpl. +func (u *uniqueInstrumentMeterImpl) RecordBatch(ctx context.Context, labels []label.KeyValue, ms ...metric.Measurement) { u.impl.RecordBatch(ctx, labels, ms...) } -func keyOf(descriptor otel.Descriptor) key { +func keyOf(descriptor metric.Descriptor) key { return key{ descriptor.Name(), descriptor.InstrumentationName(), @@ -89,7 +89,7 @@ func keyOf(descriptor otel.Descriptor) key { // NewMetricKindMismatchError formats an error that describes a // mismatched metric instrument definition. -func NewMetricKindMismatchError(desc otel.Descriptor) error { +func NewMetricKindMismatchError(desc metric.Descriptor) error { return fmt.Errorf("Metric was %s (%s %s)registered as a %s %s: %w", desc.Name(), desc.InstrumentationName(), @@ -99,9 +99,9 @@ func NewMetricKindMismatchError(desc otel.Descriptor) error { ErrMetricKindMismatch) } -// Compatible determines whether two otel.Descriptors are considered +// Compatible determines whether two metric.Descriptors are considered // the same for the purpose of uniqueness checking. -func Compatible(candidate, existing otel.Descriptor) bool { +func Compatible(candidate, existing metric.Descriptor) bool { return candidate.InstrumentKind() == existing.InstrumentKind() && candidate.NumberKind() == existing.NumberKind() } @@ -111,7 +111,7 @@ func Compatible(candidate, existing otel.Descriptor) bool { // `descriptor` argument. If there is an existing compatible // registration, this returns the already-registered instrument. If // there is no conflict and no prior registration, returns (nil, nil). -func (u *uniqueInstrumentMeterImpl) checkUniqueness(descriptor otel.Descriptor) (otel.InstrumentImpl, error) { +func (u *uniqueInstrumentMeterImpl) checkUniqueness(descriptor metric.Descriptor) (metric.InstrumentImpl, error) { impl, ok := u.state[keyOf(descriptor)] if !ok { return nil, nil @@ -124,8 +124,8 @@ func (u *uniqueInstrumentMeterImpl) checkUniqueness(descriptor otel.Descriptor) return impl, nil } -// NewSyncInstrument implements otel.MeterImpl. -func (u *uniqueInstrumentMeterImpl) NewSyncInstrument(descriptor otel.Descriptor) (otel.SyncImpl, error) { +// NewSyncInstrument implements metric.MeterImpl. +func (u *uniqueInstrumentMeterImpl) NewSyncInstrument(descriptor metric.Descriptor) (metric.SyncImpl, error) { u.lock.Lock() defer u.lock.Unlock() @@ -134,7 +134,7 @@ func (u *uniqueInstrumentMeterImpl) NewSyncInstrument(descriptor otel.Descriptor if err != nil { return nil, err } else if impl != nil { - return impl.(otel.SyncImpl), nil + return impl.(metric.SyncImpl), nil } syncInst, err := u.impl.NewSyncInstrument(descriptor) @@ -145,11 +145,11 @@ func (u *uniqueInstrumentMeterImpl) NewSyncInstrument(descriptor otel.Descriptor return syncInst, nil } -// NewAsyncInstrument implements otel.MeterImpl. +// NewAsyncInstrument implements metric.MeterImpl. func (u *uniqueInstrumentMeterImpl) NewAsyncInstrument( - descriptor otel.Descriptor, - runner otel.AsyncRunner, -) (otel.AsyncImpl, error) { + descriptor metric.Descriptor, + runner metric.AsyncRunner, +) (metric.AsyncImpl, error) { u.lock.Lock() defer u.lock.Unlock() @@ -158,7 +158,7 @@ func (u *uniqueInstrumentMeterImpl) NewAsyncInstrument( if err != nil { return nil, err } else if impl != nil { - return impl.(otel.AsyncImpl), nil + return impl.(metric.AsyncImpl), nil } asyncInst, err := u.impl.NewAsyncInstrument(descriptor, runner) diff --git a/registry/registry_test.go b/metric/registry/registry_test.go similarity index 75% rename from registry/registry_test.go rename to metric/registry/registry_test.go index 05084d96bfa..ed86ba739d0 100644 --- a/registry/registry_test.go +++ b/metric/registry/registry_test.go @@ -21,49 +21,49 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/registry" "go.opentelemetry.io/otel/oteltest" - "go.opentelemetry.io/otel/registry" ) type ( - newFunc func(m otel.Meter, name string) (otel.InstrumentImpl, error) + newFunc func(m metric.Meter, name string) (metric.InstrumentImpl, error) ) var ( allNew = map[string]newFunc{ - "counter.int64": func(m otel.Meter, name string) (otel.InstrumentImpl, error) { + "counter.int64": func(m metric.Meter, name string) (metric.InstrumentImpl, error) { return unwrap(m.NewInt64Counter(name)) }, - "counter.float64": func(m otel.Meter, name string) (otel.InstrumentImpl, error) { + "counter.float64": func(m metric.Meter, name string) (metric.InstrumentImpl, error) { return unwrap(m.NewFloat64Counter(name)) }, - "valuerecorder.int64": func(m otel.Meter, name string) (otel.InstrumentImpl, error) { + "valuerecorder.int64": func(m metric.Meter, name string) (metric.InstrumentImpl, error) { return unwrap(m.NewInt64ValueRecorder(name)) }, - "valuerecorder.float64": func(m otel.Meter, name string) (otel.InstrumentImpl, error) { + "valuerecorder.float64": func(m metric.Meter, name string) (metric.InstrumentImpl, error) { return unwrap(m.NewFloat64ValueRecorder(name)) }, - "valueobserver.int64": func(m otel.Meter, name string) (otel.InstrumentImpl, error) { - return unwrap(m.NewInt64ValueObserver(name, func(context.Context, otel.Int64ObserverResult) {})) + "valueobserver.int64": func(m metric.Meter, name string) (metric.InstrumentImpl, error) { + return unwrap(m.NewInt64ValueObserver(name, func(context.Context, metric.Int64ObserverResult) {})) }, - "valueobserver.float64": func(m otel.Meter, name string) (otel.InstrumentImpl, error) { - return unwrap(m.NewFloat64ValueObserver(name, func(context.Context, otel.Float64ObserverResult) {})) + "valueobserver.float64": func(m metric.Meter, name string) (metric.InstrumentImpl, error) { + return unwrap(m.NewFloat64ValueObserver(name, func(context.Context, metric.Float64ObserverResult) {})) }, } ) -func unwrap(impl interface{}, err error) (otel.InstrumentImpl, error) { +func unwrap(impl interface{}, err error) (metric.InstrumentImpl, error) { if impl == nil { return nil, err } if s, ok := impl.(interface { - SyncImpl() otel.SyncImpl + SyncImpl() metric.SyncImpl }); ok { return s.SyncImpl(), err } if a, ok := impl.(interface { - AsyncImpl() otel.AsyncImpl + AsyncImpl() metric.AsyncImpl }); ok { return a.AsyncImpl(), err } diff --git a/numberkind_string.go b/numberkind_string.go deleted file mode 100644 index 005e324af1b..00000000000 --- a/numberkind_string.go +++ /dev/null @@ -1,24 +0,0 @@ -// Code generated by "stringer -type=NumberKind"; DO NOT EDIT. - -package otel - -import "strconv" - -func _() { - // An "invalid array index" compiler error signifies that the constant values have changed. - // Re-run the stringer command to generate them again. - var x [1]struct{} - _ = x[Int64NumberKind-0] - _ = x[Float64NumberKind-1] -} - -const _NumberKind_name = "Int64NumberKindFloat64NumberKind" - -var _NumberKind_index = [...]uint8{0, 15, 32} - -func (i NumberKind) String() string { - if i < 0 || i >= NumberKind(len(_NumberKind_index)-1) { - return "NumberKind(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _NumberKind_name[_NumberKind_index[i]:_NumberKind_index[i+1]] -} diff --git a/oteltest/config.go b/oteltest/config.go index 582beaa1548..5ef080424fc 100644 --- a/oteltest/config.go +++ b/oteltest/config.go @@ -20,17 +20,17 @@ import ( "sync" "sync/atomic" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" ) // defaultSpanContextFunc returns the default SpanContextFunc. -func defaultSpanContextFunc() func(context.Context) otel.SpanContext { +func defaultSpanContextFunc() func(context.Context) trace.SpanContext { var traceID, spanID uint64 = 1, 1 - return func(ctx context.Context) otel.SpanContext { - var sc otel.SpanContext - if lsc := otel.SpanContextFromContext(ctx); lsc.IsValid() { + return func(ctx context.Context) trace.SpanContext { + var sc trace.SpanContext + if lsc := trace.SpanContextFromContext(ctx); lsc.IsValid() { sc = lsc - } else if rsc := otel.RemoteSpanContextFromContext(ctx); rsc.IsValid() { + } else if rsc := trace.RemoteSpanContextFromContext(ctx); rsc.IsValid() { sc = rsc } else { binary.BigEndian.PutUint64(sc.TraceID[:], atomic.AddUint64(&traceID, 1)) @@ -43,7 +43,7 @@ func defaultSpanContextFunc() func(context.Context) otel.SpanContext { type config struct { // SpanContextFunc returns a SpanContext from an parent Context for a // new span. - SpanContextFunc func(context.Context) otel.SpanContext + SpanContextFunc func(context.Context) trace.SpanContext // SpanRecorder keeps track of spans. SpanRecorder SpanRecorder @@ -66,7 +66,7 @@ type Option interface { } type spanContextFuncOption struct { - SpanContextFunc func(context.Context) otel.SpanContext + SpanContextFunc func(context.Context) trace.SpanContext } func (o spanContextFuncOption) Apply(c *config) { @@ -75,7 +75,7 @@ func (o spanContextFuncOption) Apply(c *config) { // WithSpanContextFunc sets the SpanContextFunc used to generate a new Spans // context from a parent SpanContext. -func WithSpanContextFunc(f func(context.Context) otel.SpanContext) Option { +func WithSpanContextFunc(f func(context.Context) trace.SpanContext) Option { return spanContextFuncOption{f} } diff --git a/oteltest/harness.go b/oteltest/harness.go index 7ce4b080d1d..309e6832a5c 100644 --- a/oteltest/harness.go +++ b/oteltest/harness.go @@ -20,10 +20,10 @@ import ( "testing" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/internal/matchers" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" ) // Harness is a testing harness used to test implementations of the @@ -41,7 +41,7 @@ func NewHarness(t *testing.T) *Harness { // TestTracer runs validation tests for an implementation of the OpenTelemetry // Tracer API. -func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) { +func (h *Harness) TestTracer(subjectFactory func() trace.Tracer) { h.t.Run("#Start", func(t *testing.T) { t.Run("propagates the original context", func(t *testing.T) { t.Parallel() @@ -81,8 +81,8 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) { ctx, span := subject.Start(context.Background(), "test") e.Expect(span).NotToBeNil() - e.Expect(span.SpanContext()).NotToEqual(otel.SpanContext{}) - e.Expect(otel.SpanFromContext(ctx)).ToEqual(span) + e.Expect(span.SpanContext()).NotToEqual(trace.SpanContext{}) + e.Expect(trace.SpanFromContext(ctx)).ToEqual(span) }) t.Run("starts spans with unique trace and span IDs", func(t *testing.T) { @@ -107,7 +107,7 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) { e := matchers.NewExpecter(t) subject := subjectFactory() - _, span := subject.Start(context.Background(), "span", otel.WithRecord()) + _, span := subject.Start(context.Background(), "span", trace.WithRecord()) e.Expect(span.IsRecording()).ToBeTrue() }) @@ -135,7 +135,7 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) { subject := subjectFactory() ctx, parent := subject.Start(context.Background(), "parent") - _, child := subject.Start(ctx, "child", otel.WithNewRoot()) + _, child := subject.Start(ctx, "child", trace.WithNewRoot()) psc := parent.SpanContext() csc := child.SpanContext() @@ -151,7 +151,7 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) { subject := subjectFactory() _, remoteParent := subject.Start(context.Background(), "remote parent") - parentCtx := otel.ContextWithRemoteSpanContext(context.Background(), remoteParent.SpanContext()) + parentCtx := trace.ContextWithRemoteSpanContext(context.Background(), remoteParent.SpanContext()) _, child := subject.Start(parentCtx, "child") psc := remoteParent.SpanContext() @@ -168,8 +168,8 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) { subject := subjectFactory() _, remoteParent := subject.Start(context.Background(), "remote parent") - parentCtx := otel.ContextWithRemoteSpanContext(context.Background(), remoteParent.SpanContext()) - _, child := subject.Start(parentCtx, "child", otel.WithNewRoot()) + parentCtx := trace.ContextWithRemoteSpanContext(context.Background(), remoteParent.SpanContext()) + _, child := subject.Start(parentCtx, "child", trace.WithNewRoot()) psc := remoteParent.SpanContext() csc := child.SpanContext() @@ -182,29 +182,29 @@ func (h *Harness) TestTracer(subjectFactory func() otel.Tracer) { h.testSpan(subjectFactory) } -func (h *Harness) testSpan(tracerFactory func() otel.Tracer) { - var methods = map[string]func(span otel.Span){ - "#End": func(span otel.Span) { +func (h *Harness) testSpan(tracerFactory func() trace.Tracer) { + var methods = map[string]func(span trace.Span){ + "#End": func(span trace.Span) { span.End() }, - "#AddEvent": func(span otel.Span) { + "#AddEvent": func(span trace.Span) { span.AddEvent("test event") }, - "#AddEventWithTimestamp": func(span otel.Span) { - span.AddEvent("test event", otel.WithTimestamp(time.Now().Add(1*time.Second))) + "#AddEventWithTimestamp": func(span trace.Span) { + span.AddEvent("test event", trace.WithTimestamp(time.Now().Add(1*time.Second))) }, - "#SetStatus": func(span otel.Span) { + "#SetStatus": func(span trace.Span) { span.SetStatus(codes.Error, "internal") }, - "#SetName": func(span otel.Span) { + "#SetName": func(span trace.Span) { span.SetName("new name") }, - "#SetAttributes": func(span otel.Span) { + "#SetAttributes": func(span trace.Span) { span.SetAttributes(label.String("key1", "value"), label.Int("key2", 123)) }, } - var mechanisms = map[string]func() otel.Span{ - "Span created via Tracer#Start": func() otel.Span { + var mechanisms = map[string]func() trace.Span{ + "Span created via Tracer#Start": func() trace.Span { tracer := tracerFactory() _, subject := tracer.Start(context.Background(), "test") diff --git a/oteltest/meter.go b/oteltest/meter.go index 44abe7304ef..d7899ce71a8 100644 --- a/oteltest/meter.go +++ b/oteltest/meter.go @@ -19,11 +19,11 @@ import ( "sync" "testing" - "go.opentelemetry.io/otel" - apimetric "go.opentelemetry.io/otel" internalmetric "go.opentelemetry.io/otel/internal/metric" "go.opentelemetry.io/otel/label" - "go.opentelemetry.io/otel/registry" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" + "go.opentelemetry.io/otel/metric/registry" ) type ( @@ -51,19 +51,19 @@ type ( Measurement struct { // Number needs to be aligned for 64-bit atomic operations. - Number apimetric.Number - Instrument apimetric.InstrumentImpl + Number number.Number + Instrument metric.InstrumentImpl } Instrument struct { meter *MeterImpl - descriptor apimetric.Descriptor + descriptor metric.Descriptor } Async struct { Instrument - runner apimetric.AsyncRunner + runner metric.AsyncRunner } Sync struct { @@ -72,13 +72,13 @@ type ( ) var ( - _ apimetric.SyncImpl = &Sync{} - _ apimetric.BoundSyncImpl = &Handle{} - _ apimetric.MeterImpl = &MeterImpl{} - _ apimetric.AsyncImpl = &Async{} + _ metric.SyncImpl = &Sync{} + _ metric.BoundSyncImpl = &Handle{} + _ metric.MeterImpl = &MeterImpl{} + _ metric.AsyncImpl = &Async{} ) -func (i Instrument) Descriptor() apimetric.Descriptor { +func (i Instrument) Descriptor() metric.Descriptor { return i.descriptor } @@ -90,44 +90,44 @@ func (s *Sync) Implementation() interface{} { return s } -func (s *Sync) Bind(labels []label.KeyValue) apimetric.BoundSyncImpl { +func (s *Sync) Bind(labels []label.KeyValue) metric.BoundSyncImpl { return &Handle{ Instrument: s, Labels: labels, } } -func (s *Sync) RecordOne(ctx context.Context, number apimetric.Number, labels []label.KeyValue) { +func (s *Sync) RecordOne(ctx context.Context, number number.Number, labels []label.KeyValue) { s.meter.doRecordSingle(ctx, labels, s, number) } -func (h *Handle) RecordOne(ctx context.Context, number apimetric.Number) { +func (h *Handle) RecordOne(ctx context.Context, number number.Number) { h.Instrument.meter.doRecordSingle(ctx, h.Labels, h.Instrument, number) } func (h *Handle) Unbind() { } -func (m *MeterImpl) doRecordSingle(ctx context.Context, labels []label.KeyValue, instrument apimetric.InstrumentImpl, number apimetric.Number) { +func (m *MeterImpl) doRecordSingle(ctx context.Context, labels []label.KeyValue, instrument metric.InstrumentImpl, number number.Number) { m.collect(ctx, labels, []Measurement{{ Instrument: instrument, Number: number, }}) } -func NewMeterProvider() (*MeterImpl, apimetric.MeterProvider) { +func NewMeterProvider() (*MeterImpl, metric.MeterProvider) { impl := &MeterImpl{ asyncInstruments: internalmetric.NewAsyncInstrumentState(), } return impl, registry.NewMeterProvider(impl) } -func NewMeter() (*MeterImpl, apimetric.Meter) { +func NewMeter() (*MeterImpl, metric.Meter) { impl, p := NewMeterProvider() return impl, p.Meter("mock") } -func (m *MeterImpl) NewSyncInstrument(descriptor otel.Descriptor) (apimetric.SyncImpl, error) { +func (m *MeterImpl) NewSyncInstrument(descriptor metric.Descriptor) (metric.SyncImpl, error) { m.lock.Lock() defer m.lock.Unlock() @@ -139,7 +139,7 @@ func (m *MeterImpl) NewSyncInstrument(descriptor otel.Descriptor) (apimetric.Syn }, nil } -func (m *MeterImpl) NewAsyncInstrument(descriptor otel.Descriptor, runner otel.AsyncRunner) (apimetric.AsyncImpl, error) { +func (m *MeterImpl) NewAsyncInstrument(descriptor metric.Descriptor, runner metric.AsyncRunner) (metric.AsyncImpl, error) { m.lock.Lock() defer m.lock.Unlock() @@ -154,7 +154,7 @@ func (m *MeterImpl) NewAsyncInstrument(descriptor otel.Descriptor, runner otel.A return a, nil } -func (m *MeterImpl) RecordBatch(ctx context.Context, labels []label.KeyValue, measurements ...apimetric.Measurement) { +func (m *MeterImpl) RecordBatch(ctx context.Context, labels []label.KeyValue, measurements ...metric.Measurement) { mm := make([]Measurement, len(measurements)) for i := 0; i < len(measurements); i++ { m := measurements[i] @@ -166,7 +166,7 @@ func (m *MeterImpl) RecordBatch(ctx context.Context, labels []label.KeyValue, me m.collect(ctx, labels, mm) } -func (m *MeterImpl) CollectAsync(labels []label.KeyValue, obs ...otel.Observation) { +func (m *MeterImpl) CollectAsync(labels []label.KeyValue, obs ...metric.Observation) { mm := make([]Measurement, len(obs)) for i := 0; i < len(obs); i++ { o := obs[i] @@ -200,7 +200,7 @@ type Measured struct { InstrumentationName string InstrumentationVersion string Labels map[label.Key]label.Value - Number otel.Number + Number number.Number } // LabelsToMap converts label set to keyValue map, to be easily used in tests @@ -230,13 +230,13 @@ func AsStructs(batches []Batch) []Measured { } // ResolveNumberByKind takes defined metric descriptor creates a concrete typed metric number -func ResolveNumberByKind(t *testing.T, kind otel.NumberKind, value float64) otel.Number { +func ResolveNumberByKind(t *testing.T, kind number.Kind, value float64) number.Number { t.Helper() switch kind { - case otel.Int64NumberKind: - return otel.NewInt64Number(int64(value)) - case otel.Float64NumberKind: - return otel.NewFloat64Number(value) + case number.Int64Kind: + return number.NewInt64Number(int64(value)) + case number.Float64Kind: + return number.NewFloat64Number(value) } panic("invalid number kind") } diff --git a/oteltest/provider.go b/oteltest/provider.go index e35ba9c959e..babba528e12 100644 --- a/oteltest/provider.go +++ b/oteltest/provider.go @@ -17,7 +17,7 @@ package oteltest // import "go.opentelemetry.io/otel/oteltest" import ( "sync" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" ) // TracerProvider is a testing TracerProvider. It is an functioning @@ -31,7 +31,7 @@ type TracerProvider struct { tracers map[instrumentation]*Tracer } -var _ otel.TracerProvider = (*TracerProvider)(nil) +var _ trace.TracerProvider = (*TracerProvider)(nil) // NewTracerProvider returns a *TracerProvider configured with options. func NewTracerProvider(options ...Option) *TracerProvider { @@ -46,8 +46,8 @@ type instrumentation struct { } // Tracer returns an OpenTelemetry Tracer used for testing. -func (p *TracerProvider) Tracer(instName string, opts ...otel.TracerOption) otel.Tracer { - conf := otel.NewTracerConfig(opts...) +func (p *TracerProvider) Tracer(instName string, opts ...trace.TracerOption) trace.Tracer { + conf := trace.NewTracerConfig(opts...) inst := instrumentation{ Name: instName, @@ -68,6 +68,6 @@ func (p *TracerProvider) Tracer(instName string, opts ...otel.TracerOption) otel } // DefaulTracer returns a default tracer for testing purposes. -func DefaultTracer() otel.Tracer { +func DefaultTracer() trace.Tracer { return NewTracerProvider().Tracer("") } diff --git a/oteltest/span.go b/oteltest/span.go index 3321eb82d70..feb892fdd59 100644 --- a/oteltest/span.go +++ b/oteltest/span.go @@ -20,9 +20,9 @@ import ( "sync" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" ) const ( @@ -31,14 +31,14 @@ const ( errorEventName = "error" ) -var _ otel.Span = (*Span)(nil) +var _ trace.Span = (*Span)(nil) // Span is an OpenTelemetry Span used for testing. type Span struct { lock sync.RWMutex tracer *Tracer - spanContext otel.SpanContext - parentSpanID otel.SpanID + spanContext trace.SpanContext + parentSpanID trace.SpanID ended bool name string startTime time.Time @@ -47,19 +47,19 @@ type Span struct { statusMessage string attributes map[label.Key]label.Value events []Event - links map[otel.SpanContext][]label.KeyValue - spanKind otel.SpanKind + links map[trace.SpanContext][]label.KeyValue + spanKind trace.SpanKind } // Tracer returns the Tracer that created s. -func (s *Span) Tracer() otel.Tracer { +func (s *Span) Tracer() trace.Tracer { return s.tracer } // End ends s. If the Tracer that created s was configured with a // SpanRecorder, that recorder's OnEnd method is called as the final part of // this method. -func (s *Span) End(opts ...otel.SpanOption) { +func (s *Span) End(opts ...trace.SpanOption) { s.lock.Lock() defer s.lock.Unlock() @@ -67,7 +67,7 @@ func (s *Span) End(opts ...otel.SpanOption) { return } - c := otel.NewSpanConfig(opts...) + c := trace.NewSpanConfig(opts...) s.endTime = time.Now() if endTime := c.Timestamp; !endTime.IsZero() { s.endTime = endTime @@ -80,7 +80,7 @@ func (s *Span) End(opts ...otel.SpanOption) { } // RecordError records an error as a Span event. -func (s *Span) RecordError(err error, opts ...otel.EventOption) { +func (s *Span) RecordError(err error, opts ...trace.EventOption) { if err == nil || s.ended { return } @@ -92,7 +92,7 @@ func (s *Span) RecordError(err error, opts ...otel.EventOption) { } s.SetStatus(codes.Error, "") - opts = append(opts, otel.WithAttributes( + opts = append(opts, trace.WithAttributes( errorTypeKey.String(errTypeString), errorMessageKey.String(err.Error()), )) @@ -101,7 +101,7 @@ func (s *Span) RecordError(err error, opts ...otel.EventOption) { } // AddEvent adds an event to s. -func (s *Span) AddEvent(name string, o ...otel.EventOption) { +func (s *Span) AddEvent(name string, o ...trace.EventOption) { s.lock.Lock() defer s.lock.Unlock() @@ -109,7 +109,7 @@ func (s *Span) AddEvent(name string, o ...otel.EventOption) { return } - c := otel.NewEventConfig(o...) + c := trace.NewEventConfig(o...) var attributes map[label.Key]label.Value if l := len(c.Attributes); l > 0 { @@ -132,7 +132,7 @@ func (s *Span) IsRecording() bool { } // SpanContext returns the SpanContext of s. -func (s *Span) SpanContext() otel.SpanContext { +func (s *Span) SpanContext() trace.SpanContext { return s.spanContext } @@ -182,7 +182,7 @@ func (s *Span) Name() string { return s.name } // ParentSpanID returns the SpanID of the parent Span. If s is a root Span, // and therefore does not have a parent, the returned SpanID will be invalid // (i.e., it will contain all zeroes). -func (s *Span) ParentSpanID() otel.SpanID { return s.parentSpanID } +func (s *Span) ParentSpanID() trace.SpanID { return s.parentSpanID } // Attributes returns the attributes set on s, either at or after creation // time. If the same attribute key was set multiple times, the last call will @@ -206,8 +206,8 @@ func (s *Span) Events() []Event { return s.events } // Links returns the links set on s at creation time. If multiple links for // the same SpanContext were set, the last link will be used. -func (s *Span) Links() map[otel.SpanContext][]label.KeyValue { - links := make(map[otel.SpanContext][]label.KeyValue) +func (s *Span) Links() map[trace.SpanContext][]label.KeyValue { + links := make(map[trace.SpanContext][]label.KeyValue) for sc, attributes := range s.links { links[sc] = append([]label.KeyValue{}, attributes...) @@ -239,4 +239,4 @@ func (s *Span) StatusCode() codes.Code { return s.statusCode } func (s *Span) StatusMessage() string { return s.statusMessage } // SpanKind returns the span kind of s. -func (s *Span) SpanKind() otel.SpanKind { return s.spanKind } +func (s *Span) SpanKind() trace.SpanKind { return s.spanKind } diff --git a/oteltest/span_test.go b/oteltest/span_test.go index de0171da7c4..cc526c6ebf8 100644 --- a/oteltest/span_test.go +++ b/oteltest/span_test.go @@ -22,12 +22,12 @@ import ( "testing" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/internal/matchers" ottest "go.opentelemetry.io/otel/internal/testing" "go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/oteltest" + "go.opentelemetry.io/otel/trace" ) func TestSpan(t *testing.T) { @@ -113,7 +113,7 @@ func TestSpan(t *testing.T) { e.Expect(ok).ToBeTrue() expectedEndTime := time.Now().AddDate(5, 0, 0) - subject.End(otel.WithTimestamp(expectedEndTime)) + subject.End(trace.WithTimestamp(expectedEndTime)) e.Expect(subject.Ended()).ToBeTrue() @@ -156,7 +156,7 @@ func TestSpan(t *testing.T) { e.Expect(ok).ToBeTrue() testTime := time.Now() - subject.RecordError(s.err, otel.WithTimestamp(testTime)) + subject.RecordError(s.err, trace.WithTimestamp(testTime)) expectedEvents := []oteltest.Event{{ Timestamp: testTime, @@ -186,7 +186,7 @@ func TestSpan(t *testing.T) { errMsg := "test error message" testErr := ottest.NewTestError(errMsg) testTime := time.Now() - subject.RecordError(testErr, otel.WithTimestamp(testTime)) + subject.RecordError(testErr, trace.WithTimestamp(testTime)) expectedEvents := []oteltest.Event{{ Timestamp: testTime, @@ -464,7 +464,7 @@ func TestSpan(t *testing.T) { } event1Start := time.Now() - subject.AddEvent(event1Name, otel.WithAttributes(event1Attributes...)) + subject.AddEvent(event1Name, trace.WithAttributes(event1Attributes...)) event1End := time.Now() event2Timestamp := time.Now().AddDate(5, 0, 0) @@ -473,7 +473,7 @@ func TestSpan(t *testing.T) { label.String("event2Attr", "abc"), } - subject.AddEvent(event2Name, otel.WithTimestamp(event2Timestamp), otel.WithAttributes(event2Attributes...)) + subject.AddEvent(event2Name, trace.WithTimestamp(event2Timestamp), trace.WithAttributes(event2Attributes...)) events := subject.Events() @@ -601,13 +601,13 @@ func TestSpan(t *testing.T) { tracer := tp.Tracer(t.Name()) _, span := tracer.Start(context.Background(), "test", - otel.WithSpanKind(otel.SpanKindConsumer)) + trace.WithSpanKind(trace.SpanKindConsumer)) subject, ok := span.(*oteltest.Span) e.Expect(ok).ToBeTrue() subject.End() - e.Expect(subject.SpanKind()).ToEqual(otel.SpanKindConsumer) + e.Expect(subject.SpanKind()).ToEqual(trace.SpanKindConsumer) }) }) } diff --git a/oteltest/tracer.go b/oteltest/tracer.go index bf18e30c78a..45446e70a84 100644 --- a/oteltest/tracer.go +++ b/oteltest/tracer.go @@ -18,11 +18,11 @@ import ( "context" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" ) -var _ otel.Tracer = (*Tracer)(nil) +var _ trace.Tracer = (*Tracer)(nil) // Tracer is an OpenTelemetry Tracer implementation used for testing. type Tracer struct { @@ -36,8 +36,8 @@ type Tracer struct { // Start creates a span. If t is configured with a SpanRecorder its OnStart // method will be called after the created Span has been initialized. -func (t *Tracer) Start(ctx context.Context, name string, opts ...otel.SpanOption) (context.Context, otel.Span) { - c := otel.NewSpanConfig(opts...) +func (t *Tracer) Start(ctx context.Context, name string, opts ...trace.SpanOption) (context.Context, trace.Span) { + c := trace.NewSpanConfig(opts...) startTime := time.Now() if st := c.Timestamp; !st.IsZero() { startTime = st @@ -47,26 +47,26 @@ func (t *Tracer) Start(ctx context.Context, name string, opts ...otel.SpanOption tracer: t, startTime: startTime, attributes: make(map[label.Key]label.Value), - links: make(map[otel.SpanContext][]label.KeyValue), + links: make(map[trace.SpanContext][]label.KeyValue), spanKind: c.SpanKind, } if c.NewRoot { - span.spanContext = otel.SpanContext{} + span.spanContext = trace.SpanContext{} iodKey := label.Key("ignored-on-demand") - if lsc := otel.SpanContextFromContext(ctx); lsc.IsValid() { + if lsc := trace.SpanContextFromContext(ctx); lsc.IsValid() { span.links[lsc] = []label.KeyValue{iodKey.String("current")} } - if rsc := otel.RemoteSpanContextFromContext(ctx); rsc.IsValid() { + if rsc := trace.RemoteSpanContextFromContext(ctx); rsc.IsValid() { span.links[rsc] = []label.KeyValue{iodKey.String("remote")} } } else { span.spanContext = t.config.SpanContextFunc(ctx) - if lsc := otel.SpanContextFromContext(ctx); lsc.IsValid() { + if lsc := trace.SpanContextFromContext(ctx); lsc.IsValid() { span.spanContext.TraceID = lsc.TraceID span.parentSpanID = lsc.SpanID - } else if rsc := otel.RemoteSpanContextFromContext(ctx); rsc.IsValid() { + } else if rsc := trace.RemoteSpanContextFromContext(ctx); rsc.IsValid() { span.spanContext.TraceID = rsc.TraceID span.parentSpanID = rsc.SpanID } @@ -82,5 +82,5 @@ func (t *Tracer) Start(ctx context.Context, name string, opts ...otel.SpanOption if t.config.SpanRecorder != nil { t.config.SpanRecorder.OnStart(span) } - return otel.ContextWithSpan(ctx, span), span + return trace.ContextWithSpan(ctx, span), span } diff --git a/oteltest/tracer_test.go b/oteltest/tracer_test.go index c0959908209..1de96913a4f 100644 --- a/oteltest/tracer_test.go +++ b/oteltest/tracer_test.go @@ -22,25 +22,25 @@ import ( "testing" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/internal/matchers" "go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/oteltest" + "go.opentelemetry.io/otel/trace" ) func TestTracer(t *testing.T) { tp := oteltest.NewTracerProvider() - oteltest.NewHarness(t).TestTracer(func() func() otel.Tracer { + oteltest.NewHarness(t).TestTracer(func() func() trace.Tracer { tp := oteltest.NewTracerProvider() var i uint64 - return func() otel.Tracer { + return func() trace.Tracer { return tp.Tracer(fmt.Sprintf("tracer %d", atomic.AddUint64(&i, 1))) } }()) t.Run("#Start", func(t *testing.T) { - testTracedSpan(t, func(tracer otel.Tracer, name string) (otel.Span, error) { + testTracedSpan(t, func(tracer trace.Tracer, name string) (trace.Span, error) { _, span := tracer.Start(context.Background(), name) return span, nil @@ -54,7 +54,7 @@ func TestTracer(t *testing.T) { expectedStartTime := time.Now().AddDate(5, 0, 0) subject := tp.Tracer(t.Name()) - _, span := subject.Start(context.Background(), "test", otel.WithTimestamp(expectedStartTime)) + _, span := subject.Start(context.Background(), "test", trace.WithTimestamp(expectedStartTime)) testSpan, ok := span.(*oteltest.Span) e.Expect(ok).ToBeTrue() @@ -71,7 +71,7 @@ func TestTracer(t *testing.T) { attr2 := label.String("b", "2") subject := tp.Tracer(t.Name()) - _, span := subject.Start(context.Background(), "test", otel.WithAttributes(attr1, attr2)) + _, span := subject.Start(context.Background(), "test", trace.WithAttributes(attr1, attr2)) testSpan, ok := span.(*oteltest.Span) e.Expect(ok).ToBeTrue() @@ -111,7 +111,7 @@ func TestTracer(t *testing.T) { parent, parentSpan := subject.Start(context.Background(), "parent") _, remoteParentSpan := subject.Start(context.Background(), "remote not-a-parent") - parent = otel.ContextWithRemoteSpanContext(parent, remoteParentSpan.SpanContext()) + parent = trace.ContextWithRemoteSpanContext(parent, remoteParentSpan.SpanContext()) parentSpanContext := parentSpan.SpanContext() _, span := subject.Start(parent, "child") @@ -133,7 +133,7 @@ func TestTracer(t *testing.T) { subject := tp.Tracer(t.Name()) _, remoteParentSpan := subject.Start(context.Background(), "remote parent") - parent := otel.ContextWithRemoteSpanContext(context.Background(), remoteParentSpan.SpanContext()) + parent := trace.ContextWithRemoteSpanContext(context.Background(), remoteParentSpan.SpanContext()) remoteParentSpanContext := remoteParentSpan.SpanContext() _, span := subject.Start(parent, "child") @@ -183,9 +183,9 @@ func TestTracer(t *testing.T) { _, remoteParentSpan := subject.Start(context.Background(), "remote not-a-parent") parentSpanContext := parentSpan.SpanContext() remoteParentSpanContext := remoteParentSpan.SpanContext() - parentCtx = otel.ContextWithRemoteSpanContext(parentCtx, remoteParentSpanContext) + parentCtx = trace.ContextWithRemoteSpanContext(parentCtx, remoteParentSpanContext) - _, span := subject.Start(parentCtx, "child", otel.WithNewRoot()) + _, span := subject.Start(parentCtx, "child", trace.WithNewRoot()) testSpan, ok := span.(*oteltest.Span) e.Expect(ok).ToBeTrue() @@ -197,7 +197,7 @@ func TestTracer(t *testing.T) { e.Expect(childSpanContext.SpanID).NotToEqual(remoteParentSpanContext.SpanID) e.Expect(testSpan.ParentSpanID().IsValid()).ToBeFalse() - expectedLinks := []otel.Link{ + expectedLinks := []trace.Link{ { SpanContext: parentSpanContext, Attributes: []label.KeyValue{ @@ -212,9 +212,9 @@ func TestTracer(t *testing.T) { }, } tsLinks := testSpan.Links() - gotLinks := make([]otel.Link, 0, len(tsLinks)) + gotLinks := make([]trace.Link, 0, len(tsLinks)) for sc, attributes := range tsLinks { - gotLinks = append(gotLinks, otel.Link{ + gotLinks = append(gotLinks, trace.Link{ SpanContext: sc, Attributes: attributes, }) @@ -230,7 +230,7 @@ func TestTracer(t *testing.T) { subject := tp.Tracer(t.Name()) _, span := subject.Start(context.Background(), "link1") - link1 := otel.Link{ + link1 := trace.Link{ SpanContext: span.SpanContext(), Attributes: []label.KeyValue{ label.String("a", "1"), @@ -238,14 +238,14 @@ func TestTracer(t *testing.T) { } _, span = subject.Start(context.Background(), "link2") - link2 := otel.Link{ + link2 := trace.Link{ SpanContext: span.SpanContext(), Attributes: []label.KeyValue{ label.String("b", "2"), }, } - _, span = subject.Start(context.Background(), "test", otel.WithLinks(link1, link2)) + _, span = subject.Start(context.Background(), "test", trace.WithLinks(link1, link2)) testSpan, ok := span.(*oteltest.Span) e.Expect(ok).ToBeTrue() @@ -257,7 +257,7 @@ func TestTracer(t *testing.T) { }) } -func testTracedSpan(t *testing.T, fn func(tracer otel.Tracer, name string) (otel.Span, error)) { +func testTracedSpan(t *testing.T, fn func(tracer trace.Tracer, name string) (trace.Span, error)) { tp := oteltest.NewTracerProvider() t.Run("starts a span with the expected name", func(t *testing.T) { t.Parallel() diff --git a/propagators/propagators_test.go b/propagators/propagators_test.go index c5e0509e9ad..03af3ca0d38 100644 --- a/propagators/propagators_test.go +++ b/propagators/propagators_test.go @@ -23,6 +23,7 @@ import ( "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/propagators" + "go.opentelemetry.io/otel/trace" ) const ( @@ -35,18 +36,18 @@ var ( spanID = mustSpanIDFromHex(spanIDStr) ) -func mustTraceIDFromHex(s string) (t otel.TraceID) { +func mustTraceIDFromHex(s string) (t trace.TraceID) { var err error - t, err = otel.TraceIDFromHex(s) + t, err = trace.TraceIDFromHex(s) if err != nil { panic(err) } return } -func mustSpanIDFromHex(s string) (t otel.SpanID) { +func mustSpanIDFromHex(s string) (t trace.SpanID) { var err error - t, err = otel.SpanIDFromHex(s) + t, err = trace.SpanIDFromHex(s) if err != nil { panic(err) } @@ -60,13 +61,13 @@ type outOfThinAirPropagator struct { var _ otel.TextMapPropagator = outOfThinAirPropagator{} func (p outOfThinAirPropagator) Extract(ctx context.Context, carrier otel.TextMapCarrier) context.Context { - sc := otel.SpanContext{ + sc := trace.SpanContext{ TraceID: traceID, SpanID: spanID, TraceFlags: 0, } require.True(p.t, sc.IsValid()) - return otel.ContextWithRemoteSpanContext(ctx, sc) + return trace.ContextWithRemoteSpanContext(ctx, sc) } func (outOfThinAirPropagator) Inject(context.Context, otel.TextMapCarrier) {} @@ -96,7 +97,7 @@ func TestMultiplePropagators(t *testing.T) { // generates the valid span context out of thin air { ctx := ootaProp.Extract(bg, ns) - sc := otel.RemoteSpanContextFromContext(ctx) + sc := trace.RemoteSpanContextFromContext(ctx) require.True(t, sc.IsValid(), "oota prop failed sanity check") } // sanity check for real propagators, ensuring that they @@ -104,13 +105,13 @@ func TestMultiplePropagators(t *testing.T) { // go context in absence of the HTTP headers. for _, prop := range testProps { ctx := prop.Extract(bg, ns) - sc := otel.RemoteSpanContextFromContext(ctx) + sc := trace.RemoteSpanContextFromContext(ctx) require.Falsef(t, sc.IsValid(), "%#v failed sanity check", prop) } for _, prop := range testProps { props := otel.NewCompositeTextMapPropagator(ootaProp, prop) ctx := props.Extract(bg, ns) - sc := otel.RemoteSpanContextFromContext(ctx) + sc := trace.RemoteSpanContextFromContext(ctx) assert.Truef(t, sc.IsValid(), "%#v clobbers span context", prop) } } diff --git a/propagators/trace_context.go b/propagators/trace_context.go index b93c59bcf27..0e25da785b5 100644 --- a/propagators/trace_context.go +++ b/propagators/trace_context.go @@ -21,6 +21,7 @@ import ( "regexp" "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" ) const ( @@ -56,7 +57,7 @@ func (tc TraceContext) Inject(ctx context.Context, carrier otel.TextMapCarrier) carrier.Set(tracestateHeader, state) } - sc := otel.SpanContextFromContext(ctx) + sc := trace.SpanContextFromContext(ctx) if !sc.IsValid() { return } @@ -64,7 +65,7 @@ func (tc TraceContext) Inject(ctx context.Context, carrier otel.TextMapCarrier) supportedVersion, sc.TraceID, sc.SpanID, - sc.TraceFlags&otel.FlagsSampled) + sc.TraceFlags&trace.FlagsSampled) carrier.Set(traceparentHeader, h) } @@ -79,72 +80,72 @@ func (tc TraceContext) Extract(ctx context.Context, carrier otel.TextMapCarrier) if !sc.IsValid() { return ctx } - return otel.ContextWithRemoteSpanContext(ctx, sc) + return trace.ContextWithRemoteSpanContext(ctx, sc) } -func (tc TraceContext) extract(carrier otel.TextMapCarrier) otel.SpanContext { +func (tc TraceContext) extract(carrier otel.TextMapCarrier) trace.SpanContext { h := carrier.Get(traceparentHeader) if h == "" { - return otel.SpanContext{} + return trace.SpanContext{} } matches := traceCtxRegExp.FindStringSubmatch(h) if len(matches) == 0 { - return otel.SpanContext{} + return trace.SpanContext{} } if len(matches) < 5 { // four subgroups plus the overall match - return otel.SpanContext{} + return trace.SpanContext{} } if len(matches[1]) != 2 { - return otel.SpanContext{} + return trace.SpanContext{} } ver, err := hex.DecodeString(matches[1]) if err != nil { - return otel.SpanContext{} + return trace.SpanContext{} } version := int(ver[0]) if version > maxVersion { - return otel.SpanContext{} + return trace.SpanContext{} } if version == 0 && len(matches) != 5 { // four subgroups plus the overall match - return otel.SpanContext{} + return trace.SpanContext{} } if len(matches[2]) != 32 { - return otel.SpanContext{} + return trace.SpanContext{} } - var sc otel.SpanContext + var sc trace.SpanContext - sc.TraceID, err = otel.TraceIDFromHex(matches[2][:32]) + sc.TraceID, err = trace.TraceIDFromHex(matches[2][:32]) if err != nil { - return otel.SpanContext{} + return trace.SpanContext{} } if len(matches[3]) != 16 { - return otel.SpanContext{} + return trace.SpanContext{} } - sc.SpanID, err = otel.SpanIDFromHex(matches[3]) + sc.SpanID, err = trace.SpanIDFromHex(matches[3]) if err != nil { - return otel.SpanContext{} + return trace.SpanContext{} } if len(matches[4]) != 2 { - return otel.SpanContext{} + return trace.SpanContext{} } opts, err := hex.DecodeString(matches[4]) if err != nil || len(opts) < 1 || (version == 0 && opts[0] > 2) { - return otel.SpanContext{} + return trace.SpanContext{} } // Clear all flags other than the trace-context supported sampling bit. - sc.TraceFlags = opts[0] & otel.FlagsSampled + sc.TraceFlags = opts[0] & trace.FlagsSampled if !sc.IsValid() { - return otel.SpanContext{} + return trace.SpanContext{} } return sc diff --git a/propagators/trace_context_benchmark_test.go b/propagators/trace_context_benchmark_test.go index 3f5ff715567..ba029cb481c 100644 --- a/propagators/trace_context_benchmark_test.go +++ b/propagators/trace_context_benchmark_test.go @@ -19,9 +19,9 @@ import ( "net/http" "testing" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/oteltest" "go.opentelemetry.io/otel/propagators" + "go.opentelemetry.io/otel/trace" ) func BenchmarkInject(b *testing.B) { @@ -38,17 +38,17 @@ func BenchmarkInject(b *testing.B) { func injectSubBenchmarks(b *testing.B, fn func(context.Context, *testing.B)) { b.Run("SampledSpanContext", func(b *testing.B) { - spanID, _ := otel.SpanIDFromHex("00f067aa0ba902b7") - traceID, _ := otel.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") + spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7") + traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") mockTracer := oteltest.DefaultTracer() b.ReportAllocs() - sc := otel.SpanContext{ + sc := trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: otel.FlagsSampled, + TraceFlags: trace.FlagsSampled, } - ctx := otel.ContextWithRemoteSpanContext(context.Background(), sc) + ctx := trace.ContextWithRemoteSpanContext(context.Background(), sc) ctx, _ = mockTracer.Start(ctx, "inject") fn(ctx, b) }) diff --git a/propagators/trace_context_test.go b/propagators/trace_context_test.go index d63c8b9f2a2..b32460ed241 100644 --- a/propagators/trace_context_test.go +++ b/propagators/trace_context_test.go @@ -21,9 +21,9 @@ import ( "github.com/google/go-cmp/cmp" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/oteltest" "go.opentelemetry.io/otel/propagators" + "go.opentelemetry.io/otel/trace" ) func TestExtractValidTraceContextFromHTTPReq(t *testing.T) { @@ -31,12 +31,12 @@ func TestExtractValidTraceContextFromHTTPReq(t *testing.T) { tests := []struct { name string header string - wantSc otel.SpanContext + wantSc trace.SpanContext }{ { name: "valid w3cHeader", header: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00", - wantSc: otel.SpanContext{ + wantSc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, }, @@ -44,34 +44,34 @@ func TestExtractValidTraceContextFromHTTPReq(t *testing.T) { { name: "valid w3cHeader and sampled", header: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", - wantSc: otel.SpanContext{ + wantSc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: otel.FlagsSampled, + TraceFlags: trace.FlagsSampled, }, }, { name: "future version", header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", - wantSc: otel.SpanContext{ + wantSc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: otel.FlagsSampled, + TraceFlags: trace.FlagsSampled, }, }, { name: "future options with sampled bit set", header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09", - wantSc: otel.SpanContext{ + wantSc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: otel.FlagsSampled, + TraceFlags: trace.FlagsSampled, }, }, { name: "future options with sampled bit cleared", header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-08", - wantSc: otel.SpanContext{ + wantSc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, }, @@ -79,28 +79,28 @@ func TestExtractValidTraceContextFromHTTPReq(t *testing.T) { { name: "future additional data", header: "02-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09-XYZxsf09", - wantSc: otel.SpanContext{ + wantSc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: otel.FlagsSampled, + TraceFlags: trace.FlagsSampled, }, }, { name: "valid b3Header ending in dash", header: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01-", - wantSc: otel.SpanContext{ + wantSc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: otel.FlagsSampled, + TraceFlags: trace.FlagsSampled, }, }, { name: "future valid b3Header ending in dash", header: "01-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-09-", - wantSc: otel.SpanContext{ + wantSc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: otel.FlagsSampled, + TraceFlags: trace.FlagsSampled, }, }, } @@ -112,7 +112,7 @@ func TestExtractValidTraceContextFromHTTPReq(t *testing.T) { ctx := context.Background() ctx = prop.Extract(ctx, req.Header) - gotSc := otel.RemoteSpanContextFromContext(ctx) + gotSc := trace.RemoteSpanContextFromContext(ctx) if diff := cmp.Diff(gotSc, tt.wantSc); diff != "" { t.Errorf("Extract Tracecontext: %s: -got +want %s", tt.name, diff) } @@ -121,7 +121,7 @@ func TestExtractValidTraceContextFromHTTPReq(t *testing.T) { } func TestExtractInvalidTraceContextFromHTTPReq(t *testing.T) { - wantSc := otel.SpanContext{} + wantSc := trace.SpanContext{} prop := propagators.TraceContext{} tests := []struct { name string @@ -200,7 +200,7 @@ func TestExtractInvalidTraceContextFromHTTPReq(t *testing.T) { ctx := context.Background() ctx = prop.Extract(ctx, req.Header) - gotSc := otel.RemoteSpanContextFromContext(ctx) + gotSc := trace.RemoteSpanContextFromContext(ctx) if diff := cmp.Diff(gotSc, wantSc); diff != "" { t.Errorf("Extract Tracecontext: %s: -got +want %s", tt.name, diff) } @@ -213,21 +213,21 @@ func TestInjectTraceContextToHTTPReq(t *testing.T) { prop := propagators.TraceContext{} tests := []struct { name string - sc otel.SpanContext + sc trace.SpanContext wantHeader string }{ { name: "valid spancontext, sampled", - sc: otel.SpanContext{ + sc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: otel.FlagsSampled, + TraceFlags: trace.FlagsSampled, }, wantHeader: "00-4bf92f3577b34da6a3ce929d0e0e4736-0000000000000002-01", }, { name: "valid spancontext, not sampled", - sc: otel.SpanContext{ + sc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, }, @@ -235,7 +235,7 @@ func TestInjectTraceContextToHTTPReq(t *testing.T) { }, { name: "valid spancontext, with unsupported bit set in traceflags", - sc: otel.SpanContext{ + sc: trace.SpanContext{ TraceID: traceID, SpanID: spanID, TraceFlags: 0xff, @@ -244,7 +244,7 @@ func TestInjectTraceContextToHTTPReq(t *testing.T) { }, { name: "invalid spancontext", - sc: otel.SpanContext{}, + sc: trace.SpanContext{}, wantHeader: "", }, } @@ -253,7 +253,7 @@ func TestInjectTraceContextToHTTPReq(t *testing.T) { req, _ := http.NewRequest("GET", "http://example.com", nil) ctx := context.Background() if tt.sc.IsValid() { - ctx = otel.ContextWithRemoteSpanContext(ctx, tt.sc) + ctx = trace.ContextWithRemoteSpanContext(ctx, tt.sc) ctx, _ = mockTracer.Start(ctx, "inject") } prop.Inject(ctx, req.Header) diff --git a/sdk/export/metric/aggregation/aggregation.go b/sdk/export/metric/aggregation/aggregation.go index e81e9012722..7f76b0baeb9 100644 --- a/sdk/export/metric/aggregation/aggregation.go +++ b/sdk/export/metric/aggregation/aggregation.go @@ -18,7 +18,7 @@ import ( "fmt" "time" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric/number" ) // These interfaces describe the various ways to access state from an @@ -37,7 +37,7 @@ type ( // Sum returns an aggregated sum. Sum interface { Aggregation - Sum() (otel.Number, error) + Sum() (number.Number, error) } // Count returns the number of values that were aggregated. @@ -49,32 +49,32 @@ type ( // Min returns the minimum value over the set of values that were aggregated. Min interface { Aggregation - Min() (otel.Number, error) + Min() (number.Number, error) } // Max returns the maximum value over the set of values that were aggregated. Max interface { Aggregation - Max() (otel.Number, error) + Max() (number.Number, error) } // Quantile returns an exact or estimated quantile over the // set of values that were aggregated. Quantile interface { Aggregation - Quantile(float64) (otel.Number, error) + Quantile(float64) (number.Number, error) } // LastValue returns the latest value that was aggregated. LastValue interface { Aggregation - LastValue() (otel.Number, time.Time, error) + LastValue() (number.Number, time.Time, error) } // Points returns the raw set of values that were aggregated. Points interface { Aggregation - Points() ([]otel.Number, error) + Points() ([]number.Number, error) } // Buckets represents histogram buckets boundaries and counts. @@ -96,16 +96,16 @@ type ( Histogram interface { Aggregation Count() (int64, error) - Sum() (otel.Number, error) + Sum() (number.Number, error) Histogram() (Buckets, error) } // MinMaxSumCount supports the Min, Max, Sum, and Count interfaces. MinMaxSumCount interface { Aggregation - Min() (otel.Number, error) - Max() (otel.Number, error) - Sum() (otel.Number, error) + Min() (number.Number, error) + Max() (number.Number, error) + Sum() (number.Number, error) Count() (int64, error) } @@ -113,11 +113,11 @@ type ( // interfaces. Distribution interface { Aggregation - Min() (otel.Number, error) - Max() (otel.Number, error) - Sum() (otel.Number, error) + Min() (number.Number, error) + Max() (number.Number, error) + Sum() (number.Number, error) Count() (int64, error) - Quantile(float64) (otel.Number, error) + Quantile(float64) (number.Number, error) } ) diff --git a/sdk/export/metric/exportkind_string.go b/sdk/export/metric/exportkind_string.go index c2f8bcf8dff..a92c1c1f2de 100644 --- a/sdk/export/metric/exportkind_string.go +++ b/sdk/export/metric/exportkind_string.go @@ -8,28 +8,18 @@ func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} - _ = x[CumulativeExporter-1] - _ = x[DeltaExporter-2] - _ = x[PassThroughExporter-4] + _ = x[CumulativeExportKind-1] + _ = x[DeltaExportKind-2] } -const ( - _ExportKind_name_0 = "CumulativeExporterDeltaExporter" - _ExportKind_name_1 = "PassThroughExporter" -) +const _ExportKind_name = "CumulativeExportKindDeltaExportKind" -var ( - _ExportKind_index_0 = [...]uint8{0, 18, 31} -) +var _ExportKind_index = [...]uint8{0, 20, 35} func (i ExportKind) String() string { - switch { - case 1 <= i && i <= 2: - i -= 1 - return _ExportKind_name_0[_ExportKind_index_0[i]:_ExportKind_index_0[i+1]] - case i == 4: - return _ExportKind_name_1 - default: - return "ExportKind(" + strconv.FormatInt(int64(i), 10) + ")" + i -= 1 + if i < 0 || i >= ExportKind(len(_ExportKind_index)-1) { + return "ExportKind(" + strconv.FormatInt(int64(i+1), 10) + ")" } + return _ExportKind_name[_ExportKind_index[i]:_ExportKind_index[i+1]] } diff --git a/sdk/export/metric/exportkind_test.go b/sdk/export/metric/exportkind_test.go index 19ef5542ae4..acaa12cd1dc 100644 --- a/sdk/export/metric/exportkind_test.go +++ b/sdk/export/metric/exportkind_test.go @@ -19,46 +19,56 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" ) -func TestExportKindIdentity(t *testing.T) { - akind := aggregation.Kind("Noop") - - require.Equal(t, CumulativeExporter, CumulativeExporter.ExportKindFor(nil, akind)) - require.Equal(t, DeltaExporter, DeltaExporter.ExportKindFor(nil, akind)) - require.Equal(t, PassThroughExporter, PassThroughExporter.ExportKindFor(nil, akind)) -} - func TestExportKindIncludes(t *testing.T) { - require.True(t, CumulativeExporter.Includes(CumulativeExporter)) - require.True(t, DeltaExporter.Includes(CumulativeExporter|DeltaExporter)) - require.False(t, DeltaExporter.Includes(PassThroughExporter|CumulativeExporter)) + require.True(t, CumulativeExportKind.Includes(CumulativeExportKind)) + require.True(t, DeltaExportKind.Includes(CumulativeExportKind|DeltaExportKind)) } -var deltaMemoryKinds = []otel.InstrumentKind{ - otel.SumObserverInstrumentKind, - otel.UpDownSumObserverInstrumentKind, +var deltaMemoryKinds = []metric.InstrumentKind{ + metric.SumObserverInstrumentKind, + metric.UpDownSumObserverInstrumentKind, } -var cumulativeMemoryKinds = []otel.InstrumentKind{ - otel.ValueRecorderInstrumentKind, - otel.ValueObserverInstrumentKind, - otel.CounterInstrumentKind, - otel.UpDownCounterInstrumentKind, +var cumulativeMemoryKinds = []metric.InstrumentKind{ + metric.ValueRecorderInstrumentKind, + metric.ValueObserverInstrumentKind, + metric.CounterInstrumentKind, + metric.UpDownCounterInstrumentKind, } func TestExportKindMemoryRequired(t *testing.T) { for _, kind := range deltaMemoryKinds { - require.True(t, DeltaExporter.MemoryRequired(kind)) - require.False(t, CumulativeExporter.MemoryRequired(kind)) - require.False(t, PassThroughExporter.MemoryRequired(kind)) + require.True(t, DeltaExportKind.MemoryRequired(kind)) + require.False(t, CumulativeExportKind.MemoryRequired(kind)) } for _, kind := range cumulativeMemoryKinds { - require.True(t, CumulativeExporter.MemoryRequired(kind)) - require.False(t, DeltaExporter.MemoryRequired(kind)) - require.False(t, PassThroughExporter.MemoryRequired(kind)) + require.True(t, CumulativeExportKind.MemoryRequired(kind)) + require.False(t, DeltaExportKind.MemoryRequired(kind)) + } +} + +func TestExportKindSelectors(t *testing.T) { + ceks := CumulativeExportKindSelector() + deks := DeltaExportKindSelector() + seks := StatelessExportKindSelector() + + for _, ikind := range append(deltaMemoryKinds, cumulativeMemoryKinds...) { + desc := metric.NewDescriptor("instrument", ikind, number.Int64Kind) + + var akind aggregation.Kind + if ikind.Adding() { + akind = aggregation.SumKind + } else { + akind = aggregation.HistogramKind + } + require.Equal(t, CumulativeExportKind, ceks.ExportKindFor(&desc, akind)) + require.Equal(t, DeltaExportKind, deks.ExportKindFor(&desc, akind)) + require.False(t, seks.ExportKindFor(&desc, akind).MemoryRequired(ikind)) } } diff --git a/sdk/export/metric/metric.go b/sdk/export/metric/metric.go index 1f7fa5e5077..6a089601968 100644 --- a/sdk/export/metric/metric.go +++ b/sdk/export/metric/metric.go @@ -21,8 +21,9 @@ import ( "sync" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/resource" ) @@ -94,7 +95,7 @@ type AggregatorSelector interface { // Note: This is context-free because the aggregator should // not relate to the incoming context. This call should not // block. - AggregatorFor(descriptor *otel.Descriptor, aggregator ...*Aggregator) + AggregatorFor(descriptor *metric.Descriptor, aggregator ...*Aggregator) } // Checkpointer is the interface used by a Controller to coordinate @@ -152,7 +153,7 @@ type Aggregator interface { // // The Context argument comes from user-level code and could be // inspected for a `correlation.Map` or `trace.SpanContext`. - Update(ctx context.Context, number otel.Number, descriptor *otel.Descriptor) error + Update(ctx context.Context, number number.Number, descriptor *metric.Descriptor) error // SynchronizedMove is called during collection to finish one // period of aggregation by atomically saving the @@ -173,7 +174,7 @@ type Aggregator interface { // // This call has no Context argument because it is expected to // perform only computation. - SynchronizedMove(destination Aggregator, descriptor *otel.Descriptor) error + SynchronizedMove(destination Aggregator, descriptor *metric.Descriptor) error // Merge combines the checkpointed state from the argument // Aggregator into this Aggregator. Merge is not synchronized @@ -181,7 +182,7 @@ type Aggregator interface { // // The owner of an Aggregator being merged is responsible for // synchronization of both Aggregator states. - Merge(aggregator Aggregator, descriptor *otel.Descriptor) error + Merge(aggregator Aggregator, descriptor *metric.Descriptor) error } // Subtractor is an optional interface implemented by some @@ -191,7 +192,7 @@ type Aggregator interface { type Subtractor interface { // Subtract subtracts the `operand` from this Aggregator and // outputs the value in `result`. - Subtract(operand, result Aggregator, descriptor *otel.Descriptor) error + Subtract(operand, result Aggregator, descriptor *metric.Descriptor) error } // Exporter handles presentation of the checkpoint of aggregate @@ -221,7 +222,7 @@ type ExportKindSelector interface { // ExportKindFor should return the correct ExportKind that // should be used when exporting data for the given metric // instrument and Aggregator kind. - ExportKindFor(descriptor *otel.Descriptor, aggregatorKind aggregation.Kind) ExportKind + ExportKindFor(descriptor *metric.Descriptor, aggregatorKind aggregation.Kind) ExportKind } // CheckpointSet allows a controller to access a complete checkpoint of @@ -262,7 +263,7 @@ type CheckpointSet interface { // are shared by the Accumulator->Processor and Processor->Exporter // steps. type Metadata struct { - descriptor *otel.Descriptor + descriptor *metric.Descriptor labels *label.Set resource *resource.Resource } @@ -285,7 +286,7 @@ type Record struct { } // Descriptor describes the metric instrument being exported. -func (m Metadata) Descriptor() *otel.Descriptor { +func (m Metadata) Descriptor() *metric.Descriptor { return m.descriptor } @@ -304,7 +305,7 @@ func (m Metadata) Resource() *resource.Resource { // Accumulations to send to Processors. The Descriptor, Labels, Resource, // and Aggregator represent aggregate metric events received over a single // collection period. -func NewAccumulation(descriptor *otel.Descriptor, labels *label.Set, resource *resource.Resource, aggregator Aggregator) Accumulation { +func NewAccumulation(descriptor *metric.Descriptor, labels *label.Set, resource *resource.Resource, aggregator Aggregator) Accumulation { return Accumulation{ Metadata: Metadata{ descriptor: descriptor, @@ -324,7 +325,7 @@ func (r Accumulation) Aggregator() Aggregator { // NewRecord allows Processor implementations to construct export // records. The Descriptor, Labels, and Aggregator represent // aggregate metric events received over a single collection period. -func NewRecord(descriptor *otel.Descriptor, labels *label.Set, resource *resource.Resource, aggregation aggregation.Aggregation, start, end time.Time) Record { +func NewRecord(descriptor *metric.Descriptor, labels *label.Set, resource *resource.Resource, aggregation aggregation.Aggregation, start, end time.Time) Record { return Record{ Metadata: Metadata{ descriptor: descriptor, @@ -358,18 +359,13 @@ func (r Record) EndTime() time.Time { type ExportKind int const ( - // CumulativeExporter indicates that the Exporter expects a + // CumulativeExportKind indicates that an Exporter expects a // Cumulative Aggregation. - CumulativeExporter ExportKind = 1 // e.g., Prometheus + CumulativeExportKind ExportKind = 1 - // DeltaExporter indicates that the Exporter expects a + // DeltaExportKind indicates that an Exporter expects a // Delta Aggregation. - DeltaExporter ExportKind = 2 // e.g., StatsD - - // PassThroughExporter indicates that the Exporter expects - // either a Cumulative or a Delta Aggregation, whichever does - // not require maintaining state for the given instrument. - PassThroughExporter ExportKind = 4 // e.g., OTLP + DeltaExportKind ExportKind = 2 ) // Includes tests whether `kind` includes a specific kind of @@ -378,26 +374,69 @@ func (kind ExportKind) Includes(has ExportKind) bool { return kind&has != 0 } -// ExportKindFor returns a constant, as an implementation of ExportKindSelector. -func (kind ExportKind) ExportKindFor(_ *otel.Descriptor, _ aggregation.Kind) ExportKind { - return kind -} - // MemoryRequired returns whether an exporter of this kind requires // memory to export correctly. -func (kind ExportKind) MemoryRequired(mkind otel.InstrumentKind) bool { +func (kind ExportKind) MemoryRequired(mkind metric.InstrumentKind) bool { switch mkind { - case otel.ValueRecorderInstrumentKind, otel.ValueObserverInstrumentKind, - otel.CounterInstrumentKind, otel.UpDownCounterInstrumentKind: + case metric.ValueRecorderInstrumentKind, metric.ValueObserverInstrumentKind, + metric.CounterInstrumentKind, metric.UpDownCounterInstrumentKind: // Delta-oriented instruments: - return kind.Includes(CumulativeExporter) + return kind.Includes(CumulativeExportKind) - case otel.SumObserverInstrumentKind, otel.UpDownSumObserverInstrumentKind: + case metric.SumObserverInstrumentKind, metric.UpDownSumObserverInstrumentKind: // Cumulative-oriented instruments: - return kind.Includes(DeltaExporter) + return kind.Includes(DeltaExportKind) } // Something unexpected is happening--we could panic. This // will become an error when the exporter tries to access a // checkpoint, presumably, so let it be. return false } + +type ( + constantExportKindSelector ExportKind + statelessExportKindSelector struct{} +) + +var ( + _ ExportKindSelector = constantExportKindSelector(0) + _ ExportKindSelector = statelessExportKindSelector{} +) + +// ConstantExportKindSelector returns an ExportKindSelector that returns +// a constant ExportKind, one that is either always cumulative or always delta. +func ConstantExportKindSelector(kind ExportKind) ExportKindSelector { + return constantExportKindSelector(kind) +} + +// CumulativeExportKindSelector returns an ExportKindSelector that +// always returns CumulativeExportKind. +func CumulativeExportKindSelector() ExportKindSelector { + return ConstantExportKindSelector(CumulativeExportKind) +} + +// DeltaExportKindSelector returns an ExportKindSelector that +// always returns DeltaExportKind. +func DeltaExportKindSelector() ExportKindSelector { + return ConstantExportKindSelector(DeltaExportKind) +} + +// StatelessExportKindSelector returns an ExportKindSelector that +// always returns the ExportKind that avoids long-term memory +// requirements. +func StatelessExportKindSelector() ExportKindSelector { + return statelessExportKindSelector{} +} + +// ExportKindFor implements ExportKindSelector. +func (c constantExportKindSelector) ExportKindFor(_ *metric.Descriptor, _ aggregation.Kind) ExportKind { + return ExportKind(c) +} + +// ExportKindFor implements ExportKindSelector. +func (s statelessExportKindSelector) ExportKindFor(desc *metric.Descriptor, kind aggregation.Kind) ExportKind { + if kind == aggregation.SumKind && desc.InstrumentKind().PrecomputedSum() { + return CumulativeExportKind + } + return DeltaExportKind +} diff --git a/sdk/export/metric/metrictest/test.go b/sdk/export/metric/metrictest/test.go index c9235a40915..9905300d893 100644 --- a/sdk/export/metric/metrictest/test.go +++ b/sdk/export/metric/metrictest/test.go @@ -21,15 +21,16 @@ import ( "sync" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/resource" ) type mapkey struct { - desc *otel.Descriptor + desc *metric.Descriptor distinct label.Distinct } @@ -48,17 +49,17 @@ type NoopAggregator struct{} var _ export.Aggregator = (*NoopAggregator)(nil) // Update implements export.Aggregator. -func (NoopAggregator) Update(context.Context, otel.Number, *otel.Descriptor) error { +func (NoopAggregator) Update(context.Context, number.Number, *metric.Descriptor) error { return nil } // SynchronizedMove implements export.Aggregator. -func (NoopAggregator) SynchronizedMove(export.Aggregator, *otel.Descriptor) error { +func (NoopAggregator) SynchronizedMove(export.Aggregator, *metric.Descriptor) error { return nil } // Merge implements export.Aggregator. -func (NoopAggregator) Merge(export.Aggregator, *otel.Descriptor) error { +func (NoopAggregator) Merge(export.Aggregator, *metric.Descriptor) error { return nil } @@ -91,7 +92,7 @@ func (p *CheckpointSet) Reset() { // // If there is an existing record with the same descriptor and labels, // the stored aggregator will be returned and should be merged. -func (p *CheckpointSet) Add(desc *otel.Descriptor, newAgg export.Aggregator, labels ...label.KeyValue) (agg export.Aggregator, added bool) { +func (p *CheckpointSet) Add(desc *metric.Descriptor, newAgg export.Aggregator, labels ...label.KeyValue) (agg export.Aggregator, added bool) { elabels := label.NewSet(labels...) key := mapkey{ diff --git a/sdk/export/trace/trace.go b/sdk/export/trace/trace.go index 83a0b1c28e7..a9883bff73f 100644 --- a/sdk/export/trace/trace.go +++ b/sdk/export/trace/trace.go @@ -18,9 +18,10 @@ import ( "context" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" + "go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/resource" ) @@ -49,9 +50,9 @@ type SpanExporter interface { // SpanData contains all the information collected by a completed span. type SpanData struct { - SpanContext otel.SpanContext - ParentSpanID otel.SpanID - SpanKind otel.SpanKind + SpanContext trace.SpanContext + ParentSpanID trace.SpanID + SpanKind trace.SpanKind Name string StartTime time.Time // The wall clock time of EndTime will be adjusted to always be offset @@ -59,7 +60,7 @@ type SpanData struct { EndTime time.Time Attributes []label.KeyValue MessageEvents []Event - Links []otel.Link + Links []trace.Link StatusCode codes.Code StatusMessage string HasRemoteParent bool diff --git a/sdk/metric/aggregator/aggregator.go b/sdk/metric/aggregator/aggregator.go index 6393f42fe74..0539a0fd79b 100644 --- a/sdk/metric/aggregator/aggregator.go +++ b/sdk/metric/aggregator/aggregator.go @@ -18,7 +18,8 @@ import ( "fmt" "math" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" ) @@ -34,16 +35,16 @@ func NewInconsistentAggregatorError(a1, a2 export.Aggregator) error { // This rejects NaN values. This rejects negative values when the // metric instrument does not support negative values, including // monotonic counter metrics and absolute ValueRecorder metrics. -func RangeTest(number otel.Number, descriptor *otel.Descriptor) error { +func RangeTest(num number.Number, descriptor *metric.Descriptor) error { numberKind := descriptor.NumberKind() - if numberKind == otel.Float64NumberKind && math.IsNaN(number.AsFloat64()) { + if numberKind == number.Float64Kind && math.IsNaN(num.AsFloat64()) { return aggregation.ErrNaNInput } switch descriptor.InstrumentKind() { - case otel.CounterInstrumentKind, otel.SumObserverInstrumentKind: - if number.IsNegative(numberKind) { + case metric.CounterInstrumentKind, metric.SumObserverInstrumentKind: + if num.IsNegative(numberKind) { return aggregation.ErrNegativeInput } } diff --git a/sdk/metric/aggregator/aggregator_test.go b/sdk/metric/aggregator/aggregator_test.go index 0cc94387ad9..674d08cd03c 100644 --- a/sdk/metric/aggregator/aggregator_test.go +++ b/sdk/metric/aggregator/aggregator_test.go @@ -21,7 +21,8 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator" "go.opentelemetry.io/otel/sdk/metric/aggregator/lastvalue" @@ -38,27 +39,27 @@ func TestInconsistentAggregatorErr(t *testing.T) { require.True(t, errors.Is(err, aggregation.ErrInconsistentType)) } -func testRangeNaN(t *testing.T, desc *otel.Descriptor) { +func testRangeNaN(t *testing.T, desc *metric.Descriptor) { // If the descriptor uses int64 numbers, this won't register as NaN - nan := otel.NewFloat64Number(math.NaN()) + nan := number.NewFloat64Number(math.NaN()) err := aggregator.RangeTest(nan, desc) - if desc.NumberKind() == otel.Float64NumberKind { + if desc.NumberKind() == number.Float64Kind { require.Equal(t, aggregation.ErrNaNInput, err) } else { require.Nil(t, err) } } -func testRangeNegative(t *testing.T, desc *otel.Descriptor) { - var neg, pos otel.Number +func testRangeNegative(t *testing.T, desc *metric.Descriptor) { + var neg, pos number.Number - if desc.NumberKind() == otel.Float64NumberKind { - pos = otel.NewFloat64Number(+1) - neg = otel.NewFloat64Number(-1) + if desc.NumberKind() == number.Float64Kind { + pos = number.NewFloat64Number(+1) + neg = number.NewFloat64Number(-1) } else { - pos = otel.NewInt64Number(+1) - neg = otel.NewInt64Number(-1) + pos = number.NewInt64Number(+1) + neg = number.NewInt64Number(-1) } posErr := aggregator.RangeTest(pos, desc) @@ -70,11 +71,11 @@ func testRangeNegative(t *testing.T, desc *otel.Descriptor) { func TestRangeTest(t *testing.T) { // Only Counters implement a range test. - for _, nkind := range []otel.NumberKind{otel.Float64NumberKind, otel.Int64NumberKind} { + for _, nkind := range []number.Kind{number.Float64Kind, number.Int64Kind} { t.Run(nkind.String(), func(t *testing.T) { - desc := otel.NewDescriptor( + desc := metric.NewDescriptor( "name", - otel.CounterInstrumentKind, + metric.CounterInstrumentKind, nkind, ) testRangeNegative(t, &desc) @@ -83,14 +84,14 @@ func TestRangeTest(t *testing.T) { } func TestNaNTest(t *testing.T) { - for _, nkind := range []otel.NumberKind{otel.Float64NumberKind, otel.Int64NumberKind} { + for _, nkind := range []number.Kind{number.Float64Kind, number.Int64Kind} { t.Run(nkind.String(), func(t *testing.T) { - for _, mkind := range []otel.InstrumentKind{ - otel.CounterInstrumentKind, - otel.ValueRecorderInstrumentKind, - otel.ValueObserverInstrumentKind, + for _, mkind := range []metric.InstrumentKind{ + metric.CounterInstrumentKind, + metric.ValueRecorderInstrumentKind, + metric.ValueObserverInstrumentKind, } { - desc := otel.NewDescriptor( + desc := metric.NewDescriptor( "name", mkind, nkind, diff --git a/sdk/metric/aggregator/aggregatortest/test.go b/sdk/metric/aggregator/aggregatortest/test.go index b097314769e..1b12032f07f 100644 --- a/sdk/metric/aggregator/aggregatortest/test.go +++ b/sdk/metric/aggregator/aggregatortest/test.go @@ -22,8 +22,9 @@ import ( "testing" "unsafe" - "go.opentelemetry.io/otel" ottest "go.opentelemetry.io/otel/internal/testing" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/metric/aggregator" ) @@ -31,30 +32,30 @@ import ( const Magnitude = 1000 type Profile struct { - NumberKind otel.NumberKind - Random func(sign int) otel.Number + NumberKind number.Kind + Random func(sign int) number.Number } func newProfiles() []Profile { rnd := rand.New(rand.NewSource(rand.Int63())) return []Profile{ { - NumberKind: otel.Int64NumberKind, - Random: func(sign int) otel.Number { - return otel.NewInt64Number(int64(sign) * int64(rnd.Intn(Magnitude+1))) + NumberKind: number.Int64Kind, + Random: func(sign int) number.Number { + return number.NewInt64Number(int64(sign) * int64(rnd.Intn(Magnitude+1))) }, }, { - NumberKind: otel.Float64NumberKind, - Random: func(sign int) otel.Number { - return otel.NewFloat64Number(float64(sign) * rnd.Float64() * Magnitude) + NumberKind: number.Float64Kind, + Random: func(sign int) number.Number { + return number.NewFloat64Number(float64(sign) * rnd.Float64() * Magnitude) }, }, } } -func NewAggregatorTest(mkind otel.InstrumentKind, nkind otel.NumberKind) *otel.Descriptor { - desc := otel.NewDescriptor("test.name", mkind, nkind) +func NewAggregatorTest(mkind metric.InstrumentKind, nkind number.Kind) *metric.Descriptor { + desc := metric.NewDescriptor("test.name", mkind, nkind) return &desc } @@ -85,17 +86,17 @@ func TestMain(m *testing.M) { type Numbers struct { // numbers has to be aligned for 64-bit atomic operations. - numbers []otel.Number - kind otel.NumberKind + numbers []number.Number + kind number.Kind } -func NewNumbers(kind otel.NumberKind) Numbers { +func NewNumbers(kind number.Kind) Numbers { return Numbers{ kind: kind, } } -func (n *Numbers) Append(v otel.Number) { +func (n *Numbers) Append(v number.Number) { n.numbers = append(n.numbers, v) } @@ -115,8 +116,8 @@ func (n *Numbers) Swap(i, j int) { n.numbers[i], n.numbers[j] = n.numbers[j], n.numbers[i] } -func (n *Numbers) Sum() otel.Number { - var sum otel.Number +func (n *Numbers) Sum() number.Number { + var sum number.Number for _, num := range n.numbers { sum.AddNumber(n.kind, num) } @@ -127,16 +128,16 @@ func (n *Numbers) Count() int64 { return int64(len(n.numbers)) } -func (n *Numbers) Min() otel.Number { +func (n *Numbers) Min() number.Number { return n.numbers[0] } -func (n *Numbers) Max() otel.Number { +func (n *Numbers) Max() number.Number { return n.numbers[len(n.numbers)-1] } // Median() is an alias for Quantile(0.5). -func (n *Numbers) Median() otel.Number { +func (n *Numbers) Median() number.Number { // Note that len(n.numbers) is 1 greater than the max element // index, so dividing by two rounds up. This gives the // intended definition for Quantile() in tests, which is to @@ -145,12 +146,12 @@ func (n *Numbers) Median() otel.Number { return n.numbers[len(n.numbers)/2] } -func (n *Numbers) Points() []otel.Number { +func (n *Numbers) Points() []number.Number { return n.numbers } // Performs the same range test the SDK does on behalf of the aggregator. -func CheckedUpdate(t *testing.T, agg export.Aggregator, number otel.Number, descriptor *otel.Descriptor) { +func CheckedUpdate(t *testing.T, agg export.Aggregator, number number.Number, descriptor *metric.Descriptor) { ctx := context.Background() // Note: Aggregator tests are written assuming that the SDK @@ -166,7 +167,7 @@ func CheckedUpdate(t *testing.T, agg export.Aggregator, number otel.Number, desc } } -func CheckedMerge(t *testing.T, aggInto, aggFrom export.Aggregator, descriptor *otel.Descriptor) { +func CheckedMerge(t *testing.T, aggInto, aggFrom export.Aggregator, descriptor *metric.Descriptor) { if err := aggInto.Merge(aggFrom, descriptor); err != nil { t.Error("Unexpected Merge failure", err) } diff --git a/sdk/metric/aggregator/array/array.go b/sdk/metric/aggregator/array/array.go index 5038aeededa..5346be36b0e 100644 --- a/sdk/metric/aggregator/array/array.go +++ b/sdk/metric/aggregator/array/array.go @@ -21,7 +21,8 @@ import ( "sync" "unsafe" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator" @@ -32,11 +33,11 @@ type ( // an array with the exact set of values. Aggregator struct { lock sync.Mutex - sum otel.Number + sum number.Number points points } - points []otel.Number + points []number.Number ) var _ export.Aggregator = &Aggregator{} @@ -62,7 +63,7 @@ func (c *Aggregator) Kind() aggregation.Kind { } // Sum returns the sum of values in the checkpoint. -func (c *Aggregator) Sum() (otel.Number, error) { +func (c *Aggregator) Sum() (number.Number, error) { return c.sum, nil } @@ -72,29 +73,29 @@ func (c *Aggregator) Count() (int64, error) { } // Max returns the maximum value in the checkpoint. -func (c *Aggregator) Max() (otel.Number, error) { +func (c *Aggregator) Max() (number.Number, error) { return c.points.Quantile(1) } // Min returns the mininum value in the checkpoint. -func (c *Aggregator) Min() (otel.Number, error) { +func (c *Aggregator) Min() (number.Number, error) { return c.points.Quantile(0) } // Quantile returns the estimated quantile of data in the checkpoint. // It is an error if `q` is less than 0 or greated than 1. -func (c *Aggregator) Quantile(q float64) (otel.Number, error) { +func (c *Aggregator) Quantile(q float64) (number.Number, error) { return c.points.Quantile(q) } // Points returns access to the raw data set. -func (c *Aggregator) Points() ([]otel.Number, error) { +func (c *Aggregator) Points() ([]number.Number, error) { return c.points, nil } // SynchronizedMove saves the current state to oa and resets the current state to // the empty set, taking a lock to prevent concurrent Update() calls. -func (c *Aggregator) SynchronizedMove(oa export.Aggregator, desc *otel.Descriptor) error { +func (c *Aggregator) SynchronizedMove(oa export.Aggregator, desc *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(c, oa) @@ -116,7 +117,7 @@ func (c *Aggregator) SynchronizedMove(oa export.Aggregator, desc *otel.Descripto // Update adds the recorded measurement to the current data set. // Update takes a lock to prevent concurrent Update() and SynchronizedMove() // calls. -func (c *Aggregator) Update(_ context.Context, number otel.Number, desc *otel.Descriptor) error { +func (c *Aggregator) Update(_ context.Context, number number.Number, desc *metric.Descriptor) error { c.lock.Lock() c.points = append(c.points, number) c.sum.AddNumber(desc.NumberKind(), number) @@ -126,7 +127,7 @@ func (c *Aggregator) Update(_ context.Context, number otel.Number, desc *otel.De } // Merge combines two data sets into one. -func (c *Aggregator) Merge(oa export.Aggregator, desc *otel.Descriptor) error { +func (c *Aggregator) Merge(oa export.Aggregator, desc *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(c, oa) @@ -140,12 +141,12 @@ func (c *Aggregator) Merge(oa export.Aggregator, desc *otel.Descriptor) error { return nil } -func (c *Aggregator) sort(kind otel.NumberKind) { +func (c *Aggregator) sort(kind number.Kind) { switch kind { - case otel.Float64NumberKind: + case number.Float64Kind: sort.Float64s(*(*[]float64)(unsafe.Pointer(&c.points))) - case otel.Int64NumberKind: + case number.Int64Kind: sort.Sort(&c.points) default: @@ -155,7 +156,7 @@ func (c *Aggregator) sort(kind otel.NumberKind) { } } -func combine(a, b points, kind otel.NumberKind) points { +func combine(a, b points, kind number.Kind) points { result := make(points, 0, len(a)+len(b)) for len(a) != 0 && len(b) != 0 { @@ -190,7 +191,7 @@ func (p *points) Swap(i, j int) { // Quantile returns the least X such that Pr(x=q, where X is an // element of the data set. This uses the "Nearest-Rank" definition // of a quantile. -func (p *points) Quantile(q float64) (otel.Number, error) { +func (p *points) Quantile(q float64) (number.Number, error) { if len(*p) == 0 { return 0, aggregation.ErrNoData } diff --git a/sdk/metric/aggregator/array/array_test.go b/sdk/metric/aggregator/array/array_test.go index 4ea1134b4fc..db32d9d603c 100644 --- a/sdk/metric/aggregator/array/array_test.go +++ b/sdk/metric/aggregator/array/array_test.go @@ -22,7 +22,8 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator/aggregatortest" ) @@ -31,7 +32,7 @@ type updateTest struct { count int } -func checkZero(t *testing.T, agg *Aggregator, desc *otel.Descriptor) { +func checkZero(t *testing.T, agg *Aggregator, desc *metric.Descriptor) { kind := desc.NumberKind() sum, err := agg.Sum() @@ -62,7 +63,7 @@ func new4() (_, _, _, _ *Aggregator) { } func (ut *updateTest) run(t *testing.T, profile aggregatortest.Profile) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) agg, ckpt := new2() all := aggregatortest.NewNumbers(profile.NumberKind) @@ -129,7 +130,7 @@ type mergeTest struct { } func (mt *mergeTest) run(t *testing.T, profile aggregatortest.Profile) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) agg1, agg2, ckpt1, ckpt2 := new4() all := aggregatortest.NewNumbers(profile.NumberKind) @@ -225,12 +226,12 @@ func TestArrayErrors(t *testing.T) { require.Error(t, err) require.Equal(t, err, aggregation.ErrNoData) - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) - aggregatortest.CheckedUpdate(t, agg, otel.Number(0), descriptor) + aggregatortest.CheckedUpdate(t, agg, number.Number(0), descriptor) - if profile.NumberKind == otel.Float64NumberKind { - aggregatortest.CheckedUpdate(t, agg, otel.NewFloat64Number(math.NaN()), descriptor) + if profile.NumberKind == number.Float64Kind { + aggregatortest.CheckedUpdate(t, agg, number.NewFloat64Number(math.NaN()), descriptor) } require.NoError(t, agg.SynchronizedMove(ckpt, descriptor)) @@ -240,7 +241,7 @@ func TestArrayErrors(t *testing.T) { num, err := ckpt.Quantile(0) require.Nil(t, err) - require.Equal(t, num, otel.Number(0)) + require.Equal(t, num, number.Number(0)) _, err = ckpt.Quantile(-0.0001) require.Error(t, err) @@ -253,7 +254,7 @@ func TestArrayErrors(t *testing.T) { } func TestArrayFloat64(t *testing.T) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, otel.Float64NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, number.Float64Kind) fpsf := func(sign int) []float64 { // Check behavior of a bunch of odd floating @@ -282,18 +283,18 @@ func TestArrayFloat64(t *testing.T) { } } - all := aggregatortest.NewNumbers(otel.Float64NumberKind) + all := aggregatortest.NewNumbers(number.Float64Kind) agg, ckpt := new2() for _, f := range fpsf(1) { - all.Append(otel.NewFloat64Number(f)) - aggregatortest.CheckedUpdate(t, agg, otel.NewFloat64Number(f), descriptor) + all.Append(number.NewFloat64Number(f)) + aggregatortest.CheckedUpdate(t, agg, number.NewFloat64Number(f), descriptor) } for _, f := range fpsf(-1) { - all.Append(otel.NewFloat64Number(f)) - aggregatortest.CheckedUpdate(t, agg, otel.NewFloat64Number(f), descriptor) + all.Append(number.NewFloat64Number(f)) + aggregatortest.CheckedUpdate(t, agg, number.NewFloat64Number(f), descriptor) } require.NoError(t, agg.SynchronizedMove(ckpt, descriptor)) diff --git a/sdk/metric/aggregator/ddsketch/ddsketch.go b/sdk/metric/aggregator/ddsketch/ddsketch.go index 6d35e3f2ea1..1e844f570fe 100644 --- a/sdk/metric/aggregator/ddsketch/ddsketch.go +++ b/sdk/metric/aggregator/ddsketch/ddsketch.go @@ -20,7 +20,8 @@ import ( sdk "github.com/DataDog/sketches-go/ddsketch" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator" @@ -33,7 +34,7 @@ type Config = sdk.Config type Aggregator struct { lock sync.Mutex cfg *Config - kind otel.NumberKind + kind number.Kind sketch *sdk.DDSketch } @@ -42,7 +43,7 @@ var _ aggregation.MinMaxSumCount = &Aggregator{} var _ aggregation.Distribution = &Aggregator{} // New returns a new DDSketch aggregator. -func New(cnt int, desc *otel.Descriptor, cfg *Config) []Aggregator { +func New(cnt int, desc *metric.Descriptor, cfg *Config) []Aggregator { if cfg == nil { cfg = NewDefaultConfig() } @@ -73,7 +74,7 @@ func NewDefaultConfig() *Config { } // Sum returns the sum of values in the checkpoint. -func (c *Aggregator) Sum() (otel.Number, error) { +func (c *Aggregator) Sum() (number.Number, error) { return c.toNumber(c.sketch.Sum()), nil } @@ -83,18 +84,18 @@ func (c *Aggregator) Count() (int64, error) { } // Max returns the maximum value in the checkpoint. -func (c *Aggregator) Max() (otel.Number, error) { +func (c *Aggregator) Max() (number.Number, error) { return c.Quantile(1) } // Min returns the minimum value in the checkpoint. -func (c *Aggregator) Min() (otel.Number, error) { +func (c *Aggregator) Min() (number.Number, error) { return c.Quantile(0) } // Quantile returns the estimated quantile of data in the checkpoint. // It is an error if `q` is less than 0 or greated than 1. -func (c *Aggregator) Quantile(q float64) (otel.Number, error) { +func (c *Aggregator) Quantile(q float64) (number.Number, error) { if c.sketch.Count() == 0 { return 0, aggregation.ErrNoData } @@ -105,16 +106,16 @@ func (c *Aggregator) Quantile(q float64) (otel.Number, error) { return c.toNumber(f), nil } -func (c *Aggregator) toNumber(f float64) otel.Number { - if c.kind == otel.Float64NumberKind { - return otel.NewFloat64Number(f) +func (c *Aggregator) toNumber(f float64) number.Number { + if c.kind == number.Float64Kind { + return number.NewFloat64Number(f) } - return otel.NewInt64Number(int64(f)) + return number.NewInt64Number(int64(f)) } // SynchronizedMove saves the current state into oa and resets the current state to // a new sketch, taking a lock to prevent concurrent Update() calls. -func (c *Aggregator) SynchronizedMove(oa export.Aggregator, _ *otel.Descriptor) error { +func (c *Aggregator) SynchronizedMove(oa export.Aggregator, _ *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(c, oa) @@ -131,7 +132,7 @@ func (c *Aggregator) SynchronizedMove(oa export.Aggregator, _ *otel.Descriptor) // Update adds the recorded measurement to the current data set. // Update takes a lock to prevent concurrent Update() and SynchronizedMove() // calls. -func (c *Aggregator) Update(_ context.Context, number otel.Number, desc *otel.Descriptor) error { +func (c *Aggregator) Update(_ context.Context, number number.Number, desc *metric.Descriptor) error { c.lock.Lock() defer c.lock.Unlock() c.sketch.Add(number.CoerceToFloat64(desc.NumberKind())) @@ -139,7 +140,7 @@ func (c *Aggregator) Update(_ context.Context, number otel.Number, desc *otel.De } // Merge combines two sketches into one. -func (c *Aggregator) Merge(oa export.Aggregator, d *otel.Descriptor) error { +func (c *Aggregator) Merge(oa export.Aggregator, d *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(c, oa) diff --git a/sdk/metric/aggregator/ddsketch/ddsketch_test.go b/sdk/metric/aggregator/ddsketch/ddsketch_test.go index fc21a042d51..63bcbab4675 100644 --- a/sdk/metric/aggregator/ddsketch/ddsketch_test.go +++ b/sdk/metric/aggregator/ddsketch/ddsketch_test.go @@ -21,7 +21,7 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator/aggregatortest" ) @@ -31,17 +31,17 @@ const count = 1000 type updateTest struct { } -func new2(desc *otel.Descriptor) (_, _ *Aggregator) { +func new2(desc *metric.Descriptor) (_, _ *Aggregator) { alloc := New(2, desc, NewDefaultConfig()) return &alloc[0], &alloc[1] } -func new4(desc *otel.Descriptor) (_, _, _, _ *Aggregator) { +func new4(desc *metric.Descriptor) (_, _, _, _ *Aggregator) { alloc := New(4, desc, NewDefaultConfig()) return &alloc[0], &alloc[1], &alloc[2], &alloc[3] } -func checkZero(t *testing.T, agg *Aggregator, desc *otel.Descriptor) { +func checkZero(t *testing.T, agg *Aggregator, desc *metric.Descriptor) { kind := desc.NumberKind() sum, err := agg.Sum() @@ -66,7 +66,7 @@ func checkZero(t *testing.T, agg *Aggregator, desc *otel.Descriptor) { } func (ut *updateTest) run(t *testing.T, profile aggregatortest.Profile) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) agg, ckpt := new2(descriptor) all := aggregatortest.NewNumbers(profile.NumberKind) @@ -127,7 +127,7 @@ type mergeTest struct { } func (mt *mergeTest) run(t *testing.T, profile aggregatortest.Profile) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) agg1, agg2, ckpt1, ckpt2 := new4(descriptor) diff --git a/sdk/metric/aggregator/histogram/benchmark_test.go b/sdk/metric/aggregator/histogram/benchmark_test.go index b554fea78bd..91fab848c92 100644 --- a/sdk/metric/aggregator/histogram/benchmark_test.go +++ b/sdk/metric/aggregator/histogram/benchmark_test.go @@ -19,7 +19,8 @@ import ( "math/rand" "testing" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/sdk/metric/aggregator/aggregatortest" "go.opentelemetry.io/otel/sdk/metric/aggregator/histogram" ) @@ -37,7 +38,7 @@ func benchmarkHistogramSearchFloat64(b *testing.B, size int) { for i := range values { values[i] = rand.Float64() * inputRange } - desc := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, otel.Float64NumberKind) + desc := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, number.Float64Kind) agg := &histogram.New(1, desc, boundaries)[0] ctx := context.Background() @@ -45,7 +46,7 @@ func benchmarkHistogramSearchFloat64(b *testing.B, size int) { b.ResetTimer() for i := 0; i < b.N; i++ { - _ = agg.Update(ctx, otel.NewFloat64Number(values[i]), desc) + _ = agg.Update(ctx, number.NewFloat64Number(values[i]), desc) } } @@ -88,7 +89,7 @@ func benchmarkHistogramSearchInt64(b *testing.B, size int) { for i := range values { values[i] = int64(rand.Float64() * inputRange) } - desc := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, otel.Int64NumberKind) + desc := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, number.Int64Kind) agg := &histogram.New(1, desc, boundaries)[0] ctx := context.Background() @@ -96,7 +97,7 @@ func benchmarkHistogramSearchInt64(b *testing.B, size int) { b.ResetTimer() for i := 0; i < b.N; i++ { - _ = agg.Update(ctx, otel.NewInt64Number(values[i]), desc) + _ = agg.Update(ctx, number.NewInt64Number(values[i]), desc) } } diff --git a/sdk/metric/aggregator/histogram/histogram.go b/sdk/metric/aggregator/histogram/histogram.go index 2df53a4a8e9..733becd09c0 100644 --- a/sdk/metric/aggregator/histogram/histogram.go +++ b/sdk/metric/aggregator/histogram/histogram.go @@ -19,7 +19,8 @@ import ( "sort" "sync" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator" @@ -36,7 +37,7 @@ type ( Aggregator struct { lock sync.Mutex boundaries []float64 - kind otel.NumberKind + kind number.Kind state state } @@ -45,7 +46,7 @@ type ( // the less than equal bucket count for the pre-determined boundaries. state struct { bucketCounts []float64 - sum otel.Number + sum number.Number count int64 } ) @@ -63,7 +64,7 @@ var _ aggregation.Histogram = &Aggregator{} // Note that this aggregator maintains each value using independent // atomic operations, which introduces the possibility that // checkpoints are inconsistent. -func New(cnt int, desc *otel.Descriptor, boundaries []float64) []Aggregator { +func New(cnt int, desc *metric.Descriptor, boundaries []float64) []Aggregator { aggs := make([]Aggregator, cnt) // Boundaries MUST be ordered otherwise the histogram could not @@ -94,7 +95,7 @@ func (c *Aggregator) Kind() aggregation.Kind { } // Sum returns the sum of all values in the checkpoint. -func (c *Aggregator) Sum() (otel.Number, error) { +func (c *Aggregator) Sum() (number.Number, error) { return c.state.sum, nil } @@ -115,7 +116,7 @@ func (c *Aggregator) Histogram() (aggregation.Buckets, error) { // the empty set. Since no locks are taken, there is a chance that // the independent Sum, Count and Bucket Count are not consistent with each // other. -func (c *Aggregator) SynchronizedMove(oa export.Aggregator, desc *otel.Descriptor) error { +func (c *Aggregator) SynchronizedMove(oa export.Aggregator, desc *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(c, oa) @@ -134,7 +135,7 @@ func emptyState(boundaries []float64) state { } // Update adds the recorded measurement to the current data set. -func (c *Aggregator) Update(_ context.Context, number otel.Number, desc *otel.Descriptor) error { +func (c *Aggregator) Update(_ context.Context, number number.Number, desc *metric.Descriptor) error { kind := desc.NumberKind() asFloat := number.CoerceToFloat64(kind) @@ -168,7 +169,7 @@ func (c *Aggregator) Update(_ context.Context, number otel.Number, desc *otel.De } // Merge combines two histograms that have the same buckets into a single one. -func (c *Aggregator) Merge(oa export.Aggregator, desc *otel.Descriptor) error { +func (c *Aggregator) Merge(oa export.Aggregator, desc *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(c, oa) diff --git a/sdk/metric/aggregator/histogram/histogram_test.go b/sdk/metric/aggregator/histogram/histogram_test.go index d5088c3727d..c7468149ddd 100644 --- a/sdk/metric/aggregator/histogram/histogram_test.go +++ b/sdk/metric/aggregator/histogram/histogram_test.go @@ -22,7 +22,8 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/sdk/metric/aggregator/aggregatortest" "go.opentelemetry.io/otel/sdk/metric/aggregator/histogram" ) @@ -60,19 +61,19 @@ var ( boundaries = []float64{500, 250, 750} ) -func new2(desc *otel.Descriptor) (_, _ *histogram.Aggregator) { +func new2(desc *metric.Descriptor) (_, _ *histogram.Aggregator) { alloc := histogram.New(2, desc, boundaries) return &alloc[0], &alloc[1] } -func new4(desc *otel.Descriptor) (_, _, _, _ *histogram.Aggregator) { +func new4(desc *metric.Descriptor) (_, _, _, _ *histogram.Aggregator) { alloc := histogram.New(4, desc, boundaries) return &alloc[0], &alloc[1], &alloc[2], &alloc[3] } -func checkZero(t *testing.T, agg *histogram.Aggregator, desc *otel.Descriptor) { +func checkZero(t *testing.T, agg *histogram.Aggregator, desc *metric.Descriptor) { asum, err := agg.Sum() - require.Equal(t, otel.Number(0), asum, "Empty checkpoint sum = 0") + require.Equal(t, number.Number(0), asum, "Empty checkpoint sum = 0") require.NoError(t, err) count, err := agg.Count() @@ -109,7 +110,7 @@ func TestHistogramPositiveAndNegative(t *testing.T) { // Validates count, sum and buckets for a given profile and policy func testHistogram(t *testing.T, profile aggregatortest.Profile, policy policy) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) agg, ckpt := new2(descriptor) @@ -154,7 +155,7 @@ func testHistogram(t *testing.T, profile aggregatortest.Profile, policy policy) func TestHistogramInitial(t *testing.T) { aggregatortest.RunProfiles(t, func(t *testing.T, profile aggregatortest.Profile) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) agg := &histogram.New(1, descriptor, boundaries)[0] buckets, err := agg.Histogram() @@ -167,7 +168,7 @@ func TestHistogramInitial(t *testing.T) { func TestHistogramMerge(t *testing.T) { aggregatortest.RunProfiles(t, func(t *testing.T, profile aggregatortest.Profile) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) agg1, agg2, ckpt1, ckpt2 := new4(descriptor) @@ -219,7 +220,7 @@ func TestHistogramMerge(t *testing.T) { func TestHistogramNotSet(t *testing.T) { aggregatortest.RunProfiles(t, func(t *testing.T, profile aggregatortest.Profile) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) agg, ckpt := new2(descriptor) @@ -231,7 +232,7 @@ func TestHistogramNotSet(t *testing.T) { }) } -func calcBuckets(points []otel.Number, profile aggregatortest.Profile) []uint64 { +func calcBuckets(points []number.Number, profile aggregatortest.Profile) []uint64 { sortedBoundaries := make([]float64, len(boundaries)) copy(sortedBoundaries, boundaries) diff --git a/sdk/metric/aggregator/lastvalue/lastvalue.go b/sdk/metric/aggregator/lastvalue/lastvalue.go index c572090e9ce..e220d88edfb 100644 --- a/sdk/metric/aggregator/lastvalue/lastvalue.go +++ b/sdk/metric/aggregator/lastvalue/lastvalue.go @@ -20,7 +20,8 @@ import ( "time" "unsafe" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator" @@ -40,7 +41,7 @@ type ( // value is the int64- or float64-encoded Set() data // // value needs to be aligned for 64-bit atomic operations. - value otel.Number + value number.Number // timestamp indicates when this record was submitted. // this can be used to pick a winner when multiple @@ -82,7 +83,7 @@ func (g *Aggregator) Kind() aggregation.Kind { // corresponding timestamp. The error value aggregation.ErrNoData // will be returned if (due to a race condition) the checkpoint was // computed before the first value was set. -func (g *Aggregator) LastValue() (otel.Number, time.Time, error) { +func (g *Aggregator) LastValue() (number.Number, time.Time, error) { gd := (*lastValueData)(g.value) if gd == unsetLastValue { return 0, time.Time{}, aggregation.ErrNoData @@ -91,7 +92,7 @@ func (g *Aggregator) LastValue() (otel.Number, time.Time, error) { } // SynchronizedMove atomically saves the current value. -func (g *Aggregator) SynchronizedMove(oa export.Aggregator, _ *otel.Descriptor) error { +func (g *Aggregator) SynchronizedMove(oa export.Aggregator, _ *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(g, oa) @@ -101,7 +102,7 @@ func (g *Aggregator) SynchronizedMove(oa export.Aggregator, _ *otel.Descriptor) } // Update atomically sets the current "last" value. -func (g *Aggregator) Update(_ context.Context, number otel.Number, desc *otel.Descriptor) error { +func (g *Aggregator) Update(_ context.Context, number number.Number, desc *metric.Descriptor) error { ngd := &lastValueData{ value: number, timestamp: time.Now(), @@ -112,7 +113,7 @@ func (g *Aggregator) Update(_ context.Context, number otel.Number, desc *otel.De // Merge combines state from two aggregators. The most-recently set // value is chosen. -func (g *Aggregator) Merge(oa export.Aggregator, desc *otel.Descriptor) error { +func (g *Aggregator) Merge(oa export.Aggregator, desc *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(g, oa) diff --git a/sdk/metric/aggregator/lastvalue/lastvalue_test.go b/sdk/metric/aggregator/lastvalue/lastvalue_test.go index 48e7bc77f85..62438c36619 100644 --- a/sdk/metric/aggregator/lastvalue/lastvalue_test.go +++ b/sdk/metric/aggregator/lastvalue/lastvalue_test.go @@ -24,8 +24,9 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" ottest "go.opentelemetry.io/otel/internal/testing" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator/aggregatortest" @@ -64,16 +65,16 @@ func checkZero(t *testing.T, agg *Aggregator) { lv, ts, err := agg.LastValue() require.True(t, errors.Is(err, aggregation.ErrNoData)) require.Equal(t, time.Time{}, ts) - require.Equal(t, otel.Number(0), lv) + require.Equal(t, number.Number(0), lv) } func TestLastValueUpdate(t *testing.T) { aggregatortest.RunProfiles(t, func(t *testing.T, profile aggregatortest.Profile) { agg, ckpt := new2() - record := aggregatortest.NewAggregatorTest(otel.ValueObserverInstrumentKind, profile.NumberKind) + record := aggregatortest.NewAggregatorTest(metric.ValueObserverInstrumentKind, profile.NumberKind) - var last otel.Number + var last number.Number for i := 0; i < count; i++ { x := profile.Random(rand.Intn(1)*2 - 1) last = x @@ -93,7 +94,7 @@ func TestLastValueMerge(t *testing.T) { aggregatortest.RunProfiles(t, func(t *testing.T, profile aggregatortest.Profile) { agg1, agg2, ckpt1, ckpt2 := new4() - descriptor := aggregatortest.NewAggregatorTest(otel.ValueObserverInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueObserverInstrumentKind, profile.NumberKind) first1 := profile.Random(+1) first2 := profile.Random(+1) @@ -124,7 +125,7 @@ func TestLastValueMerge(t *testing.T) { } func TestLastValueNotSet(t *testing.T) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueObserverInstrumentKind, otel.Int64NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueObserverInstrumentKind, number.Int64Kind) g, ckpt := new2() require.NoError(t, g.SynchronizedMove(ckpt, descriptor)) diff --git a/sdk/metric/aggregator/minmaxsumcount/mmsc.go b/sdk/metric/aggregator/minmaxsumcount/mmsc.go index 54db3a694c2..5095e594452 100644 --- a/sdk/metric/aggregator/minmaxsumcount/mmsc.go +++ b/sdk/metric/aggregator/minmaxsumcount/mmsc.go @@ -18,7 +18,8 @@ import ( "context" "sync" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator" @@ -29,14 +30,14 @@ type ( // keeping only the min, max, sum, and count. Aggregator struct { lock sync.Mutex - kind otel.NumberKind + kind number.Kind state } state struct { - sum otel.Number - min otel.Number - max otel.Number + sum number.Number + min number.Number + max number.Number count int64 } ) @@ -49,7 +50,7 @@ var _ aggregation.MinMaxSumCount = &Aggregator{} // Max. // // This type uses a mutex for Update() and SynchronizedMove() concurrency. -func New(cnt int, desc *otel.Descriptor) []Aggregator { +func New(cnt int, desc *metric.Descriptor) []Aggregator { kind := desc.NumberKind() aggs := make([]Aggregator, cnt) for i := range aggs { @@ -72,7 +73,7 @@ func (c *Aggregator) Kind() aggregation.Kind { } // Sum returns the sum of values in the checkpoint. -func (c *Aggregator) Sum() (otel.Number, error) { +func (c *Aggregator) Sum() (number.Number, error) { return c.sum, nil } @@ -84,7 +85,7 @@ func (c *Aggregator) Count() (int64, error) { // Min returns the minimum value in the checkpoint. // The error value aggregation.ErrNoData will be returned // if there were no measurements recorded during the checkpoint. -func (c *Aggregator) Min() (otel.Number, error) { +func (c *Aggregator) Min() (number.Number, error) { if c.count == 0 { return 0, aggregation.ErrNoData } @@ -94,7 +95,7 @@ func (c *Aggregator) Min() (otel.Number, error) { // Max returns the maximum value in the checkpoint. // The error value aggregation.ErrNoData will be returned // if there were no measurements recorded during the checkpoint. -func (c *Aggregator) Max() (otel.Number, error) { +func (c *Aggregator) Max() (number.Number, error) { if c.count == 0 { return 0, aggregation.ErrNoData } @@ -103,7 +104,7 @@ func (c *Aggregator) Max() (otel.Number, error) { // SynchronizedMove saves the current state into oa and resets the current state to // the empty set. -func (c *Aggregator) SynchronizedMove(oa export.Aggregator, desc *otel.Descriptor) error { +func (c *Aggregator) SynchronizedMove(oa export.Aggregator, desc *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(c, oa) @@ -119,7 +120,7 @@ func (c *Aggregator) SynchronizedMove(oa export.Aggregator, desc *otel.Descripto return nil } -func emptyState(kind otel.NumberKind) state { +func emptyState(kind number.Kind) state { return state{ count: 0, sum: 0, @@ -129,7 +130,7 @@ func emptyState(kind otel.NumberKind) state { } // Update adds the recorded measurement to the current data set. -func (c *Aggregator) Update(_ context.Context, number otel.Number, desc *otel.Descriptor) error { +func (c *Aggregator) Update(_ context.Context, number number.Number, desc *metric.Descriptor) error { kind := desc.NumberKind() c.lock.Lock() @@ -146,7 +147,7 @@ func (c *Aggregator) Update(_ context.Context, number otel.Number, desc *otel.De } // Merge combines two data sets into one. -func (c *Aggregator) Merge(oa export.Aggregator, desc *otel.Descriptor) error { +func (c *Aggregator) Merge(oa export.Aggregator, desc *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(c, oa) diff --git a/sdk/metric/aggregator/minmaxsumcount/mmsc_test.go b/sdk/metric/aggregator/minmaxsumcount/mmsc_test.go index 4adebc73695..0df3e79ddef 100644 --- a/sdk/metric/aggregator/minmaxsumcount/mmsc_test.go +++ b/sdk/metric/aggregator/minmaxsumcount/mmsc_test.go @@ -22,7 +22,8 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator/aggregatortest" ) @@ -76,17 +77,17 @@ func TestMinMaxSumCountPositiveAndNegative(t *testing.T) { }) } -func new2(desc *otel.Descriptor) (_, _ *Aggregator) { +func new2(desc *metric.Descriptor) (_, _ *Aggregator) { alloc := New(2, desc) return &alloc[0], &alloc[1] } -func new4(desc *otel.Descriptor) (_, _, _, _ *Aggregator) { +func new4(desc *metric.Descriptor) (_, _, _, _ *Aggregator) { alloc := New(4, desc) return &alloc[0], &alloc[1], &alloc[2], &alloc[3] } -func checkZero(t *testing.T, agg *Aggregator, desc *otel.Descriptor) { +func checkZero(t *testing.T, agg *Aggregator, desc *metric.Descriptor) { kind := desc.NumberKind() sum, err := agg.Sum() @@ -108,7 +109,7 @@ func checkZero(t *testing.T, agg *Aggregator, desc *otel.Descriptor) { // Validates min, max, sum and count for a given profile and policy func minMaxSumCount(t *testing.T, profile aggregatortest.Profile, policy policy) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) agg, ckpt := new2(descriptor) @@ -156,7 +157,7 @@ func minMaxSumCount(t *testing.T, profile aggregatortest.Profile, policy policy) func TestMinMaxSumCountMerge(t *testing.T) { aggregatortest.RunProfiles(t, func(t *testing.T, profile aggregatortest.Profile) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) agg1, agg2, ckpt1, ckpt2 := new4(descriptor) @@ -214,7 +215,7 @@ func TestMinMaxSumCountMerge(t *testing.T) { func TestMaxSumCountNotSet(t *testing.T) { aggregatortest.RunProfiles(t, func(t *testing.T, profile aggregatortest.Profile) { - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) alloc := New(2, descriptor) agg, ckpt := &alloc[0], &alloc[1] @@ -222,7 +223,7 @@ func TestMaxSumCountNotSet(t *testing.T) { require.NoError(t, agg.SynchronizedMove(ckpt, descriptor)) asum, err := ckpt.Sum() - require.Equal(t, otel.Number(0), asum, "Empty checkpoint sum = 0") + require.Equal(t, number.Number(0), asum, "Empty checkpoint sum = 0") require.Nil(t, err) count, err := ckpt.Count() @@ -231,6 +232,6 @@ func TestMaxSumCountNotSet(t *testing.T) { max, err := ckpt.Max() require.Equal(t, aggregation.ErrNoData, err) - require.Equal(t, otel.Number(0), max) + require.Equal(t, number.Number(0), max) }) } diff --git a/sdk/metric/aggregator/sum/sum.go b/sdk/metric/aggregator/sum/sum.go index b1fbe050c00..0c559acd2ba 100644 --- a/sdk/metric/aggregator/sum/sum.go +++ b/sdk/metric/aggregator/sum/sum.go @@ -17,7 +17,8 @@ package sum // import "go.opentelemetry.io/otel/sdk/metric/aggregator/sum" import ( "context" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator" @@ -27,7 +28,7 @@ import ( type Aggregator struct { // current holds current increments to this counter record // current needs to be aligned for 64-bit atomic operations. - value otel.Number + value number.Number } var _ export.Aggregator = &Aggregator{} @@ -53,29 +54,29 @@ func (c *Aggregator) Kind() aggregation.Kind { // Sum returns the last-checkpointed sum. This will never return an // error. -func (c *Aggregator) Sum() (otel.Number, error) { +func (c *Aggregator) Sum() (number.Number, error) { return c.value, nil } // SynchronizedMove atomically saves the current value into oa and resets the // current sum to zero. -func (c *Aggregator) SynchronizedMove(oa export.Aggregator, _ *otel.Descriptor) error { +func (c *Aggregator) SynchronizedMove(oa export.Aggregator, _ *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(c, oa) } - o.value = c.value.SwapNumberAtomic(otel.Number(0)) + o.value = c.value.SwapNumberAtomic(number.Number(0)) return nil } // Update atomically adds to the current value. -func (c *Aggregator) Update(_ context.Context, number otel.Number, desc *otel.Descriptor) error { - c.value.AddNumberAtomic(desc.NumberKind(), number) +func (c *Aggregator) Update(_ context.Context, num number.Number, desc *metric.Descriptor) error { + c.value.AddNumberAtomic(desc.NumberKind(), num) return nil } // Merge combines two counters by adding their sums. -func (c *Aggregator) Merge(oa export.Aggregator, desc *otel.Descriptor) error { +func (c *Aggregator) Merge(oa export.Aggregator, desc *metric.Descriptor) error { o, _ := oa.(*Aggregator) if o == nil { return aggregator.NewInconsistentAggregatorError(c, oa) @@ -84,7 +85,7 @@ func (c *Aggregator) Merge(oa export.Aggregator, desc *otel.Descriptor) error { return nil } -func (c *Aggregator) Subtract(opAgg, resAgg export.Aggregator, descriptor *otel.Descriptor) error { +func (c *Aggregator) Subtract(opAgg, resAgg export.Aggregator, descriptor *metric.Descriptor) error { op, _ := opAgg.(*Aggregator) if op == nil { return aggregator.NewInconsistentAggregatorError(c, opAgg) @@ -96,6 +97,6 @@ func (c *Aggregator) Subtract(opAgg, resAgg export.Aggregator, descriptor *otel. } res.value = c.value - res.value.AddNumber(descriptor.NumberKind(), otel.NewNumberSignChange(descriptor.NumberKind(), op.value)) + res.value.AddNumber(descriptor.NumberKind(), number.NewNumberSignChange(descriptor.NumberKind(), op.value)) return nil } diff --git a/sdk/metric/aggregator/sum/sum_test.go b/sdk/metric/aggregator/sum/sum_test.go index af31a98b3f3..9a9a14f2069 100644 --- a/sdk/metric/aggregator/sum/sum_test.go +++ b/sdk/metric/aggregator/sum/sum_test.go @@ -21,8 +21,9 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" ottest "go.opentelemetry.io/otel/internal/testing" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/sdk/metric/aggregator/aggregatortest" ) @@ -53,7 +54,7 @@ func new4() (_, _, _, _ *Aggregator) { return &alloc[0], &alloc[1], &alloc[2], &alloc[3] } -func checkZero(t *testing.T, agg *Aggregator, desc *otel.Descriptor) { +func checkZero(t *testing.T, agg *Aggregator, desc *metric.Descriptor) { kind := desc.NumberKind() sum, err := agg.Sum() @@ -65,9 +66,9 @@ func TestCounterSum(t *testing.T) { aggregatortest.RunProfiles(t, func(t *testing.T, profile aggregatortest.Profile) { agg, ckpt := new2() - descriptor := aggregatortest.NewAggregatorTest(otel.CounterInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.CounterInstrumentKind, profile.NumberKind) - sum := otel.Number(0) + sum := number.Number(0) for i := 0; i < count; i++ { x := profile.Random(+1) sum.AddNumber(profile.NumberKind, x) @@ -89,9 +90,9 @@ func TestValueRecorderSum(t *testing.T) { aggregatortest.RunProfiles(t, func(t *testing.T, profile aggregatortest.Profile) { agg, ckpt := new2() - descriptor := aggregatortest.NewAggregatorTest(otel.ValueRecorderInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.ValueRecorderInstrumentKind, profile.NumberKind) - sum := otel.Number(0) + sum := number.Number(0) for i := 0; i < count; i++ { r1 := profile.Random(+1) @@ -115,9 +116,9 @@ func TestCounterMerge(t *testing.T) { aggregatortest.RunProfiles(t, func(t *testing.T, profile aggregatortest.Profile) { agg1, agg2, ckpt1, ckpt2 := new4() - descriptor := aggregatortest.NewAggregatorTest(otel.CounterInstrumentKind, profile.NumberKind) + descriptor := aggregatortest.NewAggregatorTest(metric.CounterInstrumentKind, profile.NumberKind) - sum := otel.Number(0) + sum := number.Number(0) for i := 0; i < count; i++ { x := profile.Random(+1) sum.AddNumber(profile.NumberKind, x) diff --git a/sdk/metric/benchmark_test.go b/sdk/metric/benchmark_test.go index 9b562c4fed7..4da8cfaa694 100644 --- a/sdk/metric/benchmark_test.go +++ b/sdk/metric/benchmark_test.go @@ -20,16 +20,16 @@ import ( "math/rand" "testing" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" export "go.opentelemetry.io/otel/sdk/export/metric" sdk "go.opentelemetry.io/otel/sdk/metric" "go.opentelemetry.io/otel/sdk/metric/processor/processortest" ) type benchFixture struct { - meter otel.Meter + meter metric.Meter accumulator *sdk.Accumulator B *testing.B export.AggregatorSelector @@ -43,7 +43,7 @@ func newFixture(b *testing.B) *benchFixture { } bf.accumulator = sdk.NewAccumulator(bf, nil) - bf.meter = otel.WrapMeterImpl(bf.accumulator, "benchmarks") + bf.meter = metric.WrapMeterImpl(bf.accumulator, "benchmarks") return bf } @@ -51,12 +51,12 @@ func (f *benchFixture) Process(export.Accumulation) error { return nil } -func (f *benchFixture) Meter(_ string, _ ...otel.MeterOption) otel.Meter { +func (f *benchFixture) Meter(_ string, _ ...metric.MeterOption) metric.Meter { return f.meter } -func (f *benchFixture) meterMust() otel.MeterMust { - return otel.Must(f.meter) +func (f *benchFixture) meterMust() metric.MeterMust { + return metric.Must(f.meter) } func makeManyLabels(n int) [][]label.KeyValue { @@ -401,7 +401,7 @@ func BenchmarkObserverRegistration(b *testing.B) { for i := 0; i < b.N; i++ { names = append(names, fmt.Sprintf("test.%d.lastvalue", i)) } - cb := func(_ context.Context, result otel.Int64ObserverResult) {} + cb := func(_ context.Context, result metric.Int64ObserverResult) {} b.ResetTimer() @@ -414,7 +414,7 @@ func BenchmarkValueObserverObservationInt64(b *testing.B) { ctx := context.Background() fix := newFixture(b) labs := makeLabels(1) - _ = fix.meterMust().NewInt64ValueObserver("test.lastvalue", func(_ context.Context, result otel.Int64ObserverResult) { + _ = fix.meterMust().NewInt64ValueObserver("test.lastvalue", func(_ context.Context, result metric.Int64ObserverResult) { for i := 0; i < b.N; i++ { result.Observe((int64)(i), labs...) } @@ -429,7 +429,7 @@ func BenchmarkValueObserverObservationFloat64(b *testing.B) { ctx := context.Background() fix := newFixture(b) labs := makeLabels(1) - _ = fix.meterMust().NewFloat64ValueObserver("test.lastvalue", func(_ context.Context, result otel.Float64ObserverResult) { + _ = fix.meterMust().NewFloat64ValueObserver("test.lastvalue", func(_ context.Context, result metric.Float64ObserverResult) { for i := 0; i < b.N; i++ { result.Observe((float64)(i), labs...) } @@ -501,7 +501,7 @@ func benchmarkBatchRecord8Labels(b *testing.B, numInst int) { ctx := context.Background() fix := newFixture(b) labs := makeLabels(numLabels) - var meas []otel.Measurement + var meas []metric.Measurement for i := 0; i < numInst; i++ { inst := fix.meterMust().NewInt64Counter(fmt.Sprintf("int64.%d.sum", i)) diff --git a/sdk/metric/controller/pull/pull.go b/sdk/metric/controller/pull/pull.go index 5d48062e806..315d6a8ecee 100644 --- a/sdk/metric/controller/pull/pull.go +++ b/sdk/metric/controller/pull/pull.go @@ -18,8 +18,8 @@ import ( "context" "time" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/registry" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/registry" export "go.opentelemetry.io/otel/sdk/export/metric" sdk "go.opentelemetry.io/otel/sdk/metric" controllerTime "go.opentelemetry.io/otel/sdk/metric/controller/time" @@ -82,7 +82,7 @@ func (c *Controller) SetClock(clock controllerTime.Clock) { // MeterProvider returns a MeterProvider for the implementation managed by // this controller. -func (c *Controller) MeterProvider() otel.MeterProvider { +func (c *Controller) MeterProvider() metric.MeterProvider { return c.provider } diff --git a/sdk/metric/controller/pull/pull_test.go b/sdk/metric/controller/pull/pull_test.go index 1166d952faa..153e63e639d 100644 --- a/sdk/metric/controller/pull/pull_test.go +++ b/sdk/metric/controller/pull/pull_test.go @@ -22,8 +22,8 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/metric/controller/controllertest" "go.opentelemetry.io/otel/sdk/metric/controller/pull" @@ -36,7 +36,7 @@ func TestPullNoCache(t *testing.T) { puller := pull.New( basic.New( selector.NewWithExactDistribution(), - export.CumulativeExporter, + export.CumulativeExportKindSelector(), basic.WithMemory(true), ), pull.WithCachePeriod(0), @@ -44,13 +44,13 @@ func TestPullNoCache(t *testing.T) { ctx := context.Background() meter := puller.MeterProvider().Meter("nocache") - counter := otel.Must(meter).NewInt64Counter("counter.sum") + counter := metric.Must(meter).NewInt64Counter("counter.sum") counter.Add(ctx, 10, label.String("A", "B")) require.NoError(t, puller.Collect(ctx)) records := processortest.NewOutput(label.DefaultEncoder()) - require.NoError(t, puller.ForEach(export.CumulativeExporter, records.AddRecord)) + require.NoError(t, puller.ForEach(export.CumulativeExportKindSelector(), records.AddRecord)) require.EqualValues(t, map[string]float64{ "counter.sum/A=B/": 10, @@ -60,7 +60,7 @@ func TestPullNoCache(t *testing.T) { require.NoError(t, puller.Collect(ctx)) records = processortest.NewOutput(label.DefaultEncoder()) - require.NoError(t, puller.ForEach(export.CumulativeExporter, records.AddRecord)) + require.NoError(t, puller.ForEach(export.CumulativeExportKindSelector(), records.AddRecord)) require.EqualValues(t, map[string]float64{ "counter.sum/A=B/": 20, @@ -71,7 +71,7 @@ func TestPullWithCache(t *testing.T) { puller := pull.New( basic.New( selector.NewWithExactDistribution(), - export.CumulativeExporter, + export.CumulativeExportKindSelector(), basic.WithMemory(true), ), pull.WithCachePeriod(time.Second), @@ -81,13 +81,13 @@ func TestPullWithCache(t *testing.T) { ctx := context.Background() meter := puller.MeterProvider().Meter("nocache") - counter := otel.Must(meter).NewInt64Counter("counter.sum") + counter := metric.Must(meter).NewInt64Counter("counter.sum") counter.Add(ctx, 10, label.String("A", "B")) require.NoError(t, puller.Collect(ctx)) records := processortest.NewOutput(label.DefaultEncoder()) - require.NoError(t, puller.ForEach(export.CumulativeExporter, records.AddRecord)) + require.NoError(t, puller.ForEach(export.CumulativeExportKindSelector(), records.AddRecord)) require.EqualValues(t, map[string]float64{ "counter.sum/A=B/": 10, @@ -98,7 +98,7 @@ func TestPullWithCache(t *testing.T) { // Cached value! require.NoError(t, puller.Collect(ctx)) records = processortest.NewOutput(label.DefaultEncoder()) - require.NoError(t, puller.ForEach(export.CumulativeExporter, records.AddRecord)) + require.NoError(t, puller.ForEach(export.CumulativeExportKindSelector(), records.AddRecord)) require.EqualValues(t, map[string]float64{ "counter.sum/A=B/": 10, @@ -110,7 +110,7 @@ func TestPullWithCache(t *testing.T) { // Re-computed value! require.NoError(t, puller.Collect(ctx)) records = processortest.NewOutput(label.DefaultEncoder()) - require.NoError(t, puller.ForEach(export.CumulativeExporter, records.AddRecord)) + require.NoError(t, puller.ForEach(export.CumulativeExportKindSelector(), records.AddRecord)) require.EqualValues(t, map[string]float64{ "counter.sum/A=B/": 20, diff --git a/sdk/metric/controller/push/push.go b/sdk/metric/controller/push/push.go index 2202e927376..e5911136dc6 100644 --- a/sdk/metric/controller/push/push.go +++ b/sdk/metric/controller/push/push.go @@ -19,9 +19,9 @@ import ( "sync" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" - "go.opentelemetry.io/otel/registry" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/registry" export "go.opentelemetry.io/otel/sdk/export/metric" sdk "go.opentelemetry.io/otel/sdk/metric" controllerTime "go.opentelemetry.io/otel/sdk/metric/controller/time" @@ -85,7 +85,7 @@ func (c *Controller) SetClock(clock controllerTime.Clock) { } // MeterProvider returns a MeterProvider instance for this controller. -func (c *Controller) MeterProvider() otel.MeterProvider { +func (c *Controller) MeterProvider() metric.MeterProvider { return c.provider } diff --git a/sdk/metric/controller/push/push_test.go b/sdk/metric/controller/push/push_test.go index af1466e2c72..d61c66dc252 100644 --- a/sdk/metric/controller/push/push_test.go +++ b/sdk/metric/controller/push/push_test.go @@ -24,9 +24,9 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/controller/controllertest" @@ -66,7 +66,7 @@ func init() { func newExporter() *processorTest.Exporter { return processorTest.NewExporter( - export.PassThroughExporter, + export.StatelessExportKindSelector(), label.DefaultEncoder(), ) } @@ -114,7 +114,7 @@ func TestPushTicker(t *testing.T) { ctx := context.Background() - counter := otel.Must(meter).NewInt64Counter("counter.sum") + counter := metric.Must(meter).NewInt64Counter("counter.sum") p.Start() @@ -194,8 +194,8 @@ func TestPushExportError(t *testing.T) { ctx := context.Background() meter := p.MeterProvider().Meter("name") - counter1 := otel.Must(meter).NewInt64Counter("counter1.sum") - counter2 := otel.Must(meter).NewInt64Counter("counter2.sum") + counter1 := metric.Must(meter).NewInt64Counter("counter1.sum") + counter2 := metric.Must(meter).NewInt64Counter("counter2.sum") p.Start() runtime.Gosched() diff --git a/sdk/metric/correct_test.go b/sdk/metric/correct_test.go index 4f3aea6ca67..4cee368be92 100644 --- a/sdk/metric/correct_test.go +++ b/sdk/metric/correct_test.go @@ -23,9 +23,10 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" metricsdk "go.opentelemetry.io/otel/sdk/metric" @@ -33,7 +34,7 @@ import ( "go.opentelemetry.io/otel/sdk/resource" ) -var Must = otel.Must +var Must = metric.Must var testResource = resource.NewWithAttributes(label.String("R", "V")) type handler struct { @@ -83,12 +84,12 @@ type testSelector struct { newAggCount int } -func (ts *testSelector) AggregatorFor(desc *otel.Descriptor, aggPtrs ...*export.Aggregator) { +func (ts *testSelector) AggregatorFor(desc *metric.Descriptor, aggPtrs ...*export.Aggregator) { ts.newAggCount += len(aggPtrs) processortest.AggregatorSelector().AggregatorFor(desc, aggPtrs...) } -func newSDK(t *testing.T) (otel.Meter, *metricsdk.Accumulator, *correctnessProcessor) { +func newSDK(t *testing.T) (metric.Meter, *metricsdk.Accumulator, *correctnessProcessor) { testHandler.Reset() processor := &correctnessProcessor{ t: t, @@ -98,7 +99,7 @@ func newSDK(t *testing.T) (otel.Meter, *metricsdk.Accumulator, *correctnessProce processor, testResource, ) - meter := otel.WrapMeterImpl(accum, "test") + meter := metric.WrapMeterImpl(accum, "test") return meter, accum, processor } @@ -253,7 +254,7 @@ func TestSDKLabelsDeduplication(t *testing.T) { var actual [][]label.KeyValue for _, rec := range processor.accumulations { sum, _ := rec.Aggregator().(aggregation.Sum).Sum() - require.Equal(t, sum, otel.NewInt64Number(2)) + require.Equal(t, sum, number.NewInt64Number(2)) kvs := rec.Labels().ToSlice() actual = append(actual, kvs) @@ -300,13 +301,13 @@ func TestObserverCollection(t *testing.T) { ctx := context.Background() meter, sdk, processor := newSDK(t) - _ = Must(meter).NewFloat64ValueObserver("float.valueobserver.lastvalue", func(_ context.Context, result otel.Float64ObserverResult) { + _ = Must(meter).NewFloat64ValueObserver("float.valueobserver.lastvalue", func(_ context.Context, result metric.Float64ObserverResult) { result.Observe(1, label.String("A", "B")) // last value wins result.Observe(-1, label.String("A", "B")) result.Observe(-1, label.String("C", "D")) }) - _ = Must(meter).NewInt64ValueObserver("int.valueobserver.lastvalue", func(_ context.Context, result otel.Int64ObserverResult) { + _ = Must(meter).NewInt64ValueObserver("int.valueobserver.lastvalue", func(_ context.Context, result metric.Int64ObserverResult) { result.Observe(-1, label.String("A", "B")) result.Observe(1) // last value wins @@ -314,12 +315,12 @@ func TestObserverCollection(t *testing.T) { result.Observe(1) }) - _ = Must(meter).NewFloat64SumObserver("float.sumobserver.sum", func(_ context.Context, result otel.Float64ObserverResult) { + _ = Must(meter).NewFloat64SumObserver("float.sumobserver.sum", func(_ context.Context, result metric.Float64ObserverResult) { result.Observe(1, label.String("A", "B")) result.Observe(2, label.String("A", "B")) result.Observe(1, label.String("C", "D")) }) - _ = Must(meter).NewInt64SumObserver("int.sumobserver.sum", func(_ context.Context, result otel.Int64ObserverResult) { + _ = Must(meter).NewInt64SumObserver("int.sumobserver.sum", func(_ context.Context, result metric.Int64ObserverResult) { result.Observe(2, label.String("A", "B")) result.Observe(1) // last value wins @@ -327,12 +328,12 @@ func TestObserverCollection(t *testing.T) { result.Observe(1) }) - _ = Must(meter).NewFloat64UpDownSumObserver("float.updownsumobserver.sum", func(_ context.Context, result otel.Float64ObserverResult) { + _ = Must(meter).NewFloat64UpDownSumObserver("float.updownsumobserver.sum", func(_ context.Context, result metric.Float64ObserverResult) { result.Observe(1, label.String("A", "B")) result.Observe(-2, label.String("A", "B")) result.Observe(1, label.String("C", "D")) }) - _ = Must(meter).NewInt64UpDownSumObserver("int.updownsumobserver.sum", func(_ context.Context, result otel.Int64ObserverResult) { + _ = Must(meter).NewInt64UpDownSumObserver("int.updownsumobserver.sum", func(_ context.Context, result metric.Int64ObserverResult) { result.Observe(2, label.String("A", "B")) result.Observe(1) // last value wins @@ -340,7 +341,7 @@ func TestObserverCollection(t *testing.T) { result.Observe(-1) }) - _ = Must(meter).NewInt64ValueObserver("empty.valueobserver.sum", func(_ context.Context, result otel.Int64ObserverResult) { + _ = Must(meter).NewInt64ValueObserver("empty.valueobserver.sum", func(_ context.Context, result metric.Int64ObserverResult) { }) collected := sdk.Collect(ctx) @@ -374,13 +375,13 @@ func TestSumObserverInputRange(t *testing.T) { meter, sdk, processor := newSDK(t) // TODO: these tests are testing for negative values, not for _descending values_. Fix. - _ = Must(meter).NewFloat64SumObserver("float.sumobserver.sum", func(_ context.Context, result otel.Float64ObserverResult) { + _ = Must(meter).NewFloat64SumObserver("float.sumobserver.sum", func(_ context.Context, result metric.Float64ObserverResult) { result.Observe(-2, label.String("A", "B")) require.Equal(t, aggregation.ErrNegativeInput, testHandler.Flush()) result.Observe(-1, label.String("C", "D")) require.Equal(t, aggregation.ErrNegativeInput, testHandler.Flush()) }) - _ = Must(meter).NewInt64SumObserver("int.sumobserver.sum", func(_ context.Context, result otel.Int64ObserverResult) { + _ = Must(meter).NewInt64SumObserver("int.sumobserver.sum", func(_ context.Context, result metric.Int64ObserverResult) { result.Observe(-1, label.String("A", "B")) require.Equal(t, aggregation.ErrNegativeInput, testHandler.Flush()) result.Observe(-1) @@ -400,15 +401,15 @@ func TestObserverBatch(t *testing.T) { ctx := context.Background() meter, sdk, processor := newSDK(t) - var floatValueObs otel.Float64ValueObserver - var intValueObs otel.Int64ValueObserver - var floatSumObs otel.Float64SumObserver - var intSumObs otel.Int64SumObserver - var floatUpDownSumObs otel.Float64UpDownSumObserver - var intUpDownSumObs otel.Int64UpDownSumObserver + var floatValueObs metric.Float64ValueObserver + var intValueObs metric.Int64ValueObserver + var floatSumObs metric.Float64SumObserver + var intSumObs metric.Int64SumObserver + var floatUpDownSumObs metric.Float64UpDownSumObserver + var intUpDownSumObs metric.Int64UpDownSumObserver var batch = Must(meter).NewBatchObserver( - func(_ context.Context, result otel.BatchObserverResult) { + func(_ context.Context, result metric.BatchObserverResult) { result.Observe( []label.KeyValue{ label.String("A", "B"), @@ -530,15 +531,15 @@ func TestRecordPersistence(t *testing.T) { func TestIncorrectInstruments(t *testing.T) { // The Batch observe/record APIs are susceptible to // uninitialized instruments. - var counter otel.Int64Counter - var observer otel.Int64ValueObserver + var counter metric.Int64Counter + var observer metric.Int64ValueObserver ctx := context.Background() meter, sdk, _ := newSDK(t) // Now try with uninitialized instruments. meter.RecordBatch(ctx, nil, counter.Measurement(1)) - meter.NewBatchObserver(func(_ context.Context, result otel.BatchObserverResult) { + meter.NewBatchObserver(func(_ context.Context, result metric.BatchObserverResult) { result.Observe(nil, observer.Observation(1)) }) @@ -547,14 +548,14 @@ func TestIncorrectInstruments(t *testing.T) { require.Equal(t, 0, collected) // Now try with instruments from another SDK. - var noopMeter otel.Meter - counter = otel.Must(noopMeter).NewInt64Counter("name.sum") - observer = otel.Must(noopMeter).NewBatchObserver( - func(context.Context, otel.BatchObserverResult) {}, + var noopMeter metric.Meter + counter = metric.Must(noopMeter).NewInt64Counter("name.sum") + observer = metric.Must(noopMeter).NewBatchObserver( + func(context.Context, metric.BatchObserverResult) {}, ).NewInt64ValueObserver("observer") meter.RecordBatch(ctx, nil, counter.Measurement(1)) - meter.NewBatchObserver(func(_ context.Context, result otel.BatchObserverResult) { + meter.NewBatchObserver(func(_ context.Context, result metric.BatchObserverResult) { result.Observe(nil, observer.Observation(1)) }) @@ -569,7 +570,7 @@ func TestSyncInAsync(t *testing.T) { counter := Must(meter).NewFloat64Counter("counter.sum") _ = Must(meter).NewInt64ValueObserver("observer.lastvalue", - func(ctx context.Context, result otel.Int64ObserverResult) { + func(ctx context.Context, result metric.Int64ObserverResult) { result.Observe(10) counter.Add(ctx, 100) }, diff --git a/sdk/metric/histogram_stress_test.go b/sdk/metric/histogram_stress_test.go index 078688c5c00..a09c950cb18 100644 --- a/sdk/metric/histogram_stress_test.go +++ b/sdk/metric/histogram_stress_test.go @@ -22,12 +22,13 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/sdk/metric/aggregator/histogram" ) func TestStressInt64Histogram(t *testing.T) { - desc := otel.NewDescriptor("some_metric", otel.ValueRecorderInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("some_metric", metric.ValueRecorderInstrumentKind, number.Int64Kind) alloc := histogram.New(2, &desc, []float64{25, 50, 75}) h, ckpt := &alloc[0], &alloc[1] @@ -41,7 +42,7 @@ func TestStressInt64Histogram(t *testing.T) { case <-ctx.Done(): return default: - _ = h.Update(ctx, otel.NewInt64Number(rnd.Int63()%100), &desc) + _ = h.Update(ctx, number.NewInt64Number(rnd.Int63()%100), &desc) } } }() diff --git a/sdk/metric/minmaxsumcount_stress_test.go b/sdk/metric/minmaxsumcount_stress_test.go index c5ca9990b7d..4aafb18d160 100644 --- a/sdk/metric/minmaxsumcount_stress_test.go +++ b/sdk/metric/minmaxsumcount_stress_test.go @@ -20,12 +20,13 @@ import ( "testing" "time" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" "go.opentelemetry.io/otel/sdk/metric/aggregator/minmaxsumcount" ) func TestStressInt64MinMaxSumCount(t *testing.T) { - desc := otel.NewDescriptor("some_metric", otel.ValueRecorderInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("some_metric", metric.ValueRecorderInstrumentKind, number.Int64Kind) alloc := minmaxsumcount.New(2, &desc) mmsc, ckpt := &alloc[0], &alloc[1] @@ -39,7 +40,7 @@ func TestStressInt64MinMaxSumCount(t *testing.T) { case <-ctx.Done(): return default: - _ = mmsc.Update(ctx, otel.NewInt64Number(v), &desc) + _ = mmsc.Update(ctx, number.NewInt64Number(v), &desc) } v++ } diff --git a/sdk/metric/processor/basic/basic.go b/sdk/metric/processor/basic/basic.go index 120830a3c60..2e2a7c5df41 100644 --- a/sdk/metric/processor/basic/basic.go +++ b/sdk/metric/processor/basic/basic.go @@ -20,8 +20,8 @@ import ( "sync" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/resource" @@ -41,13 +41,13 @@ type ( // data for the same instrument with the same // resources, and this code has logic to combine data // properly from multiple accumulators. However, the - // use of *otel.Descriptor in the stateKey makes + // use of *metric.Descriptor in the stateKey makes // such combination impossible, because each // accumulator allocates its own instruments. This // can be fixed by using the instrument name and kind // instead of the descriptor pointer. See // https://github.com/open-telemetry/opentelemetry-go/issues/862. - descriptor *otel.Descriptor + descriptor *metric.Descriptor distinct label.Distinct resource label.Distinct } @@ -120,7 +120,7 @@ var _ export.Processor = &Processor{} var _ export.Checkpointer = &Processor{} var _ export.CheckpointSet = &state{} var ErrInconsistentState = fmt.Errorf("inconsistent processor state") -var ErrInvalidExporterKind = fmt.Errorf("invalid exporter kind") +var ErrInvalidExportKind = fmt.Errorf("invalid export kind") // New returns a basic Processor that is also a Checkpointer using the provided // AggregatorSelector to select Aggregators. The ExportKindSelector @@ -338,17 +338,7 @@ func (b *state) ForEach(exporter export.ExportKindSelector, f func(export.Record ekind := exporter.ExportKindFor(key.descriptor, value.current.Aggregation().Kind()) switch ekind { - case export.PassThroughExporter: - // No state is required, pass through the checkpointed value. - agg = value.current.Aggregation() - - if mkind.PrecomputedSum() { - start = b.processStart - } else { - start = b.intervalStart - } - - case export.CumulativeExporter: + case export.CumulativeExportKind: // If stateful, the sum has been computed. If stateless, the // input was already cumulative. Either way, use the checkpointed // value: @@ -359,7 +349,7 @@ func (b *state) ForEach(exporter export.ExportKindSelector, f func(export.Record } start = b.processStart - case export.DeltaExporter: + case export.DeltaExportKind: // Precomputed sums are a special case. if mkind.PrecomputedSum() { agg = value.delta.Aggregation() @@ -369,7 +359,7 @@ func (b *state) ForEach(exporter export.ExportKindSelector, f func(export.Record start = b.intervalStart default: - return fmt.Errorf("%v: %w", ekind, ErrInvalidExporterKind) + return fmt.Errorf("%v: %w", ekind, ErrInvalidExportKind) } if err := f(export.NewRecord( diff --git a/sdk/metric/processor/basic/basic_test.go b/sdk/metric/processor/basic/basic_test.go index 71e9d3870d4..a97745c5f60 100644 --- a/sdk/metric/processor/basic/basic_test.go +++ b/sdk/metric/processor/basic/basic_test.go @@ -24,8 +24,9 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/export/metric/metrictest" @@ -40,33 +41,32 @@ func TestProcessor(t *testing.T) { kind export.ExportKind } type instrumentCase struct { - kind otel.InstrumentKind + kind metric.InstrumentKind } type numberCase struct { - kind otel.NumberKind + kind number.Kind } type aggregatorCase struct { kind aggregation.Kind } for _, tc := range []exportCase{ - {kind: export.PassThroughExporter}, - {kind: export.CumulativeExporter}, - {kind: export.DeltaExporter}, + {kind: export.CumulativeExportKind}, + {kind: export.DeltaExportKind}, } { t.Run(tc.kind.String(), func(t *testing.T) { for _, ic := range []instrumentCase{ - {kind: otel.CounterInstrumentKind}, - {kind: otel.UpDownCounterInstrumentKind}, - {kind: otel.ValueRecorderInstrumentKind}, - {kind: otel.SumObserverInstrumentKind}, - {kind: otel.UpDownSumObserverInstrumentKind}, - {kind: otel.ValueObserverInstrumentKind}, + {kind: metric.CounterInstrumentKind}, + {kind: metric.UpDownCounterInstrumentKind}, + {kind: metric.ValueRecorderInstrumentKind}, + {kind: metric.SumObserverInstrumentKind}, + {kind: metric.UpDownSumObserverInstrumentKind}, + {kind: metric.ValueObserverInstrumentKind}, } { t.Run(ic.kind.String(), func(t *testing.T) { for _, nc := range []numberCase{ - {kind: otel.Int64NumberKind}, - {kind: otel.Float64NumberKind}, + {kind: number.Int64Kind}, + {kind: number.Float64Kind}, } { t.Run(nc.kind.String(), func(t *testing.T) { for _, ac := range []aggregatorCase{ @@ -95,14 +95,14 @@ func TestProcessor(t *testing.T) { } } -func asNumber(nkind otel.NumberKind, value int64) otel.Number { - if nkind == otel.Int64NumberKind { - return otel.NewInt64Number(value) +func asNumber(nkind number.Kind, value int64) number.Number { + if nkind == number.Int64Kind { + return number.NewInt64Number(value) } - return otel.NewFloat64Number(float64(value)) + return number.NewFloat64Number(float64(value)) } -func updateFor(t *testing.T, desc *otel.Descriptor, selector export.AggregatorSelector, res *resource.Resource, value int64, labs ...label.KeyValue) export.Accumulation { +func updateFor(t *testing.T, desc *metric.Descriptor, selector export.AggregatorSelector, res *resource.Resource, value int64, labs ...label.KeyValue) export.Accumulation { ls := label.NewSet(labs...) var agg export.Aggregator selector.AggregatorFor(desc, &agg) @@ -114,8 +114,8 @@ func updateFor(t *testing.T, desc *otel.Descriptor, selector export.AggregatorSe func testProcessor( t *testing.T, ekind export.ExportKind, - mkind otel.InstrumentKind, - nkind otel.NumberKind, + mkind metric.InstrumentKind, + nkind number.Kind, akind aggregation.Kind, ) { // Note: this selector uses the instrument name to dictate @@ -127,12 +127,12 @@ func testProcessor( labs2 := []label.KeyValue{label.String("L2", "V")} testBody := func(t *testing.T, hasMemory bool, nAccum, nCheckpoint int) { - processor := basic.New(selector, ekind, basic.WithMemory(hasMemory)) + processor := basic.New(selector, export.ConstantExportKindSelector(ekind), basic.WithMemory(hasMemory)) instSuffix := fmt.Sprint(".", strings.ToLower(akind.String())) - desc1 := otel.NewDescriptor(fmt.Sprint("inst1", instSuffix), mkind, nkind) - desc2 := otel.NewDescriptor(fmt.Sprint("inst2", instSuffix), mkind, nkind) + desc1 := metric.NewDescriptor(fmt.Sprint("inst1", instSuffix), mkind, nkind) + desc2 := metric.NewDescriptor(fmt.Sprint("inst2", instSuffix), mkind, nkind) for nc := 0; nc < nCheckpoint; nc++ { @@ -159,7 +159,7 @@ func testProcessor( _, canSub := subr.(export.Subtractor) // Allow unsupported subraction case only when it is called for. - require.True(t, mkind.PrecomputedSum() && ekind == export.DeltaExporter && !canSub) + require.True(t, mkind.PrecomputedSum() && ekind == export.DeltaExportKind && !canSub) return } else if err != nil { t.Fatal("unexpected FinishCollection error: ", err) @@ -183,7 +183,7 @@ func testProcessor( // Test the final checkpoint state. records1 := processorTest.NewOutput(label.DefaultEncoder()) - err = checkpointSet.ForEach(ekind, records1.AddRecord) + err = checkpointSet.ForEach(export.ConstantExportKindSelector(ekind), records1.AddRecord) // Test for an allowed error: if err != nil && err != aggregation.ErrNoSubtraction { @@ -196,7 +196,7 @@ func testProcessor( // number of Accumulators, unless LastValue aggregation. // If a precomputed sum, we expect cumulative inputs. if mkind.PrecomputedSum() { - if ekind == export.DeltaExporter && akind != aggregation.LastValueKind { + if ekind == export.DeltaExportKind && akind != aggregation.LastValueKind { multiplier = int64(nAccum) } else if akind == aggregation.LastValueKind { multiplier = cumulativeMultiplier @@ -204,7 +204,7 @@ func testProcessor( multiplier = cumulativeMultiplier * int64(nAccum) } } else { - if ekind == export.CumulativeExporter && akind != aggregation.LastValueKind { + if ekind == export.CumulativeExportKind && akind != aggregation.LastValueKind { multiplier = cumulativeMultiplier * int64(nAccum) } else if akind == aggregation.LastValueKind { multiplier = 1 @@ -216,7 +216,7 @@ func testProcessor( // Synchronous accumulate results from multiple accumulators, // use that number as the baseline multiplier. multiplier = int64(nAccum) - if ekind == export.CumulativeExporter { + if ekind == export.CumulativeExportKind { // If a cumulative exporter, include prior checkpoints. multiplier *= cumulativeMultiplier } @@ -258,7 +258,7 @@ func testProcessor( type bogusExporter struct{} -func (bogusExporter) ExportKindFor(*otel.Descriptor, aggregation.Kind) export.ExportKind { +func (bogusExporter) ExportKindFor(*metric.Descriptor, aggregation.Kind) export.ExportKind { return 1000000 } @@ -268,39 +268,39 @@ func (bogusExporter) Export(context.Context, export.CheckpointSet) error { func TestBasicInconsistent(t *testing.T) { // Test double-start - b := basic.New(processorTest.AggregatorSelector(), export.PassThroughExporter) + b := basic.New(processorTest.AggregatorSelector(), export.StatelessExportKindSelector()) b.StartCollection() b.StartCollection() require.Equal(t, basic.ErrInconsistentState, b.FinishCollection()) // Test finish without start - b = basic.New(processorTest.AggregatorSelector(), export.PassThroughExporter) + b = basic.New(processorTest.AggregatorSelector(), export.StatelessExportKindSelector()) require.Equal(t, basic.ErrInconsistentState, b.FinishCollection()) // Test no finish - b = basic.New(processorTest.AggregatorSelector(), export.PassThroughExporter) + b = basic.New(processorTest.AggregatorSelector(), export.StatelessExportKindSelector()) b.StartCollection() require.Equal( t, basic.ErrInconsistentState, b.ForEach( - export.PassThroughExporter, + export.StatelessExportKindSelector(), func(export.Record) error { return nil }, ), ) // Test no start - b = basic.New(processorTest.AggregatorSelector(), export.PassThroughExporter) + b = basic.New(processorTest.AggregatorSelector(), export.StatelessExportKindSelector()) - desc := otel.NewDescriptor("inst", otel.CounterInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("inst", metric.CounterInstrumentKind, number.Int64Kind) accum := export.NewAccumulation(&desc, label.EmptySet(), resource.Empty(), metrictest.NoopAggregator{}) require.Equal(t, basic.ErrInconsistentState, b.Process(accum)) // Test invalid kind: - b = basic.New(processorTest.AggregatorSelector(), export.PassThroughExporter) + b = basic.New(processorTest.AggregatorSelector(), export.StatelessExportKindSelector()) b.StartCollection() require.NoError(t, b.Process(accum)) require.NoError(t, b.FinishCollection()) @@ -309,16 +309,16 @@ func TestBasicInconsistent(t *testing.T) { bogusExporter{}, func(export.Record) error { return nil }, ) - require.True(t, errors.Is(err, basic.ErrInvalidExporterKind)) + require.True(t, errors.Is(err, basic.ErrInvalidExportKind)) } func TestBasicTimestamps(t *testing.T) { beforeNew := time.Now() - b := basic.New(processorTest.AggregatorSelector(), export.PassThroughExporter) + b := basic.New(processorTest.AggregatorSelector(), export.StatelessExportKindSelector()) afterNew := time.Now() - desc := otel.NewDescriptor("inst", otel.CounterInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("inst", metric.CounterInstrumentKind, number.Int64Kind) accum := export.NewAccumulation(&desc, label.EmptySet(), resource.Empty(), metrictest.NoopAggregator{}) b.StartCollection() @@ -327,7 +327,7 @@ func TestBasicTimestamps(t *testing.T) { var start1, end1 time.Time - require.NoError(t, b.ForEach(export.PassThroughExporter, func(rec export.Record) error { + require.NoError(t, b.ForEach(export.StatelessExportKindSelector(), func(rec export.Record) error { start1 = rec.StartTime() end1 = rec.EndTime() return nil @@ -344,7 +344,7 @@ func TestBasicTimestamps(t *testing.T) { var start2, end2 time.Time - require.NoError(t, b.ForEach(export.PassThroughExporter, func(rec export.Record) error { + require.NoError(t, b.ForEach(export.StatelessExportKindSelector(), func(rec export.Record) error { start2 = rec.StartTime() end2 = rec.EndTime() return nil @@ -362,12 +362,12 @@ func TestBasicTimestamps(t *testing.T) { func TestStatefulNoMemoryCumulative(t *testing.T) { res := resource.NewWithAttributes(label.String("R", "V")) - ekind := export.CumulativeExporter + ekindSel := export.CumulativeExportKindSelector() - desc := otel.NewDescriptor("inst.sum", otel.CounterInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("inst.sum", metric.CounterInstrumentKind, number.Int64Kind) selector := processorTest.AggregatorSelector() - processor := basic.New(selector, ekind, basic.WithMemory(false)) + processor := basic.New(selector, ekindSel, basic.WithMemory(false)) checkpointSet := processor.CheckpointSet() for i := 1; i < 3; i++ { @@ -377,7 +377,7 @@ func TestStatefulNoMemoryCumulative(t *testing.T) { // Verify zero elements records := processorTest.NewOutput(label.DefaultEncoder()) - require.NoError(t, checkpointSet.ForEach(ekind, records.AddRecord)) + require.NoError(t, checkpointSet.ForEach(ekindSel, records.AddRecord)) require.EqualValues(t, map[string]float64{}, records.Map()) // Add 10 @@ -387,7 +387,7 @@ func TestStatefulNoMemoryCumulative(t *testing.T) { // Verify one element records = processorTest.NewOutput(label.DefaultEncoder()) - require.NoError(t, checkpointSet.ForEach(ekind, records.AddRecord)) + require.NoError(t, checkpointSet.ForEach(ekindSel, records.AddRecord)) require.EqualValues(t, map[string]float64{ "inst.sum/A=B/R=V": float64(i * 10), }, records.Map()) @@ -396,12 +396,12 @@ func TestStatefulNoMemoryCumulative(t *testing.T) { func TestStatefulNoMemoryDelta(t *testing.T) { res := resource.NewWithAttributes(label.String("R", "V")) - ekind := export.DeltaExporter + ekindSel := export.DeltaExportKindSelector() - desc := otel.NewDescriptor("inst.sum", otel.SumObserverInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("inst.sum", metric.SumObserverInstrumentKind, number.Int64Kind) selector := processorTest.AggregatorSelector() - processor := basic.New(selector, ekind, basic.WithMemory(false)) + processor := basic.New(selector, ekindSel, basic.WithMemory(false)) checkpointSet := processor.CheckpointSet() for i := 1; i < 3; i++ { @@ -411,7 +411,7 @@ func TestStatefulNoMemoryDelta(t *testing.T) { // Verify zero elements records := processorTest.NewOutput(label.DefaultEncoder()) - require.NoError(t, checkpointSet.ForEach(ekind, records.AddRecord)) + require.NoError(t, checkpointSet.ForEach(ekindSel, records.AddRecord)) require.EqualValues(t, map[string]float64{}, records.Map()) // Add 10 @@ -421,7 +421,7 @@ func TestStatefulNoMemoryDelta(t *testing.T) { // Verify one element records = processorTest.NewOutput(label.DefaultEncoder()) - require.NoError(t, checkpointSet.ForEach(ekind, records.AddRecord)) + require.NoError(t, checkpointSet.ForEach(ekindSel, records.AddRecord)) require.EqualValues(t, map[string]float64{ "inst.sum/A=B/R=V": 10, }, records.Map()) @@ -429,17 +429,16 @@ func TestStatefulNoMemoryDelta(t *testing.T) { } func TestMultiObserverSum(t *testing.T) { - for _, ekind := range []export.ExportKind{ - export.PassThroughExporter, - export.CumulativeExporter, - export.DeltaExporter, + for _, ekindSel := range []export.ExportKindSelector{ + export.CumulativeExportKindSelector(), + export.DeltaExportKindSelector(), } { res := resource.NewWithAttributes(label.String("R", "V")) - desc := otel.NewDescriptor("observe.sum", otel.SumObserverInstrumentKind, otel.Int64NumberKind) + desc := metric.NewDescriptor("observe.sum", metric.SumObserverInstrumentKind, number.Int64Kind) selector := processorTest.AggregatorSelector() - processor := basic.New(selector, ekind, basic.WithMemory(false)) + processor := basic.New(selector, ekindSel, basic.WithMemory(false)) checkpointSet := processor.CheckpointSet() for i := 1; i < 3; i++ { @@ -452,13 +451,13 @@ func TestMultiObserverSum(t *testing.T) { // Multiplier is 1 for deltas, otherwise i. multiplier := i - if ekind == export.DeltaExporter { + if ekindSel.ExportKindFor(&desc, aggregation.SumKind) == export.DeltaExportKind { multiplier = 1 } // Verify one element records := processorTest.NewOutput(label.DefaultEncoder()) - require.NoError(t, checkpointSet.ForEach(ekind, records.AddRecord)) + require.NoError(t, checkpointSet.ForEach(ekindSel, records.AddRecord)) require.EqualValues(t, map[string]float64{ "observe.sum/A=B/R=V": float64(3 * 10 * multiplier), }, records.Map()) diff --git a/sdk/metric/processor/processortest/test.go b/sdk/metric/processor/processortest/test.go index 5ee33f75db6..56d5de154f6 100644 --- a/sdk/metric/processor/processortest/test.go +++ b/sdk/metric/processor/processortest/test.go @@ -21,8 +21,8 @@ import ( "sync" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/aggregator/array" @@ -39,7 +39,7 @@ type ( // unique descriptor, distinct labels, and distinct resource // attributes. mapKey struct { - desc *otel.Descriptor + desc *metric.Descriptor labels label.Distinct resource label.Distinct } @@ -161,7 +161,7 @@ func AggregatorSelector() export.AggregatorSelector { } // AggregatorFor implements export.AggregatorSelector. -func (testAggregatorSelector) AggregatorFor(desc *otel.Descriptor, aggPtrs ...*export.Aggregator) { +func (testAggregatorSelector) AggregatorFor(desc *metric.Descriptor, aggPtrs ...*export.Aggregator) { switch { case strings.HasSuffix(desc.Name(), ".disabled"): @@ -259,7 +259,7 @@ func (o *Output) AddRecord(rec export.Record) error { // is chosen, whichever is implemented by the underlying Aggregator. func (o *Output) Map() map[string]float64 { r := make(map[string]float64) - err := o.ForEach(export.PassThroughExporter, func(record export.Record) error { + err := o.ForEach(export.StatelessExportKindSelector(), func(record export.Record) error { for key, value := range o.m { encoded := value.labels.Encoded(o.labelEncoder) rencoded := value.resource.Encoded(o.labelEncoder) diff --git a/sdk/metric/processor/processortest/test_test.go b/sdk/metric/processor/processortest/test_test.go index d7ab2eee872..c4541d2656a 100644 --- a/sdk/metric/processor/processortest/test_test.go +++ b/sdk/metric/processor/processortest/test_test.go @@ -20,8 +20,8 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" export "go.opentelemetry.io/otel/sdk/export/metric" metricsdk "go.opentelemetry.io/otel/sdk/metric" processorTest "go.opentelemetry.io/otel/sdk/metric/processor/processortest" @@ -34,12 +34,12 @@ func generateTestData(proc export.Processor) { proc, resource.NewWithAttributes(label.String("R", "V")), ) - meter := otel.WrapMeterImpl(accum, "testing") + meter := metric.WrapMeterImpl(accum, "testing") - counter := otel.Must(meter).NewFloat64Counter("counter.sum") + counter := metric.Must(meter).NewFloat64Counter("counter.sum") - _ = otel.Must(meter).NewInt64SumObserver("observer.sum", - func(_ context.Context, result otel.Int64ObserverResult) { + _ = metric.Must(meter).NewInt64SumObserver("observer.sum", + func(_ context.Context, result metric.Int64ObserverResult) { result.Observe(10, label.String("K1", "V1")) result.Observe(11, label.String("K1", "V2")) }, @@ -74,7 +74,7 @@ func TestProcessorTesting(t *testing.T) { // Export the data and validate it again. exporter := processorTest.NewExporter( - export.PassThroughExporter, + export.StatelessExportKindSelector(), label.DefaultEncoder(), ) diff --git a/sdk/metric/processor/reducer/reducer.go b/sdk/metric/processor/reducer/reducer.go index 6ccbe337157..91c4dae2d52 100644 --- a/sdk/metric/processor/reducer/reducer.go +++ b/sdk/metric/processor/reducer/reducer.go @@ -15,8 +15,8 @@ package reducer // import "go.opentelemetry.io/otel/sdk/metric/processor/reducer" import ( - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" export "go.opentelemetry.io/otel/sdk/export/metric" ) @@ -31,7 +31,7 @@ type ( // LabelFilterSelector is the interface used to configure a // specific Filter to an instrument. LabelFilterSelector interface { - LabelFilterFor(descriptor *otel.Descriptor) label.Filter + LabelFilterFor(descriptor *metric.Descriptor) label.Filter } ) diff --git a/sdk/metric/processor/reducer/reducer_test.go b/sdk/metric/processor/reducer/reducer_test.go index 6c0a87301d2..138f3825dde 100644 --- a/sdk/metric/processor/reducer/reducer_test.go +++ b/sdk/metric/processor/reducer/reducer_test.go @@ -20,8 +20,8 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" export "go.opentelemetry.io/otel/sdk/export/metric" metricsdk "go.opentelemetry.io/otel/sdk/metric" "go.opentelemetry.io/otel/sdk/metric/processor/basic" @@ -45,20 +45,20 @@ var ( type testFilter struct{} -func (testFilter) LabelFilterFor(_ *otel.Descriptor) label.Filter { +func (testFilter) LabelFilterFor(_ *metric.Descriptor) label.Filter { return func(label label.KeyValue) bool { return label.Key == "A" || label.Key == "C" } } -func generateData(impl otel.MeterImpl) { +func generateData(impl metric.MeterImpl) { ctx := context.Background() - meter := otel.WrapMeterImpl(impl, "testing") + meter := metric.WrapMeterImpl(impl, "testing") - counter := otel.Must(meter).NewFloat64Counter("counter.sum") + counter := metric.Must(meter).NewFloat64Counter("counter.sum") - _ = otel.Must(meter).NewInt64SumObserver("observer.sum", - func(_ context.Context, result otel.Int64ObserverResult) { + _ = metric.Must(meter).NewInt64SumObserver("observer.sum", + func(_ context.Context, result metric.Int64ObserverResult) { result.Observe(10, kvs1...) result.Observe(10, kvs2...) }, @@ -89,7 +89,7 @@ func TestFilterProcessor(t *testing.T) { // Test a filter with the ../basic Processor. func TestFilterBasicProcessor(t *testing.T) { - basicProc := basic.New(processorTest.AggregatorSelector(), export.CumulativeExporter) + basicProc := basic.New(processorTest.AggregatorSelector(), export.CumulativeExportKindSelector()) accum := metricsdk.NewAccumulator( reducer.New(testFilter{}, basicProc), resource.NewWithAttributes(label.String("R", "V")), diff --git a/sdk/metric/sdk.go b/sdk/metric/sdk.go index 57384cbf3be..7a7b0dcc587 100644 --- a/sdk/metric/sdk.go +++ b/sdk/metric/sdk.go @@ -21,11 +21,11 @@ import ( "sync" "sync/atomic" - "go.opentelemetry.io/otel" - api "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" internal "go.opentelemetry.io/otel/internal/metric" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/metric/aggregator" "go.opentelemetry.io/otel/sdk/resource" @@ -79,7 +79,7 @@ type ( // mapkey uniquely describes a metric instrument in terms of // its InstrumentID and the encoded form of its labels. mapkey struct { - descriptor *otel.Descriptor + descriptor *metric.Descriptor ordered label.Distinct } @@ -127,7 +127,7 @@ type ( instrument struct { meter *Accumulator - descriptor otel.Descriptor + descriptor metric.Descriptor } asyncInstrument struct { @@ -149,15 +149,15 @@ type ( ) var ( - _ api.MeterImpl = &Accumulator{} - _ api.AsyncImpl = &asyncInstrument{} - _ api.SyncImpl = &syncInstrument{} - _ api.BoundSyncImpl = &record{} + _ metric.MeterImpl = &Accumulator{} + _ metric.AsyncImpl = &asyncInstrument{} + _ metric.SyncImpl = &syncInstrument{} + _ metric.BoundSyncImpl = &record{} ErrUninitializedInstrument = fmt.Errorf("use of an uninitialized instrument") ) -func (inst *instrument) Descriptor() api.Descriptor { +func (inst *instrument) Descriptor() metric.Descriptor { return inst.descriptor } @@ -169,8 +169,8 @@ func (s *syncInstrument) Implementation() interface{} { return s } -func (a *asyncInstrument) observe(number api.Number, labels *label.Set) { - if err := aggregator.RangeTest(number, &a.descriptor); err != nil { +func (a *asyncInstrument) observe(num number.Number, labels *label.Set) { + if err := aggregator.RangeTest(num, &a.descriptor); err != nil { global.Handle(err) return } @@ -180,7 +180,7 @@ func (a *asyncInstrument) observe(number api.Number, labels *label.Set) { // AggregatorSelector. return } - if err := recorder.Update(context.Background(), number, &a.descriptor); err != nil { + if err := recorder.Update(context.Background(), num, &a.descriptor); err != nil { global.Handle(err) return } @@ -293,12 +293,13 @@ func (s *syncInstrument) acquireHandle(kvs []label.KeyValue, labelPtr *label.Set } } -func (s *syncInstrument) Bind(kvs []label.KeyValue) api.BoundSyncImpl { +func (s *syncInstrument) Bind(kvs []label.KeyValue) metric.BoundSyncImpl { return s.acquireHandle(kvs, nil) } -func (s *syncInstrument) RecordOne(ctx context.Context, number api.Number, kvs []label.KeyValue) { - if s.meter.metricsLabelsEnricher != nil { +func (s *syncInstrument) RecordOne(ctx context.Context, num number.Number, kvs []label.KeyValue) { + + if s.meter.metricsLabelsEnricher != nil { var err error kvs, err = s.meter.metricsLabelsEnricher(ctx, kvs) if err != nil { @@ -309,7 +310,7 @@ func (s *syncInstrument) RecordOne(ctx context.Context, number api.Number, kvs [ h := s.acquireHandle(kvs, nil) defer h.Unbind() - h.RecordOne(ctx, number) + h.RecordOne(ctx, num) } // NewAccumulator constructs a new Accumulator for the given @@ -335,8 +336,8 @@ func NewAccumulator(processor export.Processor, resource *resource.Resource, opt } } -// NewSyncInstrument implements api.MetricImpl. -func (m *Accumulator) NewSyncInstrument(descriptor api.Descriptor) (api.SyncImpl, error) { +// NewSyncInstrument implements metric.MetricImpl. +func (m *Accumulator) NewSyncInstrument(descriptor metric.Descriptor) (metric.SyncImpl, error) { return &syncInstrument{ instrument: instrument{ descriptor: descriptor, @@ -345,8 +346,8 @@ func (m *Accumulator) NewSyncInstrument(descriptor api.Descriptor) (api.SyncImpl }, nil } -// NewAsyncInstrument implements api.MetricImpl. -func (m *Accumulator) NewAsyncInstrument(descriptor api.Descriptor, runner otel.AsyncRunner) (api.AsyncImpl, error) { +// NewAsyncInstrument implements metric.MetricImpl. +func (m *Accumulator) NewAsyncInstrument(descriptor metric.Descriptor, runner metric.AsyncRunner) (metric.AsyncImpl, error) { a := &asyncInstrument{ instrument: instrument{ descriptor: descriptor, @@ -422,7 +423,7 @@ func (m *Accumulator) collectSyncInstruments() int { } // CollectAsync implements internal.AsyncCollector. -func (m *Accumulator) CollectAsync(kv []label.KeyValue, obs ...otel.Observation) { +func (m *Accumulator) CollectAsync(kv []label.KeyValue, obs ...metric.Observation) { labels := label.NewSetWithSortable(kv, &m.asyncSortSlice) for _, ob := range obs { @@ -499,7 +500,7 @@ func (m *Accumulator) checkpointAsync(a *asyncInstrument) int { } // RecordBatch enters a batch of metric events. -func (m *Accumulator) RecordBatch(ctx context.Context, kvs []label.KeyValue, measurements ...api.Measurement) { +func (m *Accumulator) RecordBatch(ctx context.Context, kvs []label.KeyValue, measurements ...metric.Measurement) { // Labels will be computed the first time acquireHandle is // called. Subsequent calls to acquireHandle will re-use the // previously computed value instead of recomputing the @@ -522,17 +523,17 @@ func (m *Accumulator) RecordBatch(ctx context.Context, kvs []label.KeyValue, mea } } -// RecordOne implements api.SyncImpl. -func (r *record) RecordOne(ctx context.Context, number api.Number) { +// RecordOne implements metric.SyncImpl. +func (r *record) RecordOne(ctx context.Context, num number.Number) { if r.current == nil { // The instrument is disabled according to the AggregatorSelector. return } - if err := aggregator.RangeTest(number, &r.inst.descriptor); err != nil { + if err := aggregator.RangeTest(num, &r.inst.descriptor); err != nil { global.Handle(err) return } - if err := r.current.Update(ctx, number, &r.inst.descriptor); err != nil { + if err := r.current.Update(ctx, num, &r.inst.descriptor); err != nil { global.Handle(err) return } @@ -541,7 +542,7 @@ func (r *record) RecordOne(ctx context.Context, number api.Number) { atomic.AddInt64(&r.updateCount, 1) } -// Unbind implements api.SyncImpl. +// Unbind implements metric.SyncImpl. func (r *record) Unbind() { r.refMapped.unref() } @@ -555,7 +556,7 @@ func (r *record) mapkey() mapkey { // fromSync gets a sync implementation object, checking for // uninitialized instruments and instruments created by another SDK. -func (m *Accumulator) fromSync(sync otel.SyncImpl) *syncInstrument { +func (m *Accumulator) fromSync(sync metric.SyncImpl) *syncInstrument { if sync != nil { if inst, ok := sync.Implementation().(*syncInstrument); ok { return inst @@ -567,7 +568,7 @@ func (m *Accumulator) fromSync(sync otel.SyncImpl) *syncInstrument { // fromSync gets an async implementation object, checking for // uninitialized instruments and instruments created by another SDK. -func (m *Accumulator) fromAsync(async otel.AsyncImpl) *asyncInstrument { +func (m *Accumulator) fromAsync(async metric.AsyncImpl) *asyncInstrument { if async != nil { if inst, ok := async.Implementation().(*asyncInstrument); ok { return inst diff --git a/sdk/metric/selector/simple/simple.go b/sdk/metric/selector/simple/simple.go index e63e51e49f8..529dce1386e 100644 --- a/sdk/metric/selector/simple/simple.go +++ b/sdk/metric/selector/simple/simple.go @@ -15,7 +15,7 @@ package simple // import "go.opentelemetry.io/otel/sdk/metric/selector/simple" import ( - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/metric/aggregator/array" "go.opentelemetry.io/otel/sdk/metric/aggregator/ddsketch" @@ -94,11 +94,11 @@ func lastValueAggs(aggPtrs []*export.Aggregator) { } } -func (selectorInexpensive) AggregatorFor(descriptor *otel.Descriptor, aggPtrs ...*export.Aggregator) { +func (selectorInexpensive) AggregatorFor(descriptor *metric.Descriptor, aggPtrs ...*export.Aggregator) { switch descriptor.InstrumentKind() { - case otel.ValueObserverInstrumentKind: + case metric.ValueObserverInstrumentKind: lastValueAggs(aggPtrs) - case otel.ValueRecorderInstrumentKind: + case metric.ValueRecorderInstrumentKind: aggs := minmaxsumcount.New(len(aggPtrs), descriptor) for i := range aggPtrs { *aggPtrs[i] = &aggs[i] @@ -108,11 +108,11 @@ func (selectorInexpensive) AggregatorFor(descriptor *otel.Descriptor, aggPtrs .. } } -func (s selectorSketch) AggregatorFor(descriptor *otel.Descriptor, aggPtrs ...*export.Aggregator) { +func (s selectorSketch) AggregatorFor(descriptor *metric.Descriptor, aggPtrs ...*export.Aggregator) { switch descriptor.InstrumentKind() { - case otel.ValueObserverInstrumentKind: + case metric.ValueObserverInstrumentKind: lastValueAggs(aggPtrs) - case otel.ValueRecorderInstrumentKind: + case metric.ValueRecorderInstrumentKind: aggs := ddsketch.New(len(aggPtrs), descriptor, s.config) for i := range aggPtrs { *aggPtrs[i] = &aggs[i] @@ -122,11 +122,11 @@ func (s selectorSketch) AggregatorFor(descriptor *otel.Descriptor, aggPtrs ...*e } } -func (selectorExact) AggregatorFor(descriptor *otel.Descriptor, aggPtrs ...*export.Aggregator) { +func (selectorExact) AggregatorFor(descriptor *metric.Descriptor, aggPtrs ...*export.Aggregator) { switch descriptor.InstrumentKind() { - case otel.ValueObserverInstrumentKind: + case metric.ValueObserverInstrumentKind: lastValueAggs(aggPtrs) - case otel.ValueRecorderInstrumentKind: + case metric.ValueRecorderInstrumentKind: aggs := array.New(len(aggPtrs)) for i := range aggPtrs { *aggPtrs[i] = &aggs[i] @@ -136,11 +136,11 @@ func (selectorExact) AggregatorFor(descriptor *otel.Descriptor, aggPtrs ...*expo } } -func (s selectorHistogram) AggregatorFor(descriptor *otel.Descriptor, aggPtrs ...*export.Aggregator) { +func (s selectorHistogram) AggregatorFor(descriptor *metric.Descriptor, aggPtrs ...*export.Aggregator) { switch descriptor.InstrumentKind() { - case otel.ValueObserverInstrumentKind: + case metric.ValueObserverInstrumentKind: lastValueAggs(aggPtrs) - case otel.ValueRecorderInstrumentKind: + case metric.ValueRecorderInstrumentKind: aggs := histogram.New(len(aggPtrs), descriptor, s.boundaries) for i := range aggPtrs { *aggPtrs[i] = &aggs[i] diff --git a/sdk/metric/selector/simple/simple_test.go b/sdk/metric/selector/simple/simple_test.go index e13bbc28b77..6b279c62aaa 100644 --- a/sdk/metric/selector/simple/simple_test.go +++ b/sdk/metric/selector/simple/simple_test.go @@ -19,7 +19,8 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/metric/aggregator/array" "go.opentelemetry.io/otel/sdk/metric/aggregator/ddsketch" @@ -31,15 +32,15 @@ import ( ) var ( - testCounterDesc = otel.NewDescriptor("counter", otel.CounterInstrumentKind, otel.Int64NumberKind) - testUpDownCounterDesc = otel.NewDescriptor("updowncounter", otel.UpDownCounterInstrumentKind, otel.Int64NumberKind) - testSumObserverDesc = otel.NewDescriptor("sumobserver", otel.SumObserverInstrumentKind, otel.Int64NumberKind) - testUpDownSumObserverDesc = otel.NewDescriptor("updownsumobserver", otel.UpDownSumObserverInstrumentKind, otel.Int64NumberKind) - testValueRecorderDesc = otel.NewDescriptor("valuerecorder", otel.ValueRecorderInstrumentKind, otel.Int64NumberKind) - testValueObserverDesc = otel.NewDescriptor("valueobserver", otel.ValueObserverInstrumentKind, otel.Int64NumberKind) + testCounterDesc = metric.NewDescriptor("counter", metric.CounterInstrumentKind, number.Int64Kind) + testUpDownCounterDesc = metric.NewDescriptor("updowncounter", metric.UpDownCounterInstrumentKind, number.Int64Kind) + testSumObserverDesc = metric.NewDescriptor("sumobserver", metric.SumObserverInstrumentKind, number.Int64Kind) + testUpDownSumObserverDesc = metric.NewDescriptor("updownsumobserver", metric.UpDownSumObserverInstrumentKind, number.Int64Kind) + testValueRecorderDesc = metric.NewDescriptor("valuerecorder", metric.ValueRecorderInstrumentKind, number.Int64Kind) + testValueObserverDesc = metric.NewDescriptor("valueobserver", metric.ValueObserverInstrumentKind, number.Int64Kind) ) -func oneAgg(sel export.AggregatorSelector, desc *otel.Descriptor) export.Aggregator { +func oneAgg(sel export.AggregatorSelector, desc *metric.Descriptor) export.Aggregator { var agg export.Aggregator sel.AggregatorFor(desc, &agg) return agg diff --git a/sdk/metric/stress_test.go b/sdk/metric/stress_test.go index c43e6f528f4..4878435bde3 100644 --- a/sdk/metric/stress_test.go +++ b/sdk/metric/stress_test.go @@ -31,8 +31,9 @@ import ( "testing" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/metric" + "go.opentelemetry.io/otel/metric/number" export "go.opentelemetry.io/otel/sdk/export/metric" "go.opentelemetry.io/otel/sdk/export/metric/aggregation" "go.opentelemetry.io/otel/sdk/metric/processor/processortest" @@ -45,7 +46,7 @@ const ( epsilon = 1e-10 ) -var Must = otel.Must +var Must = metric.Must type ( testFixture struct { @@ -68,26 +69,26 @@ type ( testKey struct { labels string - descriptor *otel.Descriptor + descriptor *metric.Descriptor } testImpl struct { - newInstrument func(meter otel.Meter, name string) SyncImpler - getUpdateValue func() otel.Number - operate func(interface{}, context.Context, otel.Number, []label.KeyValue) + newInstrument func(meter metric.Meter, name string) SyncImpler + getUpdateValue func() number.Number + operate func(interface{}, context.Context, number.Number, []label.KeyValue) newStore func() interface{} // storeCollect and storeExpect are the same for // counters, different for lastValues, to ensure we are // testing the timestamps correctly. - storeCollect func(store interface{}, value otel.Number, ts time.Time) - storeExpect func(store interface{}, value otel.Number) - readStore func(store interface{}) otel.Number - equalValues func(a, b otel.Number) bool + storeCollect func(store interface{}, value number.Number, ts time.Time) + storeExpect func(store interface{}, value number.Number) + readStore func(store interface{}) number.Number + equalValues func(a, b number.Number) bool } SyncImpler interface { - SyncImpl() otel.SyncImpl + SyncImpl() metric.SyncImpl } // lastValueState supports merging lastValue values, for the case @@ -95,7 +96,7 @@ type ( // take the later timestamp. lastValueState struct { // raw has to be aligned for 64-bit atomic operations. - raw otel.Number + raw number.Number ts time.Time } ) @@ -156,11 +157,11 @@ func (f *testFixture) someLabels() []label.KeyValue { } } -func (f *testFixture) startWorker(impl *Accumulator, meter otel.Meter, wg *sync.WaitGroup, i int) { +func (f *testFixture) startWorker(impl *Accumulator, meter metric.Meter, wg *sync.WaitGroup, i int) { ctx := context.Background() name := fmt.Sprint("test_", i) instrument := f.impl.newInstrument(meter, name) - var descriptor *otel.Descriptor + var descriptor *metric.Descriptor if ii, ok := instrument.SyncImpl().(*syncInstrument); ok { descriptor = &ii.descriptor } @@ -264,13 +265,13 @@ func (f *testFixture) Process(accumulation export.Accumulation) error { agg := accumulation.Aggregator() switch accumulation.Descriptor().InstrumentKind() { - case otel.CounterInstrumentKind: + case metric.CounterInstrumentKind: sum, err := agg.(aggregation.Sum).Sum() if err != nil { f.T.Fatal("Sum error: ", err) } f.impl.storeCollect(actual, sum, time.Time{}) - case otel.ValueRecorderInstrumentKind: + case metric.ValueRecorderInstrumentKind: lv, ts, err := agg.(aggregation.LastValue).LastValue() if err != nil && err != aggregation.ErrNoData { f.T.Fatal("Last value error: ", err) @@ -294,7 +295,7 @@ func stressTest(t *testing.T, impl testImpl) { cc := concurrency() sdk := NewAccumulator(fixture, nil) - meter := otel.WrapMeterImpl(sdk, "stress_test") + meter := metric.WrapMeterImpl(sdk, "stress_test") fixture.wg.Add(cc + 1) for i := 0; i < cc; i++ { @@ -326,11 +327,11 @@ func stressTest(t *testing.T, impl testImpl) { fixture.assertTest(numCollect) } -func int64sEqual(a, b otel.Number) bool { +func int64sEqual(a, b number.Number) bool { return a.AsInt64() == b.AsInt64() } -func float64sEqual(a, b otel.Number) bool { +func float64sEqual(a, b number.Number) bool { diff := math.Abs(a.AsFloat64() - b.AsFloat64()) return diff < math.Abs(a.AsFloat64())*epsilon } @@ -339,33 +340,33 @@ func float64sEqual(a, b otel.Number) bool { func intCounterTestImpl() testImpl { return testImpl{ - newInstrument: func(meter otel.Meter, name string) SyncImpler { + newInstrument: func(meter metric.Meter, name string) SyncImpler { return Must(meter).NewInt64Counter(name + ".sum") }, - getUpdateValue: func() otel.Number { + getUpdateValue: func() number.Number { for { x := int64(rand.Intn(100)) if x != 0 { - return otel.NewInt64Number(x) + return number.NewInt64Number(x) } } }, - operate: func(inst interface{}, ctx context.Context, value otel.Number, labels []label.KeyValue) { - counter := inst.(otel.Int64Counter) + operate: func(inst interface{}, ctx context.Context, value number.Number, labels []label.KeyValue) { + counter := inst.(metric.Int64Counter) counter.Add(ctx, value.AsInt64(), labels...) }, newStore: func() interface{} { - n := otel.NewInt64Number(0) + n := number.NewInt64Number(0) return &n }, - storeCollect: func(store interface{}, value otel.Number, _ time.Time) { - store.(*otel.Number).AddInt64Atomic(value.AsInt64()) + storeCollect: func(store interface{}, value number.Number, _ time.Time) { + store.(*number.Number).AddInt64Atomic(value.AsInt64()) }, - storeExpect: func(store interface{}, value otel.Number) { - store.(*otel.Number).AddInt64Atomic(value.AsInt64()) + storeExpect: func(store interface{}, value number.Number) { + store.(*number.Number).AddInt64Atomic(value.AsInt64()) }, - readStore: func(store interface{}) otel.Number { - return store.(*otel.Number).AsNumberAtomic() + readStore: func(store interface{}) number.Number { + return store.(*number.Number).AsNumberAtomic() }, equalValues: int64sEqual, } @@ -377,33 +378,33 @@ func TestStressInt64Counter(t *testing.T) { func floatCounterTestImpl() testImpl { return testImpl{ - newInstrument: func(meter otel.Meter, name string) SyncImpler { + newInstrument: func(meter metric.Meter, name string) SyncImpler { return Must(meter).NewFloat64Counter(name + ".sum") }, - getUpdateValue: func() otel.Number { + getUpdateValue: func() number.Number { for { x := rand.Float64() if x != 0 { - return otel.NewFloat64Number(x) + return number.NewFloat64Number(x) } } }, - operate: func(inst interface{}, ctx context.Context, value otel.Number, labels []label.KeyValue) { - counter := inst.(otel.Float64Counter) + operate: func(inst interface{}, ctx context.Context, value number.Number, labels []label.KeyValue) { + counter := inst.(metric.Float64Counter) counter.Add(ctx, value.AsFloat64(), labels...) }, newStore: func() interface{} { - n := otel.NewFloat64Number(0.0) + n := number.NewFloat64Number(0.0) return &n }, - storeCollect: func(store interface{}, value otel.Number, _ time.Time) { - store.(*otel.Number).AddFloat64Atomic(value.AsFloat64()) + storeCollect: func(store interface{}, value number.Number, _ time.Time) { + store.(*number.Number).AddFloat64Atomic(value.AsFloat64()) }, - storeExpect: func(store interface{}, value otel.Number) { - store.(*otel.Number).AddFloat64Atomic(value.AsFloat64()) + storeExpect: func(store interface{}, value number.Number) { + store.(*number.Number).AddFloat64Atomic(value.AsFloat64()) }, - readStore: func(store interface{}) otel.Number { - return store.(*otel.Number).AsNumberAtomic() + readStore: func(store interface{}) number.Number { + return store.(*number.Number).AsNumberAtomic() }, equalValues: float64sEqual, } @@ -417,23 +418,23 @@ func TestStressFloat64Counter(t *testing.T) { func intLastValueTestImpl() testImpl { return testImpl{ - newInstrument: func(meter otel.Meter, name string) SyncImpler { + newInstrument: func(meter metric.Meter, name string) SyncImpler { return Must(meter).NewInt64ValueRecorder(name + ".lastvalue") }, - getUpdateValue: func() otel.Number { + getUpdateValue: func() number.Number { r1 := rand.Int63() - return otel.NewInt64Number(rand.Int63() - r1) + return number.NewInt64Number(rand.Int63() - r1) }, - operate: func(inst interface{}, ctx context.Context, value otel.Number, labels []label.KeyValue) { - valuerecorder := inst.(otel.Int64ValueRecorder) + operate: func(inst interface{}, ctx context.Context, value number.Number, labels []label.KeyValue) { + valuerecorder := inst.(metric.Int64ValueRecorder) valuerecorder.Record(ctx, value.AsInt64(), labels...) }, newStore: func() interface{} { return &lastValueState{ - raw: otel.NewInt64Number(0), + raw: number.NewInt64Number(0), } }, - storeCollect: func(store interface{}, value otel.Number, ts time.Time) { + storeCollect: func(store interface{}, value number.Number, ts time.Time) { gs := store.(*lastValueState) if !ts.Before(gs.ts) { @@ -441,11 +442,11 @@ func intLastValueTestImpl() testImpl { gs.raw.SetInt64Atomic(value.AsInt64()) } }, - storeExpect: func(store interface{}, value otel.Number) { + storeExpect: func(store interface{}, value number.Number) { gs := store.(*lastValueState) gs.raw.SetInt64Atomic(value.AsInt64()) }, - readStore: func(store interface{}) otel.Number { + readStore: func(store interface{}) number.Number { gs := store.(*lastValueState) return gs.raw.AsNumberAtomic() }, @@ -459,22 +460,22 @@ func TestStressInt64LastValue(t *testing.T) { func floatLastValueTestImpl() testImpl { return testImpl{ - newInstrument: func(meter otel.Meter, name string) SyncImpler { + newInstrument: func(meter metric.Meter, name string) SyncImpler { return Must(meter).NewFloat64ValueRecorder(name + ".lastvalue") }, - getUpdateValue: func() otel.Number { - return otel.NewFloat64Number((-0.5 + rand.Float64()) * 100000) + getUpdateValue: func() number.Number { + return number.NewFloat64Number((-0.5 + rand.Float64()) * 100000) }, - operate: func(inst interface{}, ctx context.Context, value otel.Number, labels []label.KeyValue) { - valuerecorder := inst.(otel.Float64ValueRecorder) + operate: func(inst interface{}, ctx context.Context, value number.Number, labels []label.KeyValue) { + valuerecorder := inst.(metric.Float64ValueRecorder) valuerecorder.Record(ctx, value.AsFloat64(), labels...) }, newStore: func() interface{} { return &lastValueState{ - raw: otel.NewFloat64Number(0), + raw: number.NewFloat64Number(0), } }, - storeCollect: func(store interface{}, value otel.Number, ts time.Time) { + storeCollect: func(store interface{}, value number.Number, ts time.Time) { gs := store.(*lastValueState) if !ts.Before(gs.ts) { @@ -482,11 +483,11 @@ func floatLastValueTestImpl() testImpl { gs.raw.SetFloat64Atomic(value.AsFloat64()) } }, - storeExpect: func(store interface{}, value otel.Number) { + storeExpect: func(store interface{}, value number.Number) { gs := store.(*lastValueState) gs.raw.SetFloat64Atomic(value.AsFloat64()) }, - readStore: func(store interface{}) otel.Number { + readStore: func(store interface{}) number.Number { gs := store.(*lastValueState) return gs.raw.AsNumberAtomic() }, diff --git a/sdk/trace/batch_span_processor_test.go b/sdk/trace/batch_span_processor_test.go index 173903b8e03..f240c694682 100644 --- a/sdk/trace/batch_span_processor_test.go +++ b/sdk/trace/batch_span_processor_test.go @@ -21,7 +21,8 @@ import ( "testing" "time" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" + export "go.opentelemetry.io/otel/sdk/export/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace" ) @@ -190,15 +191,15 @@ func createAndRegisterBatchSP(option testOption, te *testBatchExporter) *sdktrac return sdktrace.NewBatchSpanProcessor(te, options...) } -func generateSpan(t *testing.T, parallel bool, tr otel.Tracer, option testOption) { +func generateSpan(t *testing.T, parallel bool, tr trace.Tracer, option testOption) { sc := getSpanContext() wg := &sync.WaitGroup{} for i := 0; i < option.genNumSpans; i++ { binary.BigEndian.PutUint64(sc.TraceID[0:8], uint64(i+1)) wg.Add(1) - f := func(sc otel.SpanContext) { - ctx := otel.ContextWithRemoteSpanContext(context.Background(), sc) + f := func(sc trace.SpanContext) { + ctx := trace.ContextWithRemoteSpanContext(context.Background(), sc) _, span := tr.Start(ctx, option.name) span.End() wg.Done() @@ -212,10 +213,10 @@ func generateSpan(t *testing.T, parallel bool, tr otel.Tracer, option testOption wg.Wait() } -func getSpanContext() otel.SpanContext { - tid, _ := otel.TraceIDFromHex("01020304050607080102040810203040") - sid, _ := otel.SpanIDFromHex("0102040810203040") - return otel.SpanContext{ +func getSpanContext() trace.SpanContext { + tid, _ := trace.TraceIDFromHex("01020304050607080102040810203040") + sid, _ := trace.SpanIDFromHex("0102040810203040") + return trace.SpanContext{ TraceID: tid, SpanID: sid, TraceFlags: 0x1, diff --git a/sdk/trace/benchmark_test.go b/sdk/trace/benchmark_test.go index 4e6dcf1b267..15061e21b85 100644 --- a/sdk/trace/benchmark_test.go +++ b/sdk/trace/benchmark_test.go @@ -18,13 +18,14 @@ import ( "context" "testing" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" + sdktrace "go.opentelemetry.io/otel/sdk/trace" ) func BenchmarkStartEndSpan(b *testing.B) { - traceBenchmark(b, "Benchmark StartEndSpan", func(b *testing.B, t otel.Tracer) { + traceBenchmark(b, "Benchmark StartEndSpan", func(b *testing.B, t trace.Tracer) { ctx := context.Background() b.ResetTimer() for i := 0; i < b.N; i++ { @@ -35,7 +36,7 @@ func BenchmarkStartEndSpan(b *testing.B) { } func BenchmarkSpanWithAttributes_4(b *testing.B) { - traceBenchmark(b, "Benchmark Start With 4 Attributes", func(b *testing.B, t otel.Tracer) { + traceBenchmark(b, "Benchmark Start With 4 Attributes", func(b *testing.B, t trace.Tracer) { ctx := context.Background() b.ResetTimer() @@ -53,7 +54,7 @@ func BenchmarkSpanWithAttributes_4(b *testing.B) { } func BenchmarkSpanWithAttributes_8(b *testing.B) { - traceBenchmark(b, "Benchmark Start With 8 Attributes", func(b *testing.B, t otel.Tracer) { + traceBenchmark(b, "Benchmark Start With 8 Attributes", func(b *testing.B, t trace.Tracer) { ctx := context.Background() b.ResetTimer() @@ -75,7 +76,7 @@ func BenchmarkSpanWithAttributes_8(b *testing.B) { } func BenchmarkSpanWithAttributes_all(b *testing.B) { - traceBenchmark(b, "Benchmark Start With all Attribute types", func(b *testing.B, t otel.Tracer) { + traceBenchmark(b, "Benchmark Start With all Attribute types", func(b *testing.B, t trace.Tracer) { ctx := context.Background() b.ResetTimer() @@ -99,7 +100,7 @@ func BenchmarkSpanWithAttributes_all(b *testing.B) { } func BenchmarkSpanWithAttributes_all_2x(b *testing.B) { - traceBenchmark(b, "Benchmark Start With all Attributes types twice", func(b *testing.B, t otel.Tracer) { + traceBenchmark(b, "Benchmark Start With all Attributes types twice", func(b *testing.B, t trace.Tracer) { ctx := context.Background() b.ResetTimer() @@ -133,8 +134,8 @@ func BenchmarkSpanWithAttributes_all_2x(b *testing.B) { } func BenchmarkTraceID_DotString(b *testing.B) { - t, _ := otel.TraceIDFromHex("0000000000000001000000000000002a") - sc := otel.SpanContext{TraceID: t} + t, _ := trace.TraceIDFromHex("0000000000000001000000000000002a") + sc := trace.SpanContext{TraceID: t} want := "0000000000000001000000000000002a" for i := 0; i < b.N; i++ { @@ -145,7 +146,7 @@ func BenchmarkTraceID_DotString(b *testing.B) { } func BenchmarkSpanID_DotString(b *testing.B) { - sc := otel.SpanContext{SpanID: otel.SpanID{1}} + sc := trace.SpanContext{SpanID: trace.SpanID{1}} want := "0100000000000000" for i := 0; i < b.N; i++ { if got := sc.SpanID.String(); got != want { @@ -154,7 +155,7 @@ func BenchmarkSpanID_DotString(b *testing.B) { } } -func traceBenchmark(b *testing.B, name string, fn func(*testing.B, otel.Tracer)) { +func traceBenchmark(b *testing.B, name string, fn func(*testing.B, trace.Tracer)) { b.Run("AlwaysSample", func(b *testing.B) { b.ReportAllocs() fn(b, tracer(b, name, sdktrace.AlwaysSample())) @@ -165,7 +166,7 @@ func traceBenchmark(b *testing.B, name string, fn func(*testing.B, otel.Tracer)) }) } -func tracer(b *testing.B, name string, sampler sdktrace.Sampler) otel.Tracer { +func tracer(b *testing.B, name string, sampler sdktrace.Sampler) trace.Tracer { tp := sdktrace.NewTracerProvider(sdktrace.WithConfig(sdktrace.Config{DefaultSampler: sampler})) return tp.Tracer(name) } diff --git a/sdk/trace/config.go b/sdk/trace/config.go index a809376b0cc..3fd37de24c9 100644 --- a/sdk/trace/config.go +++ b/sdk/trace/config.go @@ -42,11 +42,11 @@ type Config struct { const ( // DefaultMaxEventsPerSpan is default max number of message events per span - DefaultMaxEventsPerSpan = 128 + DefaultMaxEventsPerSpan = 1000 // DefaultMaxAttributesPerSpan is default max number of attributes per span - DefaultMaxAttributesPerSpan = 32 + DefaultMaxAttributesPerSpan = 1000 // DefaultMaxLinksPerSpan is default max number of links per span - DefaultMaxLinksPerSpan = 32 + DefaultMaxLinksPerSpan = 1000 ) diff --git a/sdk/trace/id_generator.go b/sdk/trace/id_generator.go index c5ab4bf4b7c..3a4abe62833 100644 --- a/sdk/trace/id_generator.go +++ b/sdk/trace/id_generator.go @@ -18,7 +18,8 @@ import ( "math/rand" "sync" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" + "go.opentelemetry.io/otel/sdk/trace/internal" ) @@ -30,20 +31,20 @@ type defaultIDGenerator struct { var _ internal.IDGenerator = &defaultIDGenerator{} // NewSpanID returns a non-zero span ID from a randomly-chosen sequence. -func (gen *defaultIDGenerator) NewSpanID() otel.SpanID { +func (gen *defaultIDGenerator) NewSpanID() trace.SpanID { gen.Lock() defer gen.Unlock() - sid := otel.SpanID{} + sid := trace.SpanID{} gen.randSource.Read(sid[:]) return sid } // NewTraceID returns a non-zero trace ID from a randomly-chosen sequence. // mu should be held while this function is called. -func (gen *defaultIDGenerator) NewTraceID() otel.TraceID { +func (gen *defaultIDGenerator) NewTraceID() trace.TraceID { gen.Lock() defer gen.Unlock() - tid := otel.TraceID{} + tid := trace.TraceID{} gen.randSource.Read(tid[:]) return tid } diff --git a/sdk/trace/internal/internal.go b/sdk/trace/internal/internal.go index da9f13d6bd3..08898efae35 100644 --- a/sdk/trace/internal/internal.go +++ b/sdk/trace/internal/internal.go @@ -15,10 +15,10 @@ // Package internal provides trace internals. package internal -import "go.opentelemetry.io/otel" +import "go.opentelemetry.io/otel/trace" // IDGenerator allows custom generators for TraceId and SpanId. type IDGenerator interface { - NewTraceID() otel.TraceID - NewSpanID() otel.SpanID + NewTraceID() trace.TraceID + NewSpanID() trace.SpanID } diff --git a/sdk/trace/provider.go b/sdk/trace/provider.go index 7fa9af65c97..267a0d36fbe 100644 --- a/sdk/trace/provider.go +++ b/sdk/trace/provider.go @@ -19,8 +19,9 @@ import ( "sync" "sync/atomic" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/global" + "go.opentelemetry.io/otel/trace" + export "go.opentelemetry.io/otel/sdk/export/trace" "go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/resource" @@ -48,7 +49,7 @@ type TracerProvider struct { config atomic.Value // access atomically } -var _ otel.TracerProvider = &TracerProvider{} +var _ trace.TracerProvider = &TracerProvider{} // NewTracerProvider creates an instance of trace provider. Optional // parameter configures the provider with common options applicable @@ -82,8 +83,8 @@ func NewTracerProvider(opts ...TracerProviderOption) *TracerProvider { // Tracer with the given name. If a tracer for the given name does not exist, // it is created first. If the name is empty, DefaultTracerName is used. -func (p *TracerProvider) Tracer(name string, opts ...otel.TracerOption) otel.Tracer { - c := otel.NewTracerConfig(opts...) +func (p *TracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer { + c := trace.NewTracerConfig(opts...) p.mu.Lock() defer p.mu.Unlock() diff --git a/sdk/trace/sampling.go b/sdk/trace/sampling.go index 437f7aa70f7..e66dd65ec0c 100644 --- a/sdk/trace/sampling.go +++ b/sdk/trace/sampling.go @@ -18,8 +18,8 @@ import ( "encoding/binary" "fmt" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" ) // Sampler decides whether a trace should be sampled and exported. @@ -30,13 +30,13 @@ type Sampler interface { // SamplingParameters contains the values passed to a Sampler. type SamplingParameters struct { - ParentContext otel.SpanContext - TraceID otel.TraceID + ParentContext trace.SpanContext + TraceID trace.TraceID Name string HasRemoteParent bool - Kind otel.SpanKind + Kind trace.SpanKind Attributes []label.KeyValue - Links []otel.Link + Links []trace.Link } // SamplingDecision indicates whether a span is dropped, recorded and/or sampled. diff --git a/sdk/trace/sampling_test.go b/sdk/trace/sampling_test.go index f4fb817426f..3c998773327 100644 --- a/sdk/trace/sampling_test.go +++ b/sdk/trace/sampling_test.go @@ -21,17 +21,17 @@ import ( "github.com/stretchr/testify/require" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" ) func TestParentBasedDefaultLocalParentSampled(t *testing.T) { sampler := ParentBased(AlwaysSample()) - traceID, _ := otel.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") - spanID, _ := otel.SpanIDFromHex("00f067aa0ba902b7") - parentCtx := otel.SpanContext{ + traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") + spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7") + parentCtx := trace.SpanContext{ TraceID: traceID, SpanID: spanID, - TraceFlags: otel.FlagsSampled, + TraceFlags: trace.FlagsSampled, } if sampler.ShouldSample(SamplingParameters{ParentContext: parentCtx}).Decision != RecordAndSample { t.Error("Sampling decision should be RecordAndSample") @@ -40,9 +40,9 @@ func TestParentBasedDefaultLocalParentSampled(t *testing.T) { func TestParentBasedDefaultLocalParentNotSampled(t *testing.T) { sampler := ParentBased(AlwaysSample()) - traceID, _ := otel.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") - spanID, _ := otel.SpanIDFromHex("00f067aa0ba902b7") - parentCtx := otel.SpanContext{ + traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") + spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7") + parentCtx := trace.SpanContext{ TraceID: traceID, SpanID: spanID, } @@ -104,15 +104,15 @@ func TestParentBasedWithSamplerOptions(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - traceID, _ := otel.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") - spanID, _ := otel.SpanIDFromHex("00f067aa0ba902b7") - parentCtx := otel.SpanContext{ + traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736") + spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7") + parentCtx := trace.SpanContext{ TraceID: traceID, SpanID: spanID, } if tc.isParentSampled { - parentCtx.TraceFlags = otel.FlagsSampled + parentCtx.TraceFlags = trace.FlagsSampled } params := SamplingParameters{ParentContext: parentCtx} diff --git a/sdk/trace/simple_span_processor_test.go b/sdk/trace/simple_span_processor_test.go index 98b570308a5..8abbad213ed 100644 --- a/sdk/trace/simple_span_processor_test.go +++ b/sdk/trace/simple_span_processor_test.go @@ -18,7 +18,8 @@ import ( "context" "testing" - "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/trace" + export "go.opentelemetry.io/otel/sdk/export/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace" ) @@ -60,14 +61,14 @@ func TestSimpleSpanProcessorOnEnd(t *testing.T) { tp.RegisterSpanProcessor(ssp) tr := tp.Tracer("SimpleSpanProcessor") - tid, _ := otel.TraceIDFromHex("01020304050607080102040810203040") - sid, _ := otel.SpanIDFromHex("0102040810203040") - sc := otel.SpanContext{ + tid, _ := trace.TraceIDFromHex("01020304050607080102040810203040") + sid, _ := trace.SpanIDFromHex("0102040810203040") + sc := trace.SpanContext{ TraceID: tid, SpanID: sid, TraceFlags: 0x1, } - ctx := otel.ContextWithRemoteSpanContext(context.Background(), sc) + ctx := trace.ContextWithRemoteSpanContext(context.Background(), sc) _, span := tr.Start(ctx, "OnEnd") span.End() diff --git a/sdk/trace/span.go b/sdk/trace/span.go index 18d5d1a3f0e..120bd498d6b 100644 --- a/sdk/trace/span.go +++ b/sdk/trace/span.go @@ -21,10 +21,11 @@ import ( "sync" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" + "go.opentelemetry.io/otel/trace" + export "go.opentelemetry.io/otel/sdk/export/trace" "go.opentelemetry.io/otel/sdk/internal" ) @@ -35,19 +36,21 @@ const ( errorEventName = "error" ) -var emptySpanContext = otel.SpanContext{} +var emptySpanContext = trace.SpanContext{} // span is an implementation of the OpenTelemetry Span API representing the // individual component of a trace. type span struct { + // mu protects the contents of this span. + mu sync.Mutex + // data contains information recorded about the span. // // It will be non-nil if we are exporting the span or recording events for it. // Otherwise, data is nil, and the span is simply a carrier for the // SpanContext, so that the trace ID is propagated. data *export.SpanData - mu sync.Mutex // protects the contents of *data (but not the pointer value.) - spanContext otel.SpanContext + spanContext trace.SpanContext // attributes are capped at configured limit. When the capacity is reached an oldest entry // is removed to create room for a new entry. @@ -59,19 +62,21 @@ type span struct { // links are stored in FIFO queue capped by configured limit. links *evictedQueue - // spanStore is the spanStore this span belongs to, if any, otherwise it is nil. - //*spanStore + // endOnce ensures End is only called once. endOnce sync.Once - executionTracerTaskEnd func() // ends the execution tracer span - tracer *tracer // tracer used to create span. + // executionTracerTaskEnd ends the execution tracer span. + executionTracerTaskEnd func() + + // tracer is the SDK tracer that created this span. + tracer *tracer } -var _ otel.Span = &span{} +var _ trace.Span = &span{} -func (s *span) SpanContext() otel.SpanContext { +func (s *span) SpanContext() trace.SpanContext { if s == nil { - return otel.SpanContext{} + return trace.SpanContext{} } return s.spanContext } @@ -110,7 +115,7 @@ func (s *span) SetAttributes(attributes ...label.KeyValue) { // // If this method is called while panicking an error event is added to the // Span before ending it and the panic is continued. -func (s *span) End(options ...otel.SpanOption) { +func (s *span) End(options ...trace.SpanOption) { if s == nil { return } @@ -120,7 +125,7 @@ func (s *span) End(options ...otel.SpanOption) { defer panic(recovered) s.addEvent( errorEventName, - otel.WithAttributes( + trace.WithAttributes( errorTypeKey.String(typeStr(recovered)), errorMessageKey.String(fmt.Sprint(recovered)), ), @@ -133,7 +138,7 @@ func (s *span) End(options ...otel.SpanOption) { if !s.IsRecording() { return } - config := otel.NewSpanConfig(options...) + config := trace.NewSpanConfig(options...) s.endOnce.Do(func() { sps, ok := s.tracer.provider.spanProcessors.Load().(spanProcessorStates) mustExportOrProcess := ok && len(sps) > 0 @@ -151,13 +156,13 @@ func (s *span) End(options ...otel.SpanOption) { }) } -func (s *span) RecordError(err error, opts ...otel.EventOption) { +func (s *span) RecordError(err error, opts ...trace.EventOption) { if s == nil || err == nil || !s.IsRecording() { return } s.SetStatus(codes.Error, "") - opts = append(opts, otel.WithAttributes( + opts = append(opts, trace.WithAttributes( errorTypeKey.String(typeStr(err)), errorMessageKey.String(err.Error()), )) @@ -173,19 +178,19 @@ func typeStr(i interface{}) string { return fmt.Sprintf("%s.%s", t.PkgPath(), t.Name()) } -func (s *span) Tracer() otel.Tracer { +func (s *span) Tracer() trace.Tracer { return s.tracer } -func (s *span) AddEvent(name string, o ...otel.EventOption) { +func (s *span) AddEvent(name string, o ...trace.EventOption) { if !s.IsRecording() { return } s.addEvent(name, o...) } -func (s *span) addEvent(name string, o ...otel.EventOption) { - c := otel.NewEventConfig(o...) +func (s *span) addEvent(name string, o ...trace.EventOption) { + c := trace.NewEventConfig(o...) s.mu.Lock() defer s.mu.Unlock() @@ -209,12 +214,11 @@ func (s *span) SetName(name string) { s.data.Name = name // SAMPLING noParent := !s.data.ParentSpanID.IsValid() - var ctx otel.SpanContext + var ctx trace.SpanContext if noParent { - ctx = otel.SpanContext{} + ctx = trace.SpanContext{} } else { // FIXME: Where do we get the parent context from? - // From SpanStore? ctx = s.data.SpanContext } data := samplingData{ @@ -237,7 +241,7 @@ func (s *span) SetName(name string) { } } -func (s *span) addLink(link otel.Link) { +func (s *span) addLink(link trace.Link) { if !s.IsRecording() { return } @@ -267,10 +271,10 @@ func (s *span) makeSpanData() *export.SpanData { return &sd } -func (s *span) interfaceArrayToLinksArray() []otel.Link { - linkArr := make([]otel.Link, 0) +func (s *span) interfaceArrayToLinksArray() []trace.Link { + linkArr := make([]trace.Link, 0) for _, value := range s.links.queue { - linkArr = append(linkArr, value.(otel.Link)) + linkArr = append(linkArr, value.(trace.Link)) } return linkArr } @@ -302,7 +306,7 @@ func (s *span) addChild() { s.mu.Unlock() } -func startSpanInternal(tr *tracer, name string, parent otel.SpanContext, remoteParent bool, o *otel.SpanConfig) *span { +func startSpanInternal(tr *tracer, name string, parent trace.SpanContext, remoteParent bool, o *trace.SpanConfig) *span { var noParent bool span := &span{} span.spanContext = parent @@ -327,8 +331,6 @@ func startSpanInternal(tr *tracer, name string, parent otel.SpanContext, remoteP } sampled := makeSamplingDecision(data) - // TODO: [rghetia] restore when spanstore is added. - // if !internal.LocalSpanStoreEnabled && !span.spanContext.IsSampled() && !o.Record { if !span.spanContext.IsSampled() && !o.Record { return span } @@ -340,7 +342,7 @@ func startSpanInternal(tr *tracer, name string, parent otel.SpanContext, remoteP span.data = &export.SpanData{ SpanContext: span.spanContext, StartTime: startTime, - SpanKind: otel.ValidateSpanKind(o.SpanKind), + SpanKind: trace.ValidateSpanKind(o.SpanKind), Name: name, HasRemoteParent: remoteParent, Resource: cfg.Resource, @@ -355,14 +357,6 @@ func startSpanInternal(tr *tracer, name string, parent otel.SpanContext, remoteP if !noParent { span.data.ParentSpanID = parent.SpanID } - // TODO: [rghetia] restore when spanstore is added. - //if internal.LocalSpanStoreEnabled { - // ss := spanStoreForNameCreateIfNew(name) - // if ss != nil { - // span.spanStore = ss - // ss.add(span) - // } - //} return span } @@ -370,13 +364,13 @@ func startSpanInternal(tr *tracer, name string, parent otel.SpanContext, remoteP type samplingData struct { noParent bool remoteParent bool - parent otel.SpanContext + parent trace.SpanContext name string cfg *Config span *span attributes []label.KeyValue - links []otel.Link - kind otel.SpanKind + links []trace.Link + kind trace.SpanKind } func makeSamplingDecision(data samplingData) SamplingResult { @@ -392,9 +386,9 @@ func makeSamplingDecision(data samplingData) SamplingResult { Links: data.links, }) if sampled.Decision == RecordAndSample { - spanContext.TraceFlags |= otel.FlagsSampled + spanContext.TraceFlags |= trace.FlagsSampled } else { - spanContext.TraceFlags &^= otel.FlagsSampled + spanContext.TraceFlags &^= trace.FlagsSampled } return sampled } diff --git a/sdk/trace/trace_test.go b/sdk/trace/trace_test.go index f12ab6db3f8..af904ebb349 100644 --- a/sdk/trace/trace_test.go +++ b/sdk/trace/trace_test.go @@ -25,11 +25,11 @@ import ( "testing" "time" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/global" "go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/oteltest" + "go.opentelemetry.io/otel/trace" "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" @@ -42,8 +42,8 @@ import ( ) var ( - tid otel.TraceID - sid otel.SpanID + tid trace.TraceID + sid trace.SpanID ) type discardHandler struct{} @@ -51,8 +51,8 @@ type discardHandler struct{} func (*discardHandler) Handle(_ error) {} func init() { - tid, _ = otel.TraceIDFromHex("01020304050607080102040810203040") - sid, _ = otel.SpanIDFromHex("0102040810203040") + tid, _ = trace.TraceIDFromHex("01020304050607080102040810203040") + sid, _ = trace.SpanIDFromHex("0102040810203040") global.SetErrorHandler(new(discardHandler)) } @@ -60,7 +60,7 @@ func init() { func TestTracerFollowsExpectedAPIBehaviour(t *testing.T) { tp := NewTracerProvider(WithConfig(Config{DefaultSampler: TraceIDRatioBased(0)})) harness := oteltest.NewHarness(t) - subjectFactory := func() otel.Tracer { + subjectFactory := func() trace.Tracer { return tp.Tracer("") } @@ -263,14 +263,14 @@ func TestSampling(t *testing.T) { for i := 0; i < total; i++ { ctx := context.Background() if tc.parent { - psc := otel.SpanContext{ + psc := trace.SpanContext{ TraceID: idg.NewTraceID(), SpanID: idg.NewSpanID(), } if tc.sampledParent { - psc.TraceFlags = otel.FlagsSampled + psc.TraceFlags = trace.FlagsSampled } - ctx = otel.ContextWithRemoteSpanContext(ctx, psc) + ctx = trace.ContextWithRemoteSpanContext(ctx, psc) } _, span := tr.Start(ctx, "test") if span.SpanContext().IsSampled() { @@ -299,33 +299,33 @@ func TestStartSpanWithParent(t *testing.T) { tr := tp.Tracer("SpanWithParent") ctx := context.Background() - sc1 := otel.SpanContext{ + sc1 := trace.SpanContext{ TraceID: tid, SpanID: sid, TraceFlags: 0x1, } - _, s1 := tr.Start(otel.ContextWithRemoteSpanContext(ctx, sc1), "span1-unsampled-parent1") + _, s1 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc1), "span1-unsampled-parent1") if err := checkChild(sc1, s1); err != nil { t.Error(err) } - _, s2 := tr.Start(otel.ContextWithRemoteSpanContext(ctx, sc1), "span2-unsampled-parent1") + _, s2 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc1), "span2-unsampled-parent1") if err := checkChild(sc1, s2); err != nil { t.Error(err) } - sc2 := otel.SpanContext{ + sc2 := trace.SpanContext{ TraceID: tid, SpanID: sid, TraceFlags: 0x1, //Tracestate: testTracestate, } - _, s3 := tr.Start(otel.ContextWithRemoteSpanContext(ctx, sc2), "span3-sampled-parent2") + _, s3 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc2), "span3-sampled-parent2") if err := checkChild(sc2, s3); err != nil { t.Error(err) } - ctx2, s4 := tr.Start(otel.ContextWithRemoteSpanContext(ctx, sc2), "span4-sampled-parent2") + ctx2, s4 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, sc2), "span4-sampled-parent2") if err := checkChild(sc2, s4); err != nil { t.Error(err) } @@ -342,8 +342,8 @@ func TestSetSpanAttributesOnStart(t *testing.T) { tp := NewTracerProvider(WithSyncer(te)) span := startSpan(tp, "StartSpanAttribute", - otel.WithAttributes(label.String("key1", "value1")), - otel.WithAttributes(label.String("key2", "value2")), + trace.WithAttributes(label.String("key1", "value1")), + trace.WithAttributes(label.String("key2", "value2")), ) got, err := endSpan(te, span) if err != nil { @@ -351,7 +351,7 @@ func TestSetSpanAttributesOnStart(t *testing.T) { } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, @@ -361,7 +361,7 @@ func TestSetSpanAttributesOnStart(t *testing.T) { label.String("key1", "value1"), label.String("key2", "value2"), }, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, HasRemoteParent: true, InstrumentationLibrary: instrumentation.Library{Name: "StartSpanAttribute"}, } @@ -381,7 +381,7 @@ func TestSetSpanAttributes(t *testing.T) { } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, @@ -390,7 +390,7 @@ func TestSetSpanAttributes(t *testing.T) { Attributes: []label.KeyValue{ label.String("key1", "value1"), }, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, HasRemoteParent: true, InstrumentationLibrary: instrumentation.Library{Name: "SpanAttribute"}, } @@ -424,36 +424,36 @@ func TestSamplerAttributesLocalChildSpan(t *testing.T) { checkTime(&got[0].StartTime) checkTime(&got[0].EndTime) - got[1].SpanContext.SpanID = otel.SpanID{} + got[1].SpanContext.SpanID = trace.SpanID{} got[1].SpanContext.TraceID = tid got[1].ParentSpanID = pid - got[0].SpanContext.SpanID = otel.SpanID{} + got[0].SpanContext.SpanID = trace.SpanID{} checkTime(&got[1].StartTime) checkTime(&got[1].EndTime) want := []*export.SpanData{ { - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, ParentSpanID: sid, Name: "span1", Attributes: []label.KeyValue{label.Int("callCount", 2)}, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, HasRemoteParent: false, InstrumentationLibrary: instrumentation.Library{Name: "SpanTwo"}, }, { - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, ParentSpanID: pid, Name: "span0", Attributes: []label.KeyValue{label.Int("callCount", 1)}, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, HasRemoteParent: false, ChildSpanCount: 1, InstrumentationLibrary: instrumentation.Library{Name: "SpanOne"}, @@ -483,7 +483,7 @@ func TestSetSpanAttributesOverLimit(t *testing.T) { } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, @@ -493,7 +493,7 @@ func TestSetSpanAttributesOverLimit(t *testing.T) { label.Bool("key1", false), label.Int64("key4", 4), }, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, HasRemoteParent: true, DroppedAttributeCount: 1, InstrumentationLibrary: instrumentation.Library{Name: "SpanAttributesOverLimit"}, @@ -512,8 +512,8 @@ func TestEvents(t *testing.T) { k2v2 := label.Bool("key2", true) k3v3 := label.Int64("key3", 3) - span.AddEvent("foo", otel.WithAttributes(label.String("key1", "value1"))) - span.AddEvent("bar", otel.WithAttributes( + span.AddEvent("foo", trace.WithAttributes(label.String("key1", "value1"))) + span.AddEvent("bar", trace.WithAttributes( label.Bool("key2", true), label.Int64("key3", 3), )) @@ -529,7 +529,7 @@ func TestEvents(t *testing.T) { } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, @@ -540,7 +540,7 @@ func TestEvents(t *testing.T) { {Name: "foo", Attributes: []label.KeyValue{k1v1}}, {Name: "bar", Attributes: []label.KeyValue{k2v2, k3v3}}, }, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, InstrumentationLibrary: instrumentation.Library{Name: "Events"}, } if diff := cmpDiff(got, want); diff != "" { @@ -558,13 +558,13 @@ func TestEventsOverLimit(t *testing.T) { k2v2 := label.Bool("key2", false) k3v3 := label.String("key3", "value3") - span.AddEvent("fooDrop", otel.WithAttributes(label.String("key1", "value1"))) - span.AddEvent("barDrop", otel.WithAttributes( + span.AddEvent("fooDrop", trace.WithAttributes(label.String("key1", "value1"))) + span.AddEvent("barDrop", trace.WithAttributes( label.Bool("key2", true), label.String("key3", "value3"), )) - span.AddEvent("foo", otel.WithAttributes(label.String("key1", "value1"))) - span.AddEvent("bar", otel.WithAttributes( + span.AddEvent("foo", trace.WithAttributes(label.String("key1", "value1"))) + span.AddEvent("bar", trace.WithAttributes( label.Bool("key2", false), label.String("key3", "value3"), )) @@ -580,7 +580,7 @@ func TestEventsOverLimit(t *testing.T) { } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, @@ -592,7 +592,7 @@ func TestEventsOverLimit(t *testing.T) { }, DroppedMessageEventCount: 2, HasRemoteParent: true, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, InstrumentationLibrary: instrumentation.Library{Name: "EventsOverLimit"}, } if diff := cmpDiff(got, want); diff != "" { @@ -608,14 +608,14 @@ func TestLinks(t *testing.T) { k2v2 := label.String("key2", "value2") k3v3 := label.String("key3", "value3") - sc1 := otel.SpanContext{TraceID: otel.TraceID([16]byte{1, 1}), SpanID: otel.SpanID{3}} - sc2 := otel.SpanContext{TraceID: otel.TraceID([16]byte{1, 1}), SpanID: otel.SpanID{3}} + sc1 := trace.SpanContext{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}} + sc2 := trace.SpanContext{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}} - links := []otel.Link{ + links := []trace.Link{ {SpanContext: sc1, Attributes: []label.KeyValue{k1v1}}, {SpanContext: sc2, Attributes: []label.KeyValue{k2v2, k3v3}}, } - span := startSpan(tp, "Links", otel.WithLinks(links...)) + span := startSpan(tp, "Links", trace.WithLinks(links...)) got, err := endSpan(te, span) if err != nil { @@ -623,7 +623,7 @@ func TestLinks(t *testing.T) { } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, @@ -631,7 +631,7 @@ func TestLinks(t *testing.T) { Name: "span0", HasRemoteParent: true, Links: links, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, InstrumentationLibrary: instrumentation.Library{Name: "Links"}, } if diff := cmpDiff(got, want); diff != "" { @@ -643,17 +643,17 @@ func TestLinksOverLimit(t *testing.T) { te := NewTestExporter() cfg := Config{MaxLinksPerSpan: 2} - sc1 := otel.SpanContext{TraceID: otel.TraceID([16]byte{1, 1}), SpanID: otel.SpanID{3}} - sc2 := otel.SpanContext{TraceID: otel.TraceID([16]byte{1, 1}), SpanID: otel.SpanID{3}} - sc3 := otel.SpanContext{TraceID: otel.TraceID([16]byte{1, 1}), SpanID: otel.SpanID{3}} + sc1 := trace.SpanContext{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}} + sc2 := trace.SpanContext{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}} + sc3 := trace.SpanContext{TraceID: trace.TraceID([16]byte{1, 1}), SpanID: trace.SpanID{3}} tp := NewTracerProvider(WithConfig(cfg), WithSyncer(te)) span := startSpan(tp, "LinksOverLimit", - otel.WithLinks( - otel.Link{SpanContext: sc1, Attributes: []label.KeyValue{label.String("key1", "value1")}}, - otel.Link{SpanContext: sc2, Attributes: []label.KeyValue{label.String("key2", "value2")}}, - otel.Link{SpanContext: sc3, Attributes: []label.KeyValue{label.String("key3", "value3")}}, + trace.WithLinks( + trace.Link{SpanContext: sc1, Attributes: []label.KeyValue{label.String("key1", "value1")}}, + trace.Link{SpanContext: sc2, Attributes: []label.KeyValue{label.String("key2", "value2")}}, + trace.Link{SpanContext: sc3, Attributes: []label.KeyValue{label.String("key3", "value3")}}, ), ) @@ -666,19 +666,19 @@ func TestLinksOverLimit(t *testing.T) { } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, ParentSpanID: sid, Name: "span0", - Links: []otel.Link{ + Links: []trace.Link{ {SpanContext: sc2, Attributes: []label.KeyValue{k2v2}}, {SpanContext: sc3, Attributes: []label.KeyValue{k3v3}}, }, DroppedLinkCount: 1, HasRemoteParent: true, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, InstrumentationLibrary: instrumentation.Library{Name: "LinksOverLimit"}, } if diff := cmpDiff(got, want); diff != "" { @@ -692,7 +692,7 @@ func TestSetSpanName(t *testing.T) { ctx := context.Background() want := "SpanName-1" - ctx = otel.ContextWithRemoteSpanContext(ctx, otel.SpanContext{ + ctx = trace.ContextWithRemoteSpanContext(ctx, trace.SpanContext{ TraceID: tid, SpanID: sid, TraceFlags: 1, @@ -720,13 +720,13 @@ func TestSetSpanStatus(t *testing.T) { } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, ParentSpanID: sid, Name: "span0", - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, StatusCode: codes.Error, StatusMessage: "Error", HasRemoteParent: true, @@ -743,8 +743,8 @@ func cmpDiff(x, y interface{}) string { cmp.AllowUnexported(export.Event{})) } -func remoteSpanContext() otel.SpanContext { - return otel.SpanContext{ +func remoteSpanContext() trace.SpanContext { + return trace.SpanContext{ TraceID: tid, SpanID: sid, TraceFlags: 1, @@ -753,7 +753,7 @@ func remoteSpanContext() otel.SpanContext { // checkChild is test utility function that tests that c has fields set appropriately, // given that it is a child span of p. -func checkChild(p otel.SpanContext, apiSpan otel.Span) error { +func checkChild(p trace.SpanContext, apiSpan trace.Span) error { s := apiSpan.(*span) if s == nil { return fmt.Errorf("got nil child span, want non-nil") @@ -776,7 +776,7 @@ func checkChild(p otel.SpanContext, apiSpan otel.Span) error { // startSpan starts a span with a name "span0". See startNamedSpan for // details. -func startSpan(tp *TracerProvider, trName string, args ...otel.SpanOption) otel.Span { +func startSpan(tp *TracerProvider, trName string, args ...trace.SpanOption) trace.Span { return startNamedSpan(tp, trName, "span0", args...) } @@ -784,10 +784,10 @@ func startSpan(tp *TracerProvider, trName string, args ...otel.SpanOption) otel. // passed name and with remote span context as parent. The remote span // context contains TraceFlags with sampled bit set. This allows the // span to be automatically sampled. -func startNamedSpan(tp *TracerProvider, trName, name string, args ...otel.SpanOption) otel.Span { +func startNamedSpan(tp *TracerProvider, trName, name string, args ...trace.SpanOption) trace.Span { ctx := context.Background() - ctx = otel.ContextWithRemoteSpanContext(ctx, remoteSpanContext()) - args = append(args, otel.WithRecord()) + ctx = trace.ContextWithRemoteSpanContext(ctx, remoteSpanContext()) + args = append(args, trace.WithRecord()) _, span := tp.Tracer(trName).Start( ctx, name, @@ -800,8 +800,8 @@ func startNamedSpan(tp *TracerProvider, trName, name string, args ...otel.SpanOp // passed name and with the passed context. The context is returned // along with the span so this parent can be used to create child // spans. -func startLocalSpan(tp *TracerProvider, ctx context.Context, trName, name string, args ...otel.SpanOption) (context.Context, otel.Span) { - args = append(args, otel.WithRecord()) +func startLocalSpan(tp *TracerProvider, ctx context.Context, trName, name string, args ...trace.SpanOption) (context.Context, trace.Span) { + args = append(args, trace.WithRecord()) ctx, span := tp.Tracer(trName).Start( ctx, name, @@ -819,7 +819,7 @@ func startLocalSpan(tp *TracerProvider, ctx context.Context, trName, name string // // It also does some basic tests on the span. // It also clears spanID in the export.SpanData to make the comparison easier. -func endSpan(te *testExporter, span otel.Span) (*export.SpanData, error) { +func endSpan(te *testExporter, span trace.Span) (*export.SpanData, error) { if !span.IsRecording() { return nil, fmt.Errorf("IsRecording: got false, want true") } @@ -834,7 +834,7 @@ func endSpan(te *testExporter, span otel.Span) (*export.SpanData, error) { if !got.SpanContext.SpanID.IsValid() { return nil, fmt.Errorf("exporting span: expected nonzero SpanID") } - got.SpanContext.SpanID = otel.SpanID{} + got.SpanContext.SpanID = trace.SpanID{} if !checkTime(&got.StartTime) { return nil, fmt.Errorf("exporting span: expected nonzero StartTime") } @@ -871,7 +871,7 @@ func TestStartSpanAfterEnd(t *testing.T) { ctx := context.Background() tr := tp.Tracer("SpanAfterEnd") - ctx, span0 := tr.Start(otel.ContextWithRemoteSpanContext(ctx, remoteSpanContext()), "parent") + ctx, span0 := tr.Start(trace.ContextWithRemoteSpanContext(ctx, remoteSpanContext()), "parent") ctx1, span1 := tr.Start(ctx, "span-1") span1.End() // Start a new span with the context containing span-1 @@ -980,12 +980,12 @@ func TestExecutionTracerTaskEnd(t *testing.T) { s.executionTracerTaskEnd = executionTracerTaskEnd spans = append(spans, s) // never sample - tID, _ := otel.TraceIDFromHex("0102030405060708090a0b0c0d0e0f") - sID, _ := otel.SpanIDFromHex("0001020304050607") + tID, _ := trace.TraceIDFromHex("0102030405060708090a0b0c0d0e0f") + sID, _ := trace.SpanIDFromHex("0001020304050607") ctx := context.Background() - ctx = otel.ContextWithRemoteSpanContext(ctx, - otel.SpanContext{ + ctx = trace.ContextWithRemoteSpanContext(ctx, + trace.SpanContext{ TraceID: tID, SpanID: sID, TraceFlags: 0, @@ -1022,9 +1022,9 @@ func TestCustomStartEndTime(t *testing.T) { _, span := tp.Tracer("Custom Start and End time").Start( context.Background(), "testspan", - otel.WithTimestamp(startTime), + trace.WithTimestamp(startTime), ) - span.End(otel.WithTimestamp(endTime)) + span.End(trace.WithTimestamp(endTime)) if te.Len() != 1 { t.Fatalf("got %d exported spans, want one span", te.Len()) @@ -1062,7 +1062,7 @@ func TestRecordError(t *testing.T) { span := startSpan(tp, "RecordError") errTime := time.Now() - span.RecordError(s.err, otel.WithTimestamp(errTime)) + span.RecordError(s.err, trace.WithTimestamp(errTime)) got, err := endSpan(te, span) if err != nil { @@ -1070,14 +1070,14 @@ func TestRecordError(t *testing.T) { } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, ParentSpanID: sid, Name: "span0", StatusCode: codes.Error, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, HasRemoteParent: true, MessageEvents: []export.Event{ { @@ -1110,13 +1110,13 @@ func TestRecordErrorNil(t *testing.T) { } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, ParentSpanID: sid, Name: "span0", - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, HasRemoteParent: true, StatusCode: codes.Unset, StatusMessage: "", @@ -1138,22 +1138,22 @@ func TestWithSpanKind(t *testing.T) { t.Error(err.Error()) } - if spanData.SpanKind != otel.SpanKindInternal { - t.Errorf("Default value of Spankind should be Internal: got %+v, want %+v\n", spanData.SpanKind, otel.SpanKindInternal) + if spanData.SpanKind != trace.SpanKindInternal { + t.Errorf("Default value of Spankind should be Internal: got %+v, want %+v\n", spanData.SpanKind, trace.SpanKindInternal) } - sks := []otel.SpanKind{ - otel.SpanKindInternal, - otel.SpanKindServer, - otel.SpanKindClient, - otel.SpanKindProducer, - otel.SpanKindConsumer, + sks := []trace.SpanKind{ + trace.SpanKindInternal, + trace.SpanKindServer, + trace.SpanKindClient, + trace.SpanKindProducer, + trace.SpanKindConsumer, } for _, sk := range sks { te.Reset() - _, span := tr.Start(context.Background(), fmt.Sprintf("SpanKind-%v", sk), otel.WithSpanKind(sk)) + _, span := tr.Start(context.Background(), fmt.Sprintf("SpanKind-%v", sk), trace.WithSpanKind(sk)) spanData, err := endSpan(te, span) if err != nil { t.Error(err.Error()) @@ -1178,7 +1178,7 @@ func TestWithResource(t *testing.T) { } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, @@ -1187,7 +1187,7 @@ func TestWithResource(t *testing.T) { Attributes: []label.KeyValue{ label.String("key1", "value1"), }, - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, HasRemoteParent: true, Resource: resource.NewWithAttributes(label.String("rk1", "rv1"), label.Int64("rk2", 5)), InstrumentationLibrary: instrumentation.Library{Name: "WithResource"}, @@ -1202,24 +1202,24 @@ func TestWithInstrumentationVersion(t *testing.T) { tp := NewTracerProvider(WithSyncer(te)) ctx := context.Background() - ctx = otel.ContextWithRemoteSpanContext(ctx, remoteSpanContext()) + ctx = trace.ContextWithRemoteSpanContext(ctx, remoteSpanContext()) _, span := tp.Tracer( "WithInstrumentationVersion", - otel.WithInstrumentationVersion("v0.1.0"), - ).Start(ctx, "span0", otel.WithRecord()) + trace.WithInstrumentationVersion("v0.1.0"), + ).Start(ctx, "span0", trace.WithRecord()) got, err := endSpan(te, span) if err != nil { t.Error(err.Error()) } want := &export.SpanData{ - SpanContext: otel.SpanContext{ + SpanContext: trace.SpanContext{ TraceID: tid, TraceFlags: 0x1, }, ParentSpanID: sid, Name: "span0", - SpanKind: otel.SpanKindInternal, + SpanKind: trace.SpanKindInternal, HasRemoteParent: true, InstrumentationLibrary: instrumentation.Library{ Name: "WithInstrumentationVersion", @@ -1237,7 +1237,7 @@ func TestSpanCapturesPanic(t *testing.T) { _, span := tp.Tracer("CatchPanic").Start( context.Background(), "span", - otel.WithRecord(), + trace.WithRecord(), ) f := func() { diff --git a/sdk/trace/tracer.go b/sdk/trace/tracer.go index 659d20dc9eb..55e90b836ba 100644 --- a/sdk/trace/tracer.go +++ b/sdk/trace/tracer.go @@ -17,8 +17,9 @@ package trace // import "go.opentelemetry.io/otel/sdk/trace" import ( "context" - "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/internal/trace/parent" + "go.opentelemetry.io/otel/trace" + "go.opentelemetry.io/otel/sdk/instrumentation" ) @@ -27,7 +28,7 @@ type tracer struct { instrumentationLibrary instrumentation.Library } -var _ otel.Tracer = &tracer{} +var _ trace.Tracer = &tracer{} // Start starts a Span and returns it along with a context containing it. // @@ -35,12 +36,12 @@ var _ otel.Tracer = &tracer{} // span context found in the passed context. The created Span will be // configured appropriately by any SpanOption passed. Any Timestamp option // passed will be used as the start time of the Span's life-cycle. -func (tr *tracer) Start(ctx context.Context, name string, options ...otel.SpanOption) (context.Context, otel.Span) { - config := otel.NewSpanConfig(options...) +func (tr *tracer) Start(ctx context.Context, name string, options ...trace.SpanOption) (context.Context, trace.Span) { + config := trace.NewSpanConfig(options...) parentSpanContext, remoteParent, links := parent.GetSpanContextAndLinks(ctx, config.NewRoot) - if p := otel.SpanFromContext(ctx); p != nil { + if p := trace.SpanFromContext(ctx); p != nil { if sdkSpan, ok := p.(*span); ok { sdkSpan.addChild() } @@ -66,5 +67,5 @@ func (tr *tracer) Start(ctx context.Context, name string, options ...otel.SpanOp ctx, end := startExecutionTracerTask(ctx, name) span.executionTracerTaskEnd = end - return otel.ContextWithSpan(ctx, span), span + return trace.ContextWithSpan(ctx, span), span } diff --git a/config.go b/trace/config.go similarity index 69% rename from config.go rename to trace/config.go index 6cf5c031f24..9a343633d57 100644 --- a/config.go +++ b/trace/config.go @@ -12,13 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel // import "go.opentelemetry.io/otel" +package trace import ( "time" "go.opentelemetry.io/otel/label" - "go.opentelemetry.io/otel/unit" ) // TracerConfig is a group of options for a Tracer. @@ -179,98 +178,9 @@ func WithSpanKind(kind SpanKind) SpanOption { return spanKindSpanOption(kind) } -// InstrumentConfig contains options for metric instrument descriptors. -type InstrumentConfig struct { - // Description describes the instrument in human-readable terms. - Description string - // Unit describes the measurement unit for a instrument. - Unit unit.Unit - // InstrumentationName is the name of the library providing - // instrumentation. - InstrumentationName string - // InstrumentationVersion is the version of the library providing - // instrumentation. - InstrumentationVersion string -} - -// InstrumentOption is an interface for applying metric instrument options. -type InstrumentOption interface { - // ApplyMeter is used to set a InstrumentOption value of a - // InstrumentConfig. - ApplyInstrument(*InstrumentConfig) -} - -// NewInstrumentConfig creates a new InstrumentConfig -// and applies all the given options. -func NewInstrumentConfig(opts ...InstrumentOption) InstrumentConfig { - var config InstrumentConfig - for _, o := range opts { - o.ApplyInstrument(&config) - } - return config -} - -// WithDescription applies provided description. -func WithDescription(desc string) InstrumentOption { - return descriptionOption(desc) -} - -type descriptionOption string - -func (d descriptionOption) ApplyInstrument(config *InstrumentConfig) { - config.Description = string(d) -} - -// WithUnit applies provided unit. -func WithUnit(unit unit.Unit) InstrumentOption { - return unitOption(unit) -} - -type unitOption unit.Unit - -func (u unitOption) ApplyInstrument(config *InstrumentConfig) { - config.Unit = unit.Unit(u) -} - -// WithInstrumentationName sets the instrumentation name. -func WithInstrumentationName(name string) InstrumentOption { - return instrumentationNameOption(name) -} - -type instrumentationNameOption string - -func (i instrumentationNameOption) ApplyInstrument(config *InstrumentConfig) { - config.InstrumentationName = string(i) -} - -// MeterConfig contains options for Meters. -type MeterConfig struct { - // InstrumentationVersion is the version of the library providing - // instrumentation. - InstrumentationVersion string -} - -// MeterOption is an interface for applying Meter options. -type MeterOption interface { - // ApplyMeter is used to set a MeterOption value of a MeterConfig. - ApplyMeter(*MeterConfig) -} - -// NewMeterConfig creates a new MeterConfig and applies -// all the given options. -func NewMeterConfig(opts ...MeterOption) MeterConfig { - var config MeterConfig - for _, o := range opts { - o.ApplyMeter(&config) - } - return config -} - // InstrumentationOption is an interface for applying instrumentation specific // options. type InstrumentationOption interface { - InstrumentOption - MeterOption TracerOption } @@ -281,14 +191,6 @@ func WithInstrumentationVersion(version string) InstrumentationOption { type instrumentationVersionOption string -func (i instrumentationVersionOption) ApplyMeter(config *MeterConfig) { - config.InstrumentationVersion = string(i) -} - -func (i instrumentationVersionOption) ApplyInstrument(config *InstrumentConfig) { - config.InstrumentationVersion = string(i) -} - func (i instrumentationVersionOption) ApplyTracer(config *TracerConfig) { config.InstrumentationVersion = string(i) } diff --git a/config_test.go b/trace/config_test.go similarity index 99% rename from config_test.go rename to trace/config_test.go index 2542806e1ef..e8fc99c89fe 100644 --- a/config_test.go +++ b/trace/config_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel +package trace import ( "testing" diff --git a/trace.go b/trace/trace.go similarity index 97% rename from trace.go rename to trace/trace.go index e99c4d5a2bf..76016e5bb6e 100644 --- a/trace.go +++ b/trace/trace.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel // import "go.opentelemetry.io/otel" +package trace // import "go.opentelemetry.io/otel/trace" import ( "bytes" @@ -51,6 +51,7 @@ func (e errorConst) Error() string { } // TraceID is a unique identity of a trace. +// nolint:golint type TraceID [16]byte var nilTraceID TraceID @@ -99,6 +100,7 @@ func (s SpanID) String() string { // TraceIDFromHex returns a TraceID from a hex string if it is compliant with // the W3C trace-context specification. See more at // https://www.w3.org/TR/trace-context/#trace-id +// nolint:golint func TraceIDFromHex(h string) (TraceID, error) { t := TraceID{} if len(h) != 32 { @@ -244,8 +246,10 @@ type Span interface { // nil. Tracer() Tracer - // End completes the Span. Updates are not allowed the Span after End is - // called other than setting the status. + // End completes the Span. The Span is considered complete and ready to be + // delivered through the rest of the telemetry pipeline after this method + // is called. Therefore, updates to the Span are not allowed after this + // method has been called. End(options ...SpanOption) // AddEvent adds an event with the provided name and options. diff --git a/trace_noop.go b/trace/trace_noop.go similarity index 97% rename from trace_noop.go rename to trace/trace_noop.go index eadbde29634..6f18a948196 100644 --- a/trace_noop.go +++ b/trace/trace_noop.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel // import "go.opentelemetry.io/otel" +package trace // import "go.opentelemetry.io/otel/trace" import ( "context" diff --git a/trace_noop_test.go b/trace/trace_noop_test.go similarity index 99% rename from trace_noop_test.go rename to trace/trace_noop_test.go index 8cae51d7692..f65d7d4740c 100644 --- a/trace_noop_test.go +++ b/trace/trace_noop_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel +package trace import ( "context" diff --git a/trace_test.go b/trace/trace_test.go similarity index 99% rename from trace_test.go rename to trace/trace_test.go index 09f28286bdd..58ed137eba9 100644 --- a/trace_test.go +++ b/trace/trace_test.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package otel +package trace import ( "context"