chore: migrate to gitea
This commit is contained in:
231
vendor/go.opentelemetry.io/otel/trace/LICENSE
generated
vendored
Normal file
231
vendor/go.opentelemetry.io/otel/trace/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,231 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Copyright 2009 The Go Authors.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google LLC nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
3
vendor/go.opentelemetry.io/otel/trace/README.md
generated
vendored
Normal file
3
vendor/go.opentelemetry.io/otel/trace/README.md
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
# Trace API
|
||||
|
||||
[](https://pkg.go.dev/go.opentelemetry.io/otel/trace)
|
||||
662
vendor/go.opentelemetry.io/otel/trace/auto.go
generated
vendored
Normal file
662
vendor/go.opentelemetry.io/otel/trace/auto.go
generated
vendored
Normal file
@@ -0,0 +1,662 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
|
||||
"go.opentelemetry.io/otel/trace/embedded"
|
||||
"go.opentelemetry.io/otel/trace/internal/telemetry"
|
||||
)
|
||||
|
||||
// newAutoTracerProvider returns an auto-instrumentable [trace.TracerProvider].
|
||||
// If an [go.opentelemetry.io/auto.Instrumentation] is configured to instrument
|
||||
// the process using the returned TracerProvider, all of the telemetry it
|
||||
// produces will be processed and handled by that Instrumentation. By default,
|
||||
// if no Instrumentation instruments the TracerProvider it will not generate
|
||||
// any trace telemetry.
|
||||
func newAutoTracerProvider() TracerProvider { return tracerProviderInstance }
|
||||
|
||||
var tracerProviderInstance = new(autoTracerProvider)
|
||||
|
||||
type autoTracerProvider struct{ embedded.TracerProvider }
|
||||
|
||||
var _ TracerProvider = autoTracerProvider{}
|
||||
|
||||
func (autoTracerProvider) Tracer(name string, opts ...TracerOption) Tracer {
|
||||
cfg := NewTracerConfig(opts...)
|
||||
return autoTracer{
|
||||
name: name,
|
||||
version: cfg.InstrumentationVersion(),
|
||||
schemaURL: cfg.SchemaURL(),
|
||||
}
|
||||
}
|
||||
|
||||
type autoTracer struct {
|
||||
embedded.Tracer
|
||||
|
||||
name, schemaURL, version string
|
||||
}
|
||||
|
||||
var _ Tracer = autoTracer{}
|
||||
|
||||
func (t autoTracer) Start(ctx context.Context, name string, opts ...SpanStartOption) (context.Context, Span) {
|
||||
var psc, sc SpanContext
|
||||
sampled := true
|
||||
span := new(autoSpan)
|
||||
|
||||
// Ask eBPF for sampling decision and span context info.
|
||||
t.start(ctx, span, &psc, &sampled, &sc)
|
||||
|
||||
span.sampled.Store(sampled)
|
||||
span.spanContext = sc
|
||||
|
||||
ctx = ContextWithSpan(ctx, span)
|
||||
|
||||
if sampled {
|
||||
// Only build traces if sampled.
|
||||
cfg := NewSpanStartConfig(opts...)
|
||||
span.traces, span.span = t.traces(name, cfg, span.spanContext, psc)
|
||||
}
|
||||
|
||||
return ctx, span
|
||||
}
|
||||
|
||||
// Expected to be implemented in eBPF.
|
||||
//
|
||||
//go:noinline
|
||||
func (*autoTracer) start(
|
||||
ctx context.Context,
|
||||
spanPtr *autoSpan,
|
||||
psc *SpanContext,
|
||||
sampled *bool,
|
||||
sc *SpanContext,
|
||||
) {
|
||||
start(ctx, spanPtr, psc, sampled, sc)
|
||||
}
|
||||
|
||||
// start is used for testing.
|
||||
var start = func(context.Context, *autoSpan, *SpanContext, *bool, *SpanContext) {}
|
||||
|
||||
func (t autoTracer) traces(name string, cfg SpanConfig, sc, psc SpanContext) (*telemetry.Traces, *telemetry.Span) {
|
||||
span := &telemetry.Span{
|
||||
TraceID: telemetry.TraceID(sc.TraceID()),
|
||||
SpanID: telemetry.SpanID(sc.SpanID()),
|
||||
Flags: uint32(sc.TraceFlags()),
|
||||
TraceState: sc.TraceState().String(),
|
||||
ParentSpanID: telemetry.SpanID(psc.SpanID()),
|
||||
Name: name,
|
||||
Kind: spanKind(cfg.SpanKind()),
|
||||
}
|
||||
|
||||
span.Attrs, span.DroppedAttrs = convCappedAttrs(maxSpan.Attrs, cfg.Attributes())
|
||||
|
||||
links := cfg.Links()
|
||||
if limit := maxSpan.Links; limit == 0 {
|
||||
n := int64(len(links))
|
||||
if n > 0 {
|
||||
span.DroppedLinks = uint32(min(n, math.MaxUint32)) // nolint: gosec // Bounds checked.
|
||||
}
|
||||
} else {
|
||||
if limit > 0 {
|
||||
n := int64(max(len(links)-limit, 0))
|
||||
span.DroppedLinks = uint32(min(n, math.MaxUint32)) // nolint: gosec // Bounds checked.
|
||||
links = links[n:]
|
||||
}
|
||||
span.Links = convLinks(links)
|
||||
}
|
||||
|
||||
if t := cfg.Timestamp(); !t.IsZero() {
|
||||
span.StartTime = cfg.Timestamp()
|
||||
} else {
|
||||
span.StartTime = time.Now()
|
||||
}
|
||||
|
||||
return &telemetry.Traces{
|
||||
ResourceSpans: []*telemetry.ResourceSpans{
|
||||
{
|
||||
ScopeSpans: []*telemetry.ScopeSpans{
|
||||
{
|
||||
Scope: &telemetry.Scope{
|
||||
Name: t.name,
|
||||
Version: t.version,
|
||||
},
|
||||
Spans: []*telemetry.Span{span},
|
||||
SchemaURL: t.schemaURL,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}, span
|
||||
}
|
||||
|
||||
func spanKind(kind SpanKind) telemetry.SpanKind {
|
||||
switch kind {
|
||||
case SpanKindInternal:
|
||||
return telemetry.SpanKindInternal
|
||||
case SpanKindServer:
|
||||
return telemetry.SpanKindServer
|
||||
case SpanKindClient:
|
||||
return telemetry.SpanKindClient
|
||||
case SpanKindProducer:
|
||||
return telemetry.SpanKindProducer
|
||||
case SpanKindConsumer:
|
||||
return telemetry.SpanKindConsumer
|
||||
}
|
||||
return telemetry.SpanKind(0) // undefined.
|
||||
}
|
||||
|
||||
type autoSpan struct {
|
||||
embedded.Span
|
||||
|
||||
spanContext SpanContext
|
||||
sampled atomic.Bool
|
||||
|
||||
mu sync.Mutex
|
||||
traces *telemetry.Traces
|
||||
span *telemetry.Span
|
||||
}
|
||||
|
||||
func (s *autoSpan) SpanContext() SpanContext {
|
||||
if s == nil {
|
||||
return SpanContext{}
|
||||
}
|
||||
// s.spanContext is immutable, do not acquire lock s.mu.
|
||||
return s.spanContext
|
||||
}
|
||||
|
||||
func (s *autoSpan) IsRecording() bool {
|
||||
if s == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return s.sampled.Load()
|
||||
}
|
||||
|
||||
func (s *autoSpan) SetStatus(c codes.Code, msg string) {
|
||||
if s == nil || !s.sampled.Load() {
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.span.Status == nil {
|
||||
s.span.Status = new(telemetry.Status)
|
||||
}
|
||||
|
||||
s.span.Status.Message = msg
|
||||
|
||||
switch c {
|
||||
case codes.Unset:
|
||||
s.span.Status.Code = telemetry.StatusCodeUnset
|
||||
case codes.Error:
|
||||
s.span.Status.Code = telemetry.StatusCodeError
|
||||
case codes.Ok:
|
||||
s.span.Status.Code = telemetry.StatusCodeOK
|
||||
}
|
||||
}
|
||||
|
||||
func (s *autoSpan) SetAttributes(attrs ...attribute.KeyValue) {
|
||||
if s == nil || !s.sampled.Load() {
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
limit := maxSpan.Attrs
|
||||
if limit == 0 {
|
||||
// No attributes allowed.
|
||||
n := int64(len(attrs))
|
||||
if n > 0 {
|
||||
s.span.DroppedAttrs += uint32(min(n, math.MaxUint32)) // nolint: gosec // Bounds checked.
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
m := make(map[string]int)
|
||||
for i, a := range s.span.Attrs {
|
||||
m[a.Key] = i
|
||||
}
|
||||
|
||||
for _, a := range attrs {
|
||||
val := convAttrValue(a.Value)
|
||||
if val.Empty() {
|
||||
s.span.DroppedAttrs++
|
||||
continue
|
||||
}
|
||||
|
||||
if idx, ok := m[string(a.Key)]; ok {
|
||||
s.span.Attrs[idx] = telemetry.Attr{
|
||||
Key: string(a.Key),
|
||||
Value: val,
|
||||
}
|
||||
} else if limit < 0 || len(s.span.Attrs) < limit {
|
||||
s.span.Attrs = append(s.span.Attrs, telemetry.Attr{
|
||||
Key: string(a.Key),
|
||||
Value: val,
|
||||
})
|
||||
m[string(a.Key)] = len(s.span.Attrs) - 1
|
||||
} else {
|
||||
s.span.DroppedAttrs++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// convCappedAttrs converts up to limit attrs into a []telemetry.Attr. The
|
||||
// number of dropped attributes is also returned.
|
||||
func convCappedAttrs(limit int, attrs []attribute.KeyValue) ([]telemetry.Attr, uint32) {
|
||||
n := len(attrs)
|
||||
if limit == 0 {
|
||||
var out uint32
|
||||
if n > 0 {
|
||||
out = uint32(min(int64(n), math.MaxUint32)) // nolint: gosec // Bounds checked.
|
||||
}
|
||||
return nil, out
|
||||
}
|
||||
|
||||
if limit < 0 {
|
||||
// Unlimited.
|
||||
return convAttrs(attrs), 0
|
||||
}
|
||||
|
||||
if n < 0 {
|
||||
n = 0
|
||||
}
|
||||
|
||||
limit = min(n, limit)
|
||||
return convAttrs(attrs[:limit]), uint32(n - limit) // nolint: gosec // Bounds checked.
|
||||
}
|
||||
|
||||
func convAttrs(attrs []attribute.KeyValue) []telemetry.Attr {
|
||||
if len(attrs) == 0 {
|
||||
// Avoid allocations if not necessary.
|
||||
return nil
|
||||
}
|
||||
|
||||
out := make([]telemetry.Attr, 0, len(attrs))
|
||||
for _, attr := range attrs {
|
||||
key := string(attr.Key)
|
||||
val := convAttrValue(attr.Value)
|
||||
if val.Empty() {
|
||||
continue
|
||||
}
|
||||
out = append(out, telemetry.Attr{Key: key, Value: val})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func convAttrValue(value attribute.Value) telemetry.Value {
|
||||
switch value.Type() {
|
||||
case attribute.BOOL:
|
||||
return telemetry.BoolValue(value.AsBool())
|
||||
case attribute.INT64:
|
||||
return telemetry.Int64Value(value.AsInt64())
|
||||
case attribute.FLOAT64:
|
||||
return telemetry.Float64Value(value.AsFloat64())
|
||||
case attribute.STRING:
|
||||
v := truncate(maxSpan.AttrValueLen, value.AsString())
|
||||
return telemetry.StringValue(v)
|
||||
case attribute.BOOLSLICE:
|
||||
slice := value.AsBoolSlice()
|
||||
out := make([]telemetry.Value, 0, len(slice))
|
||||
for _, v := range slice {
|
||||
out = append(out, telemetry.BoolValue(v))
|
||||
}
|
||||
return telemetry.SliceValue(out...)
|
||||
case attribute.INT64SLICE:
|
||||
slice := value.AsInt64Slice()
|
||||
out := make([]telemetry.Value, 0, len(slice))
|
||||
for _, v := range slice {
|
||||
out = append(out, telemetry.Int64Value(v))
|
||||
}
|
||||
return telemetry.SliceValue(out...)
|
||||
case attribute.FLOAT64SLICE:
|
||||
slice := value.AsFloat64Slice()
|
||||
out := make([]telemetry.Value, 0, len(slice))
|
||||
for _, v := range slice {
|
||||
out = append(out, telemetry.Float64Value(v))
|
||||
}
|
||||
return telemetry.SliceValue(out...)
|
||||
case attribute.STRINGSLICE:
|
||||
slice := value.AsStringSlice()
|
||||
out := make([]telemetry.Value, 0, len(slice))
|
||||
for _, v := range slice {
|
||||
v = truncate(maxSpan.AttrValueLen, v)
|
||||
out = append(out, telemetry.StringValue(v))
|
||||
}
|
||||
return telemetry.SliceValue(out...)
|
||||
}
|
||||
return telemetry.Value{}
|
||||
}
|
||||
|
||||
// truncate returns a truncated version of s such that it contains less than
|
||||
// the limit number of characters. Truncation is applied by returning the limit
|
||||
// number of valid characters contained in s.
|
||||
//
|
||||
// If limit is negative, it returns the original string.
|
||||
//
|
||||
// UTF-8 is supported. When truncating, all invalid characters are dropped
|
||||
// before applying truncation.
|
||||
//
|
||||
// If s already contains less than the limit number of bytes, it is returned
|
||||
// unchanged. No invalid characters are removed.
|
||||
func truncate(limit int, s string) string {
|
||||
// This prioritize performance in the following order based on the most
|
||||
// common expected use-cases.
|
||||
//
|
||||
// - Short values less than the default limit (128).
|
||||
// - Strings with valid encodings that exceed the limit.
|
||||
// - No limit.
|
||||
// - Strings with invalid encodings that exceed the limit.
|
||||
if limit < 0 || len(s) <= limit {
|
||||
return s
|
||||
}
|
||||
|
||||
// Optimistically, assume all valid UTF-8.
|
||||
var b strings.Builder
|
||||
count := 0
|
||||
for i, c := range s {
|
||||
if c != utf8.RuneError {
|
||||
count++
|
||||
if count > limit {
|
||||
return s[:i]
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
_, size := utf8.DecodeRuneInString(s[i:])
|
||||
if size == 1 {
|
||||
// Invalid encoding.
|
||||
b.Grow(len(s) - 1)
|
||||
_, _ = b.WriteString(s[:i])
|
||||
s = s[i:]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Fast-path, no invalid input.
|
||||
if b.Cap() == 0 {
|
||||
return s
|
||||
}
|
||||
|
||||
// Truncate while validating UTF-8.
|
||||
for i := 0; i < len(s) && count < limit; {
|
||||
c := s[i]
|
||||
if c < utf8.RuneSelf {
|
||||
// Optimization for single byte runes (common case).
|
||||
_ = b.WriteByte(c)
|
||||
i++
|
||||
count++
|
||||
continue
|
||||
}
|
||||
|
||||
_, size := utf8.DecodeRuneInString(s[i:])
|
||||
if size == 1 {
|
||||
// We checked for all 1-byte runes above, this is a RuneError.
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
_, _ = b.WriteString(s[i : i+size])
|
||||
i += size
|
||||
count++
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (s *autoSpan) End(opts ...SpanEndOption) {
|
||||
if s == nil || !s.sampled.Swap(false) {
|
||||
return
|
||||
}
|
||||
|
||||
// s.end exists so the lock (s.mu) is not held while s.ended is called.
|
||||
s.ended(s.end(opts))
|
||||
}
|
||||
|
||||
func (s *autoSpan) end(opts []SpanEndOption) []byte {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
cfg := NewSpanEndConfig(opts...)
|
||||
if t := cfg.Timestamp(); !t.IsZero() {
|
||||
s.span.EndTime = cfg.Timestamp()
|
||||
} else {
|
||||
s.span.EndTime = time.Now()
|
||||
}
|
||||
|
||||
b, _ := json.Marshal(s.traces) // TODO: do not ignore this error.
|
||||
return b
|
||||
}
|
||||
|
||||
// Expected to be implemented in eBPF.
|
||||
//
|
||||
//go:noinline
|
||||
func (*autoSpan) ended(buf []byte) { ended(buf) }
|
||||
|
||||
// ended is used for testing.
|
||||
var ended = func([]byte) {}
|
||||
|
||||
func (s *autoSpan) RecordError(err error, opts ...EventOption) {
|
||||
if s == nil || err == nil || !s.sampled.Load() {
|
||||
return
|
||||
}
|
||||
|
||||
cfg := NewEventConfig(opts...)
|
||||
|
||||
attrs := cfg.Attributes()
|
||||
attrs = append(attrs,
|
||||
semconv.ExceptionType(typeStr(err)),
|
||||
semconv.ExceptionMessage(err.Error()),
|
||||
)
|
||||
if cfg.StackTrace() {
|
||||
buf := make([]byte, 2048)
|
||||
n := runtime.Stack(buf, false)
|
||||
attrs = append(attrs, semconv.ExceptionStacktrace(string(buf[0:n])))
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.addEvent(semconv.ExceptionEventName, cfg.Timestamp(), attrs)
|
||||
}
|
||||
|
||||
func typeStr(i any) string {
|
||||
t := reflect.TypeOf(i)
|
||||
if t.PkgPath() == "" && t.Name() == "" {
|
||||
// Likely a builtin type.
|
||||
return t.String()
|
||||
}
|
||||
return fmt.Sprintf("%s.%s", t.PkgPath(), t.Name())
|
||||
}
|
||||
|
||||
func (s *autoSpan) AddEvent(name string, opts ...EventOption) {
|
||||
if s == nil || !s.sampled.Load() {
|
||||
return
|
||||
}
|
||||
|
||||
cfg := NewEventConfig(opts...)
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.addEvent(name, cfg.Timestamp(), cfg.Attributes())
|
||||
}
|
||||
|
||||
// addEvent adds an event with name and attrs at tStamp to the span. The span
|
||||
// lock (s.mu) needs to be held by the caller.
|
||||
func (s *autoSpan) addEvent(name string, tStamp time.Time, attrs []attribute.KeyValue) {
|
||||
limit := maxSpan.Events
|
||||
|
||||
if limit == 0 {
|
||||
s.span.DroppedEvents++
|
||||
return
|
||||
}
|
||||
|
||||
if limit > 0 && len(s.span.Events) == limit {
|
||||
// Drop head while avoiding allocation of more capacity.
|
||||
copy(s.span.Events[:limit-1], s.span.Events[1:])
|
||||
s.span.Events = s.span.Events[:limit-1]
|
||||
s.span.DroppedEvents++
|
||||
}
|
||||
|
||||
e := &telemetry.SpanEvent{Time: tStamp, Name: name}
|
||||
e.Attrs, e.DroppedAttrs = convCappedAttrs(maxSpan.EventAttrs, attrs)
|
||||
|
||||
s.span.Events = append(s.span.Events, e)
|
||||
}
|
||||
|
||||
func (s *autoSpan) AddLink(link Link) {
|
||||
if s == nil || !s.sampled.Load() {
|
||||
return
|
||||
}
|
||||
|
||||
l := maxSpan.Links
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if l == 0 {
|
||||
s.span.DroppedLinks++
|
||||
return
|
||||
}
|
||||
|
||||
if l > 0 && len(s.span.Links) == l {
|
||||
// Drop head while avoiding allocation of more capacity.
|
||||
copy(s.span.Links[:l-1], s.span.Links[1:])
|
||||
s.span.Links = s.span.Links[:l-1]
|
||||
s.span.DroppedLinks++
|
||||
}
|
||||
|
||||
s.span.Links = append(s.span.Links, convLink(link))
|
||||
}
|
||||
|
||||
func convLinks(links []Link) []*telemetry.SpanLink {
|
||||
out := make([]*telemetry.SpanLink, 0, len(links))
|
||||
for _, link := range links {
|
||||
out = append(out, convLink(link))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func convLink(link Link) *telemetry.SpanLink {
|
||||
l := &telemetry.SpanLink{
|
||||
TraceID: telemetry.TraceID(link.SpanContext.TraceID()),
|
||||
SpanID: telemetry.SpanID(link.SpanContext.SpanID()),
|
||||
TraceState: link.SpanContext.TraceState().String(),
|
||||
Flags: uint32(link.SpanContext.TraceFlags()),
|
||||
}
|
||||
l.Attrs, l.DroppedAttrs = convCappedAttrs(maxSpan.LinkAttrs, link.Attributes)
|
||||
|
||||
return l
|
||||
}
|
||||
|
||||
func (s *autoSpan) SetName(name string) {
|
||||
if s == nil || !s.sampled.Load() {
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.span.Name = name
|
||||
}
|
||||
|
||||
func (*autoSpan) TracerProvider() TracerProvider { return newAutoTracerProvider() }
|
||||
|
||||
// maxSpan are the span limits resolved during startup.
|
||||
var maxSpan = newSpanLimits()
|
||||
|
||||
type spanLimits struct {
|
||||
// Attrs is the number of allowed attributes for a span.
|
||||
//
|
||||
// This is resolved from the environment variable value for the
|
||||
// OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT key if it exists. Otherwise, the
|
||||
// environment variable value for OTEL_ATTRIBUTE_COUNT_LIMIT, or 128 if
|
||||
// that is not set, is used.
|
||||
Attrs int
|
||||
// AttrValueLen is the maximum attribute value length allowed for a span.
|
||||
//
|
||||
// This is resolved from the environment variable value for the
|
||||
// OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT key if it exists. Otherwise, the
|
||||
// environment variable value for OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT, or -1
|
||||
// if that is not set, is used.
|
||||
AttrValueLen int
|
||||
// Events is the number of allowed events for a span.
|
||||
//
|
||||
// This is resolved from the environment variable value for the
|
||||
// OTEL_SPAN_EVENT_COUNT_LIMIT key, or 128 is used if that is not set.
|
||||
Events int
|
||||
// EventAttrs is the number of allowed attributes for a span event.
|
||||
//
|
||||
// The is resolved from the environment variable value for the
|
||||
// OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT key, or 128 is used if that is not set.
|
||||
EventAttrs int
|
||||
// Links is the number of allowed Links for a span.
|
||||
//
|
||||
// This is resolved from the environment variable value for the
|
||||
// OTEL_SPAN_LINK_COUNT_LIMIT, or 128 is used if that is not set.
|
||||
Links int
|
||||
// LinkAttrs is the number of allowed attributes for a span link.
|
||||
//
|
||||
// This is resolved from the environment variable value for the
|
||||
// OTEL_LINK_ATTRIBUTE_COUNT_LIMIT, or 128 is used if that is not set.
|
||||
LinkAttrs int
|
||||
}
|
||||
|
||||
func newSpanLimits() spanLimits {
|
||||
return spanLimits{
|
||||
Attrs: firstEnv(
|
||||
128,
|
||||
"OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT",
|
||||
"OTEL_ATTRIBUTE_COUNT_LIMIT",
|
||||
),
|
||||
AttrValueLen: firstEnv(
|
||||
-1, // Unlimited.
|
||||
"OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT",
|
||||
"OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT",
|
||||
),
|
||||
Events: firstEnv(128, "OTEL_SPAN_EVENT_COUNT_LIMIT"),
|
||||
EventAttrs: firstEnv(128, "OTEL_EVENT_ATTRIBUTE_COUNT_LIMIT"),
|
||||
Links: firstEnv(128, "OTEL_SPAN_LINK_COUNT_LIMIT"),
|
||||
LinkAttrs: firstEnv(128, "OTEL_LINK_ATTRIBUTE_COUNT_LIMIT"),
|
||||
}
|
||||
}
|
||||
|
||||
// firstEnv returns the parsed integer value of the first matching environment
|
||||
// variable from keys. The defaultVal is returned if the value is not an
|
||||
// integer or no match is found.
|
||||
func firstEnv(defaultVal int, keys ...string) int {
|
||||
for _, key := range keys {
|
||||
strV := os.Getenv(key)
|
||||
if strV == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
v, err := strconv.Atoi(strV)
|
||||
if err == nil {
|
||||
return v
|
||||
}
|
||||
// Ignore invalid environment variable.
|
||||
}
|
||||
|
||||
return defaultVal
|
||||
}
|
||||
362
vendor/go.opentelemetry.io/otel/trace/config.go
generated
vendored
Normal file
362
vendor/go.opentelemetry.io/otel/trace/config.go
generated
vendored
Normal file
@@ -0,0 +1,362 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
)
|
||||
|
||||
// TracerConfig is a group of options for a Tracer.
|
||||
type TracerConfig struct {
|
||||
instrumentationVersion string
|
||||
// Schema URL of the telemetry emitted by the Tracer.
|
||||
schemaURL string
|
||||
attrs attribute.Set
|
||||
}
|
||||
|
||||
// InstrumentationVersion returns the version of the library providing instrumentation.
|
||||
func (t *TracerConfig) InstrumentationVersion() string {
|
||||
return t.instrumentationVersion
|
||||
}
|
||||
|
||||
// InstrumentationAttributes returns the attributes associated with the library
|
||||
// providing instrumentation.
|
||||
func (t *TracerConfig) InstrumentationAttributes() attribute.Set {
|
||||
return t.attrs
|
||||
}
|
||||
|
||||
// SchemaURL returns the Schema URL of the telemetry emitted by the Tracer.
|
||||
func (t *TracerConfig) SchemaURL() string {
|
||||
return t.schemaURL
|
||||
}
|
||||
|
||||
// NewTracerConfig applies all the options to a returned TracerConfig.
|
||||
func NewTracerConfig(options ...TracerOption) TracerConfig {
|
||||
var config TracerConfig
|
||||
for _, option := range options {
|
||||
config = option.apply(config)
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
// TracerOption applies an option to a TracerConfig.
|
||||
type TracerOption interface {
|
||||
apply(TracerConfig) TracerConfig
|
||||
}
|
||||
|
||||
type tracerOptionFunc func(TracerConfig) TracerConfig
|
||||
|
||||
func (fn tracerOptionFunc) apply(cfg TracerConfig) TracerConfig {
|
||||
return fn(cfg)
|
||||
}
|
||||
|
||||
// SpanConfig is a group of options for a Span.
|
||||
type SpanConfig struct {
|
||||
attributes []attribute.KeyValue
|
||||
timestamp time.Time
|
||||
links []Link
|
||||
newRoot bool
|
||||
spanKind SpanKind
|
||||
stackTrace bool
|
||||
}
|
||||
|
||||
// Attributes describe the associated qualities of a Span.
|
||||
func (cfg *SpanConfig) Attributes() []attribute.KeyValue {
|
||||
return cfg.attributes
|
||||
}
|
||||
|
||||
// Timestamp is a time in a Span life-cycle.
|
||||
func (cfg *SpanConfig) Timestamp() time.Time {
|
||||
return cfg.timestamp
|
||||
}
|
||||
|
||||
// StackTrace reports whether stack trace capturing is enabled.
|
||||
func (cfg *SpanConfig) StackTrace() bool {
|
||||
return cfg.stackTrace
|
||||
}
|
||||
|
||||
// Links are the associations a Span has with other Spans.
|
||||
func (cfg *SpanConfig) Links() []Link {
|
||||
return cfg.links
|
||||
}
|
||||
|
||||
// NewRoot identifies a Span as the root Span for a new trace. This is
|
||||
// commonly used when an existing trace crosses trust boundaries and the
|
||||
// remote parent span context should be ignored for security.
|
||||
func (cfg *SpanConfig) NewRoot() bool {
|
||||
return cfg.newRoot
|
||||
}
|
||||
|
||||
// SpanKind is the role a Span has in a trace.
|
||||
func (cfg *SpanConfig) SpanKind() SpanKind {
|
||||
return cfg.spanKind
|
||||
}
|
||||
|
||||
// NewSpanStartConfig applies all the options to a returned SpanConfig.
|
||||
// No validation is performed on the returned SpanConfig (e.g. no uniqueness
|
||||
// checking or bounding of data), it is left to the SDK to perform this
|
||||
// action.
|
||||
func NewSpanStartConfig(options ...SpanStartOption) SpanConfig {
|
||||
var c SpanConfig
|
||||
for _, option := range options {
|
||||
c = option.applySpanStart(c)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// NewSpanEndConfig applies all the options to a returned SpanConfig.
|
||||
// No validation is performed on the returned SpanConfig (e.g. no uniqueness
|
||||
// checking or bounding of data), it is left to the SDK to perform this
|
||||
// action.
|
||||
func NewSpanEndConfig(options ...SpanEndOption) SpanConfig {
|
||||
var c SpanConfig
|
||||
for _, option := range options {
|
||||
c = option.applySpanEnd(c)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// SpanStartOption applies an option to a SpanConfig. These options are applicable
|
||||
// only when the span is created.
|
||||
type SpanStartOption interface {
|
||||
applySpanStart(SpanConfig) SpanConfig
|
||||
}
|
||||
|
||||
type spanOptionFunc func(SpanConfig) SpanConfig
|
||||
|
||||
func (fn spanOptionFunc) applySpanStart(cfg SpanConfig) SpanConfig {
|
||||
return fn(cfg)
|
||||
}
|
||||
|
||||
// SpanEndOption applies an option to a SpanConfig. These options are
|
||||
// applicable only when the span is ended.
|
||||
type SpanEndOption interface {
|
||||
applySpanEnd(SpanConfig) SpanConfig
|
||||
}
|
||||
|
||||
// EventConfig is a group of options for an Event.
|
||||
type EventConfig struct {
|
||||
attributes []attribute.KeyValue
|
||||
timestamp time.Time
|
||||
stackTrace bool
|
||||
}
|
||||
|
||||
// Attributes describe the associated qualities of an Event.
|
||||
func (cfg *EventConfig) Attributes() []attribute.KeyValue {
|
||||
return cfg.attributes
|
||||
}
|
||||
|
||||
// Timestamp is a time in an Event life-cycle.
|
||||
func (cfg *EventConfig) Timestamp() time.Time {
|
||||
return cfg.timestamp
|
||||
}
|
||||
|
||||
// StackTrace reports whether stack trace capturing is enabled.
|
||||
func (cfg *EventConfig) StackTrace() bool {
|
||||
return cfg.stackTrace
|
||||
}
|
||||
|
||||
// NewEventConfig applies all the EventOptions to a returned EventConfig. If no
|
||||
// timestamp option is passed, the returned EventConfig will have a Timestamp
|
||||
// set to the call time, otherwise no validation is performed on the returned
|
||||
// EventConfig.
|
||||
func NewEventConfig(options ...EventOption) EventConfig {
|
||||
var c EventConfig
|
||||
for _, option := range options {
|
||||
c = option.applyEvent(c)
|
||||
}
|
||||
if c.timestamp.IsZero() {
|
||||
c.timestamp = time.Now()
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// EventOption applies span event options to an EventConfig.
|
||||
type EventOption interface {
|
||||
applyEvent(EventConfig) EventConfig
|
||||
}
|
||||
|
||||
// SpanOption are options that can be used at both the beginning and end of a span.
|
||||
type SpanOption interface {
|
||||
SpanStartOption
|
||||
SpanEndOption
|
||||
}
|
||||
|
||||
// SpanStartEventOption are options that can be used at the start of a span, or with an event.
|
||||
type SpanStartEventOption interface {
|
||||
SpanStartOption
|
||||
EventOption
|
||||
}
|
||||
|
||||
// SpanEndEventOption are options that can be used at the end of a span, or with an event.
|
||||
type SpanEndEventOption interface {
|
||||
SpanEndOption
|
||||
EventOption
|
||||
}
|
||||
|
||||
type attributeOption []attribute.KeyValue
|
||||
|
||||
func (o attributeOption) applySpan(c SpanConfig) SpanConfig {
|
||||
c.attributes = append(c.attributes, []attribute.KeyValue(o)...)
|
||||
return c
|
||||
}
|
||||
func (o attributeOption) applySpanStart(c SpanConfig) SpanConfig { return o.applySpan(c) }
|
||||
func (o attributeOption) applyEvent(c EventConfig) EventConfig {
|
||||
c.attributes = append(c.attributes, []attribute.KeyValue(o)...)
|
||||
return c
|
||||
}
|
||||
|
||||
var _ SpanStartEventOption = attributeOption{}
|
||||
|
||||
// WithAttributes adds the attributes related to a span life-cycle event.
|
||||
// These attributes are used to describe the work a Span represents when this
|
||||
// option is provided to a Span's start event. Otherwise, these
|
||||
// attributes provide additional information about the event being recorded
|
||||
// (e.g. error, state change, processing progress, system event).
|
||||
//
|
||||
// If multiple of these options are passed the attributes of each successive
|
||||
// option will extend the attributes instead of overwriting. There is no
|
||||
// guarantee of uniqueness in the resulting attributes.
|
||||
func WithAttributes(attributes ...attribute.KeyValue) SpanStartEventOption {
|
||||
return attributeOption(attributes)
|
||||
}
|
||||
|
||||
// SpanEventOption are options that can be used with an event or a span.
|
||||
type SpanEventOption interface {
|
||||
SpanOption
|
||||
EventOption
|
||||
}
|
||||
|
||||
type timestampOption time.Time
|
||||
|
||||
func (o timestampOption) applySpan(c SpanConfig) SpanConfig {
|
||||
c.timestamp = time.Time(o)
|
||||
return c
|
||||
}
|
||||
func (o timestampOption) applySpanStart(c SpanConfig) SpanConfig { return o.applySpan(c) }
|
||||
func (o timestampOption) applySpanEnd(c SpanConfig) SpanConfig { return o.applySpan(c) }
|
||||
func (o timestampOption) applyEvent(c EventConfig) EventConfig {
|
||||
c.timestamp = time.Time(o)
|
||||
return c
|
||||
}
|
||||
|
||||
var _ SpanEventOption = timestampOption{}
|
||||
|
||||
// WithTimestamp sets the time of a Span or Event life-cycle moment (e.g.
|
||||
// started, stopped, errored).
|
||||
func WithTimestamp(t time.Time) SpanEventOption {
|
||||
return timestampOption(t)
|
||||
}
|
||||
|
||||
type stackTraceOption bool
|
||||
|
||||
func (o stackTraceOption) applyEvent(c EventConfig) EventConfig {
|
||||
c.stackTrace = bool(o)
|
||||
return c
|
||||
}
|
||||
|
||||
func (o stackTraceOption) applySpan(c SpanConfig) SpanConfig {
|
||||
c.stackTrace = bool(o)
|
||||
return c
|
||||
}
|
||||
func (o stackTraceOption) applySpanEnd(c SpanConfig) SpanConfig { return o.applySpan(c) }
|
||||
|
||||
// WithStackTrace sets the flag to capture the error with stack trace (e.g. true, false).
|
||||
func WithStackTrace(b bool) SpanEndEventOption {
|
||||
return stackTraceOption(b)
|
||||
}
|
||||
|
||||
// WithLinks adds links to a Span. The links are added to the existing Span
|
||||
// links, i.e. this does not overwrite. Links with invalid span context are ignored.
|
||||
func WithLinks(links ...Link) SpanStartOption {
|
||||
return spanOptionFunc(func(cfg SpanConfig) SpanConfig {
|
||||
cfg.links = append(cfg.links, links...)
|
||||
return cfg
|
||||
})
|
||||
}
|
||||
|
||||
// WithNewRoot specifies that the Span should be treated as a root Span. Any
|
||||
// existing parent span context will be ignored when defining the Span's trace
|
||||
// identifiers.
|
||||
func WithNewRoot() SpanStartOption {
|
||||
return spanOptionFunc(func(cfg SpanConfig) SpanConfig {
|
||||
cfg.newRoot = true
|
||||
return cfg
|
||||
})
|
||||
}
|
||||
|
||||
// WithSpanKind sets the SpanKind of a Span.
|
||||
func WithSpanKind(kind SpanKind) SpanStartOption {
|
||||
return spanOptionFunc(func(cfg SpanConfig) SpanConfig {
|
||||
cfg.spanKind = kind
|
||||
return cfg
|
||||
})
|
||||
}
|
||||
|
||||
// WithInstrumentationVersion sets the instrumentation version.
|
||||
func WithInstrumentationVersion(version string) TracerOption {
|
||||
return tracerOptionFunc(func(cfg TracerConfig) TracerConfig {
|
||||
cfg.instrumentationVersion = version
|
||||
return cfg
|
||||
})
|
||||
}
|
||||
|
||||
// mergeSets returns the union of keys between a and b. Any duplicate keys will
|
||||
// use the value associated with b.
|
||||
func mergeSets(a, b attribute.Set) attribute.Set {
|
||||
// NewMergeIterator uses the first value for any duplicates.
|
||||
iter := attribute.NewMergeIterator(&b, &a)
|
||||
merged := make([]attribute.KeyValue, 0, a.Len()+b.Len())
|
||||
for iter.Next() {
|
||||
merged = append(merged, iter.Attribute())
|
||||
}
|
||||
return attribute.NewSet(merged...)
|
||||
}
|
||||
|
||||
// WithInstrumentationAttributes adds the instrumentation attributes.
|
||||
//
|
||||
// This is equivalent to calling [WithInstrumentationAttributeSet] with an
|
||||
// [attribute.Set] created from a clone of the passed attributes.
|
||||
// [WithInstrumentationAttributeSet] is recommended for more control.
|
||||
//
|
||||
// If multiple [WithInstrumentationAttributes] or [WithInstrumentationAttributeSet]
|
||||
// options are passed, the attributes will be merged together in the order
|
||||
// they are passed. Attributes with duplicate keys will use the last value passed.
|
||||
func WithInstrumentationAttributes(attr ...attribute.KeyValue) TracerOption {
|
||||
set := attribute.NewSet(slices.Clone(attr)...)
|
||||
return WithInstrumentationAttributeSet(set)
|
||||
}
|
||||
|
||||
// WithInstrumentationAttributeSet adds the instrumentation attributes.
|
||||
//
|
||||
// If multiple [WithInstrumentationAttributes] or [WithInstrumentationAttributeSet]
|
||||
// options are passed, the attributes will be merged together in the order
|
||||
// they are passed. Attributes with duplicate keys will use the last value passed.
|
||||
func WithInstrumentationAttributeSet(set attribute.Set) TracerOption {
|
||||
if set.Len() == 0 {
|
||||
return tracerOptionFunc(func(config TracerConfig) TracerConfig {
|
||||
return config
|
||||
})
|
||||
}
|
||||
|
||||
return tracerOptionFunc(func(config TracerConfig) TracerConfig {
|
||||
if config.attrs.Len() == 0 {
|
||||
config.attrs = set
|
||||
} else {
|
||||
config.attrs = mergeSets(config.attrs, set)
|
||||
}
|
||||
return config
|
||||
})
|
||||
}
|
||||
|
||||
// WithSchemaURL sets the schema URL for the Tracer.
|
||||
func WithSchemaURL(schemaURL string) TracerOption {
|
||||
return tracerOptionFunc(func(cfg TracerConfig) TracerConfig {
|
||||
cfg.schemaURL = schemaURL
|
||||
return cfg
|
||||
})
|
||||
}
|
||||
50
vendor/go.opentelemetry.io/otel/trace/context.go
generated
vendored
Normal file
50
vendor/go.opentelemetry.io/otel/trace/context.go
generated
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
import "context"
|
||||
|
||||
type traceContextKeyType int
|
||||
|
||||
const currentSpanKey traceContextKeyType = iota
|
||||
|
||||
// ContextWithSpan returns a copy of parent with span set as the current Span.
|
||||
func ContextWithSpan(parent context.Context, span Span) context.Context {
|
||||
return context.WithValue(parent, currentSpanKey, span)
|
||||
}
|
||||
|
||||
// ContextWithSpanContext returns a copy of parent with sc as the current
|
||||
// Span. The Span implementation that wraps sc is non-recording and performs
|
||||
// no operations other than to return sc as the SpanContext from the
|
||||
// SpanContext method.
|
||||
func ContextWithSpanContext(parent context.Context, sc SpanContext) context.Context {
|
||||
return ContextWithSpan(parent, nonRecordingSpan{sc: sc})
|
||||
}
|
||||
|
||||
// ContextWithRemoteSpanContext returns a copy of parent with rsc set explicitly
|
||||
// as a remote SpanContext and as the current Span. The Span implementation
|
||||
// that wraps rsc is non-recording and performs no operations other than to
|
||||
// return rsc as the SpanContext from the SpanContext method.
|
||||
func ContextWithRemoteSpanContext(parent context.Context, rsc SpanContext) context.Context {
|
||||
return ContextWithSpanContext(parent, rsc.WithRemote(true))
|
||||
}
|
||||
|
||||
// SpanFromContext returns the current Span from ctx.
|
||||
//
|
||||
// If no Span is currently set in ctx an implementation of a Span that
|
||||
// performs no operations is returned.
|
||||
func SpanFromContext(ctx context.Context) Span {
|
||||
if ctx == nil {
|
||||
return noopSpanInstance
|
||||
}
|
||||
if span, ok := ctx.Value(currentSpanKey).(Span); ok {
|
||||
return span
|
||||
}
|
||||
return noopSpanInstance
|
||||
}
|
||||
|
||||
// SpanContextFromContext returns the current Span's SpanContext.
|
||||
func SpanContextFromContext(ctx context.Context) SpanContext {
|
||||
return SpanFromContext(ctx).SpanContext()
|
||||
}
|
||||
119
vendor/go.opentelemetry.io/otel/trace/doc.go
generated
vendored
Normal file
119
vendor/go.opentelemetry.io/otel/trace/doc.go
generated
vendored
Normal file
@@ -0,0 +1,119 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
/*
|
||||
Package trace provides an implementation of the tracing part of the
|
||||
OpenTelemetry API.
|
||||
|
||||
To participate in distributed traces a Span needs to be created for the
|
||||
operation being performed as part of a traced workflow. In its simplest form:
|
||||
|
||||
var tracer trace.Tracer
|
||||
|
||||
func init() {
|
||||
tracer = otel.Tracer("instrumentation/package/name")
|
||||
}
|
||||
|
||||
func operation(ctx context.Context) {
|
||||
var span trace.Span
|
||||
ctx, span = tracer.Start(ctx, "operation")
|
||||
defer span.End()
|
||||
// ...
|
||||
}
|
||||
|
||||
A Tracer is unique to the instrumentation and is used to create Spans.
|
||||
Instrumentation should be designed to accept a TracerProvider from which it
|
||||
can create its own unique Tracer. Alternatively, the registered global
|
||||
TracerProvider from the go.opentelemetry.io/otel package can be used as
|
||||
a default.
|
||||
|
||||
const (
|
||||
name = "instrumentation/package/name"
|
||||
version = "0.1.0"
|
||||
)
|
||||
|
||||
type Instrumentation struct {
|
||||
tracer trace.Tracer
|
||||
}
|
||||
|
||||
func NewInstrumentation(tp trace.TracerProvider) *Instrumentation {
|
||||
if tp == nil {
|
||||
tp = otel.TracerProvider()
|
||||
}
|
||||
return &Instrumentation{
|
||||
tracer: tp.Tracer(name, trace.WithInstrumentationVersion(version)),
|
||||
}
|
||||
}
|
||||
|
||||
func operation(ctx context.Context, inst *Instrumentation) {
|
||||
var span trace.Span
|
||||
ctx, span = inst.tracer.Start(ctx, "operation")
|
||||
defer span.End()
|
||||
// ...
|
||||
}
|
||||
|
||||
# API Implementations
|
||||
|
||||
This package does not conform to the standard Go versioning policy; all of its
|
||||
interfaces may have methods added to them without a package major version bump.
|
||||
This non-standard API evolution could surprise an uninformed implementation
|
||||
author. They could unknowingly build their implementation in a way that would
|
||||
result in a runtime panic for their users that update to the new API.
|
||||
|
||||
The API is designed to help inform an instrumentation author about this
|
||||
non-standard API evolution. It requires them to choose a default behavior for
|
||||
unimplemented interface methods. There are three behavior choices they can
|
||||
make:
|
||||
|
||||
- Compilation failure
|
||||
- Panic
|
||||
- Default to another implementation
|
||||
|
||||
All interfaces in this API embed a corresponding interface from
|
||||
[go.opentelemetry.io/otel/trace/embedded]. If an author wants the default
|
||||
behavior of their implementations to be a compilation failure, signaling to
|
||||
their users they need to update to the latest version of that implementation,
|
||||
they need to embed the corresponding interface from
|
||||
[go.opentelemetry.io/otel/trace/embedded] in their implementation. For
|
||||
example,
|
||||
|
||||
import "go.opentelemetry.io/otel/trace/embedded"
|
||||
|
||||
type TracerProvider struct {
|
||||
embedded.TracerProvider
|
||||
// ...
|
||||
}
|
||||
|
||||
If an author wants the default behavior of their implementations to panic, they
|
||||
can embed the API interface directly.
|
||||
|
||||
import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
type TracerProvider struct {
|
||||
trace.TracerProvider
|
||||
// ...
|
||||
}
|
||||
|
||||
This option is not recommended. It will lead to publishing packages that
|
||||
contain runtime panics when users update to newer versions of
|
||||
[go.opentelemetry.io/otel/trace], which may be done with a transitive
|
||||
dependency.
|
||||
|
||||
Finally, an author can embed another implementation in theirs. The embedded
|
||||
implementation will be used for methods not defined by the author. For example,
|
||||
an author who wants to default to silently dropping the call can use
|
||||
[go.opentelemetry.io/otel/trace/noop]:
|
||||
|
||||
import "go.opentelemetry.io/otel/trace/noop"
|
||||
|
||||
type TracerProvider struct {
|
||||
noop.TracerProvider
|
||||
// ...
|
||||
}
|
||||
|
||||
It is strongly recommended that authors only embed
|
||||
[go.opentelemetry.io/otel/trace/noop] if they choose this default behavior.
|
||||
That implementation is the only one OpenTelemetry authors can guarantee will
|
||||
fully implement all the API interfaces when a user updates their API.
|
||||
*/
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
3
vendor/go.opentelemetry.io/otel/trace/embedded/README.md
generated
vendored
Normal file
3
vendor/go.opentelemetry.io/otel/trace/embedded/README.md
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
# Trace Embedded
|
||||
|
||||
[](https://pkg.go.dev/go.opentelemetry.io/otel/trace/embedded)
|
||||
45
vendor/go.opentelemetry.io/otel/trace/embedded/embedded.go
generated
vendored
Normal file
45
vendor/go.opentelemetry.io/otel/trace/embedded/embedded.go
generated
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package embedded provides interfaces embedded within the [OpenTelemetry
|
||||
// trace API].
|
||||
//
|
||||
// Implementers of the [OpenTelemetry trace API] can embed the relevant type
|
||||
// from this package into their implementation directly. Doing so will result
|
||||
// in a compilation error for users when the [OpenTelemetry trace API] is
|
||||
// extended (which is something that can happen without a major version bump of
|
||||
// the API package).
|
||||
//
|
||||
// [OpenTelemetry trace API]: https://pkg.go.dev/go.opentelemetry.io/otel/trace
|
||||
package embedded // import "go.opentelemetry.io/otel/trace/embedded"
|
||||
|
||||
// TracerProvider is embedded in
|
||||
// [go.opentelemetry.io/otel/trace.TracerProvider].
|
||||
//
|
||||
// Embed this interface in your implementation of the
|
||||
// [go.opentelemetry.io/otel/trace.TracerProvider] if you want users to
|
||||
// experience a compilation error, signaling they need to update to your latest
|
||||
// implementation, when the [go.opentelemetry.io/otel/trace.TracerProvider]
|
||||
// interface is extended (which is something that can happen without a major
|
||||
// version bump of the API package).
|
||||
type TracerProvider interface{ tracerProvider() }
|
||||
|
||||
// Tracer is embedded in [go.opentelemetry.io/otel/trace.Tracer].
|
||||
//
|
||||
// Embed this interface in your implementation of the
|
||||
// [go.opentelemetry.io/otel/trace.Tracer] if you want users to experience a
|
||||
// compilation error, signaling they need to update to your latest
|
||||
// implementation, when the [go.opentelemetry.io/otel/trace.Tracer] interface
|
||||
// is extended (which is something that can happen without a major version bump
|
||||
// of the API package).
|
||||
type Tracer interface{ tracer() }
|
||||
|
||||
// Span is embedded in [go.opentelemetry.io/otel/trace.Span].
|
||||
//
|
||||
// Embed this interface in your implementation of the
|
||||
// [go.opentelemetry.io/otel/trace.Span] if you want users to experience a
|
||||
// compilation error, signaling they need to update to your latest
|
||||
// implementation, when the [go.opentelemetry.io/otel/trace.Span] interface is
|
||||
// extended (which is something that can happen without a major version bump of
|
||||
// the API package).
|
||||
type Span interface{ span() }
|
||||
38
vendor/go.opentelemetry.io/otel/trace/hex.go
generated
vendored
Normal file
38
vendor/go.opentelemetry.io/otel/trace/hex.go
generated
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
const (
|
||||
// hexLU is a hex lookup table of the 16 lowercase hex digits.
|
||||
// The character values of the string are indexed at the equivalent
|
||||
// hexadecimal value they represent. This table efficiently encodes byte data
|
||||
// into a string representation of hexadecimal.
|
||||
hexLU = "0123456789abcdef"
|
||||
|
||||
// hexRev is a reverse hex lookup table for lowercase hex digits.
|
||||
// The table is efficiently decodes a hexadecimal string into bytes.
|
||||
// Valid hexadecimal characters are indexed at their respective values. All
|
||||
// other invalid ASCII characters are represented with '\xff'.
|
||||
//
|
||||
// The '\xff' character is used as invalid because no valid character has
|
||||
// the upper 4 bits set. Meaning, an efficient validation can be performed
|
||||
// over multiple character parsing by checking these bits remain zero.
|
||||
hexRev = "" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\x0a\x0b\x0c\x0d\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" +
|
||||
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
|
||||
)
|
||||
58
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/attr.go
generated
vendored
Normal file
58
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/attr.go
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package telemetry // import "go.opentelemetry.io/otel/trace/internal/telemetry"
|
||||
|
||||
// Attr is a key-value pair.
|
||||
type Attr struct {
|
||||
Key string `json:"key,omitempty"`
|
||||
Value Value `json:"value,omitempty"`
|
||||
}
|
||||
|
||||
// String returns an Attr for a string value.
|
||||
func String(key, value string) Attr {
|
||||
return Attr{key, StringValue(value)}
|
||||
}
|
||||
|
||||
// Int64 returns an Attr for an int64 value.
|
||||
func Int64(key string, value int64) Attr {
|
||||
return Attr{key, Int64Value(value)}
|
||||
}
|
||||
|
||||
// Int returns an Attr for an int value.
|
||||
func Int(key string, value int) Attr {
|
||||
return Int64(key, int64(value))
|
||||
}
|
||||
|
||||
// Float64 returns an Attr for a float64 value.
|
||||
func Float64(key string, value float64) Attr {
|
||||
return Attr{key, Float64Value(value)}
|
||||
}
|
||||
|
||||
// Bool returns an Attr for a bool value.
|
||||
func Bool(key string, value bool) Attr {
|
||||
return Attr{key, BoolValue(value)}
|
||||
}
|
||||
|
||||
// Bytes returns an Attr for a []byte value.
|
||||
// The passed slice must not be changed after it is passed.
|
||||
func Bytes(key string, value []byte) Attr {
|
||||
return Attr{key, BytesValue(value)}
|
||||
}
|
||||
|
||||
// Slice returns an Attr for a []Value value.
|
||||
// The passed slice must not be changed after it is passed.
|
||||
func Slice(key string, value ...Value) Attr {
|
||||
return Attr{key, SliceValue(value...)}
|
||||
}
|
||||
|
||||
// Map returns an Attr for a map value.
|
||||
// The passed slice must not be changed after it is passed.
|
||||
func Map(key string, value ...Attr) Attr {
|
||||
return Attr{key, MapValue(value...)}
|
||||
}
|
||||
|
||||
// Equal reports whether a is equal to b.
|
||||
func (a Attr) Equal(b Attr) bool {
|
||||
return a.Key == b.Key && a.Value.Equal(b.Value)
|
||||
}
|
||||
8
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/doc.go
generated
vendored
Normal file
8
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/doc.go
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
/*
|
||||
Package telemetry provides a lightweight representations of OpenTelemetry
|
||||
telemetry that is compatible with the OTLP JSON protobuf encoding.
|
||||
*/
|
||||
package telemetry // import "go.opentelemetry.io/otel/trace/internal/telemetry"
|
||||
103
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/id.go
generated
vendored
Normal file
103
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/id.go
generated
vendored
Normal file
@@ -0,0 +1,103 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package telemetry // import "go.opentelemetry.io/otel/trace/internal/telemetry"
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const (
|
||||
traceIDSize = 16
|
||||
spanIDSize = 8
|
||||
)
|
||||
|
||||
// TraceID is a custom data type that is used for all trace IDs.
|
||||
type TraceID [traceIDSize]byte
|
||||
|
||||
// String returns the hex string representation form of a TraceID.
|
||||
func (tid TraceID) String() string {
|
||||
return hex.EncodeToString(tid[:])
|
||||
}
|
||||
|
||||
// IsEmpty reports whether the TraceID contains only zero bytes.
|
||||
func (tid TraceID) IsEmpty() bool {
|
||||
return tid == [traceIDSize]byte{}
|
||||
}
|
||||
|
||||
// MarshalJSON converts the trace ID into a hex string enclosed in quotes.
|
||||
func (tid TraceID) MarshalJSON() ([]byte, error) {
|
||||
if tid.IsEmpty() {
|
||||
return []byte(`""`), nil
|
||||
}
|
||||
return marshalJSON(tid[:])
|
||||
}
|
||||
|
||||
// UnmarshalJSON inflates the trace ID from hex string, possibly enclosed in
|
||||
// quotes.
|
||||
func (tid *TraceID) UnmarshalJSON(data []byte) error {
|
||||
*tid = [traceIDSize]byte{}
|
||||
return unmarshalJSON(tid[:], data)
|
||||
}
|
||||
|
||||
// SpanID is a custom data type that is used for all span IDs.
|
||||
type SpanID [spanIDSize]byte
|
||||
|
||||
// String returns the hex string representation form of a SpanID.
|
||||
func (sid SpanID) String() string {
|
||||
return hex.EncodeToString(sid[:])
|
||||
}
|
||||
|
||||
// IsEmpty reports whether the SpanID contains only zero bytes.
|
||||
func (sid SpanID) IsEmpty() bool {
|
||||
return sid == [spanIDSize]byte{}
|
||||
}
|
||||
|
||||
// MarshalJSON converts span ID into a hex string enclosed in quotes.
|
||||
func (sid SpanID) MarshalJSON() ([]byte, error) {
|
||||
if sid.IsEmpty() {
|
||||
return []byte(`""`), nil
|
||||
}
|
||||
return marshalJSON(sid[:])
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes span ID from hex string, possibly enclosed in quotes.
|
||||
func (sid *SpanID) UnmarshalJSON(data []byte) error {
|
||||
*sid = [spanIDSize]byte{}
|
||||
return unmarshalJSON(sid[:], data)
|
||||
}
|
||||
|
||||
// marshalJSON converts id into a hex string enclosed in quotes.
|
||||
func marshalJSON(id []byte) ([]byte, error) {
|
||||
// Plus 2 quote chars at the start and end.
|
||||
hexLen := hex.EncodedLen(len(id)) + 2
|
||||
|
||||
b := make([]byte, hexLen)
|
||||
hex.Encode(b[1:hexLen-1], id)
|
||||
b[0], b[hexLen-1] = '"', '"'
|
||||
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// unmarshalJSON inflates trace id from hex string, possibly enclosed in quotes.
|
||||
func unmarshalJSON(dst, src []byte) error {
|
||||
if l := len(src); l >= 2 && src[0] == '"' && src[l-1] == '"' {
|
||||
src = src[1 : l-1]
|
||||
}
|
||||
nLen := len(src)
|
||||
if nLen == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(dst) != hex.DecodedLen(nLen) {
|
||||
return errors.New("invalid length for ID")
|
||||
}
|
||||
|
||||
_, err := hex.Decode(dst, src)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot unmarshal ID from string '%s': %w", string(src), err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
67
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/number.go
generated
vendored
Normal file
67
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/number.go
generated
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package telemetry // import "go.opentelemetry.io/otel/trace/internal/telemetry"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// protoInt64 represents the protobuf encoding of integers which can be either
|
||||
// strings or integers.
|
||||
type protoInt64 int64
|
||||
|
||||
// Int64 returns the protoInt64 as an int64.
|
||||
func (i *protoInt64) Int64() int64 { return int64(*i) }
|
||||
|
||||
// UnmarshalJSON decodes both strings and integers.
|
||||
func (i *protoInt64) UnmarshalJSON(data []byte) error {
|
||||
if data[0] == '"' {
|
||||
var str string
|
||||
if err := json.Unmarshal(data, &str); err != nil {
|
||||
return err
|
||||
}
|
||||
parsedInt, err := strconv.ParseInt(str, 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*i = protoInt64(parsedInt)
|
||||
} else {
|
||||
var parsedInt int64
|
||||
if err := json.Unmarshal(data, &parsedInt); err != nil {
|
||||
return err
|
||||
}
|
||||
*i = protoInt64(parsedInt)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// protoUint64 represents the protobuf encoding of integers which can be either
|
||||
// strings or integers.
|
||||
type protoUint64 uint64
|
||||
|
||||
// Int64 returns the protoUint64 as a uint64.
|
||||
func (i *protoUint64) Uint64() uint64 { return uint64(*i) }
|
||||
|
||||
// UnmarshalJSON decodes both strings and integers.
|
||||
func (i *protoUint64) UnmarshalJSON(data []byte) error {
|
||||
if data[0] == '"' {
|
||||
var str string
|
||||
if err := json.Unmarshal(data, &str); err != nil {
|
||||
return err
|
||||
}
|
||||
parsedUint, err := strconv.ParseUint(str, 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*i = protoUint64(parsedUint)
|
||||
} else {
|
||||
var parsedUint uint64
|
||||
if err := json.Unmarshal(data, &parsedUint); err != nil {
|
||||
return err
|
||||
}
|
||||
*i = protoUint64(parsedUint)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
66
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/resource.go
generated
vendored
Normal file
66
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/resource.go
generated
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package telemetry // import "go.opentelemetry.io/otel/trace/internal/telemetry"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Resource information.
|
||||
type Resource struct {
|
||||
// Attrs are the set of attributes that describe the resource. Attribute
|
||||
// keys MUST be unique (it is not allowed to have more than one attribute
|
||||
// with the same key).
|
||||
Attrs []Attr `json:"attributes,omitempty"`
|
||||
// DroppedAttrs is the number of dropped attributes. If the value
|
||||
// is 0, then no attributes were dropped.
|
||||
DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes the OTLP formatted JSON contained in data into r.
|
||||
func (r *Resource) UnmarshalJSON(data []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
|
||||
t, err := decoder.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t != json.Delim('{') {
|
||||
return errors.New("invalid Resource type")
|
||||
}
|
||||
|
||||
for decoder.More() {
|
||||
keyIface, err := decoder.Token()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
// Empty.
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
key, ok := keyIface.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid Resource field: %#v", keyIface)
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "attributes":
|
||||
err = decoder.Decode(&r.Attrs)
|
||||
case "droppedAttributesCount", "dropped_attributes_count":
|
||||
err = decoder.Decode(&r.DroppedAttrs)
|
||||
default:
|
||||
// Skip unknown.
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
67
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/scope.go
generated
vendored
Normal file
67
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/scope.go
generated
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package telemetry // import "go.opentelemetry.io/otel/trace/internal/telemetry"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Scope is the identifying values of the instrumentation scope.
|
||||
type Scope struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Attrs []Attr `json:"attributes,omitempty"`
|
||||
DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes the OTLP formatted JSON contained in data into r.
|
||||
func (s *Scope) UnmarshalJSON(data []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
|
||||
t, err := decoder.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t != json.Delim('{') {
|
||||
return errors.New("invalid Scope type")
|
||||
}
|
||||
|
||||
for decoder.More() {
|
||||
keyIface, err := decoder.Token()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
// Empty.
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
key, ok := keyIface.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid Scope field: %#v", keyIface)
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "name":
|
||||
err = decoder.Decode(&s.Name)
|
||||
case "version":
|
||||
err = decoder.Decode(&s.Version)
|
||||
case "attributes":
|
||||
err = decoder.Decode(&s.Attrs)
|
||||
case "droppedAttributesCount", "dropped_attributes_count":
|
||||
err = decoder.Decode(&s.DroppedAttrs)
|
||||
default:
|
||||
// Skip unknown.
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
472
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/span.go
generated
vendored
Normal file
472
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/span.go
generated
vendored
Normal file
@@ -0,0 +1,472 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package telemetry // import "go.opentelemetry.io/otel/trace/internal/telemetry"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A Span represents a single operation performed by a single component of the
|
||||
// system.
|
||||
type Span struct {
|
||||
// A unique identifier for a trace. All spans from the same trace share
|
||||
// the same `trace_id`. The ID is a 16-byte array. An ID with all zeroes OR
|
||||
// of length other than 16 bytes is considered invalid (empty string in OTLP/JSON
|
||||
// is zero-length and thus is also invalid).
|
||||
//
|
||||
// This field is required.
|
||||
TraceID TraceID `json:"traceId,omitempty"`
|
||||
// A unique identifier for a span within a trace, assigned when the span
|
||||
// is created. The ID is an 8-byte array. An ID with all zeroes OR of length
|
||||
// other than 8 bytes is considered invalid (empty string in OTLP/JSON
|
||||
// is zero-length and thus is also invalid).
|
||||
//
|
||||
// This field is required.
|
||||
SpanID SpanID `json:"spanId,omitempty"`
|
||||
// trace_state conveys information about request position in multiple distributed tracing graphs.
|
||||
// It is a trace_state in w3c-trace-context format: https://www.w3.org/TR/trace-context/#tracestate-header
|
||||
// See also https://github.com/w3c/distributed-tracing for more details about this field.
|
||||
TraceState string `json:"traceState,omitempty"`
|
||||
// The `span_id` of this span's parent span. If this is a root span, then this
|
||||
// field must be empty. The ID is an 8-byte array.
|
||||
ParentSpanID SpanID `json:"parentSpanId,omitempty"`
|
||||
// Flags, a bit field.
|
||||
//
|
||||
// Bits 0-7 (8 least significant bits) are the trace flags as defined in W3C Trace
|
||||
// Context specification. To read the 8-bit W3C trace flag, use
|
||||
// `flags & SPAN_FLAGS_TRACE_FLAGS_MASK`.
|
||||
//
|
||||
// See https://www.w3.org/TR/trace-context-2/#trace-flags for the flag definitions.
|
||||
//
|
||||
// Bits 8 and 9 represent the 3 states of whether a span's parent
|
||||
// is remote. The states are (unknown, is not remote, is remote).
|
||||
// To read whether the value is known, use `(flags & SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK) != 0`.
|
||||
// To read whether the span is remote, use `(flags & SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK) != 0`.
|
||||
//
|
||||
// When creating span messages, if the message is logically forwarded from another source
|
||||
// with an equivalent flags fields (i.e., usually another OTLP span message), the field SHOULD
|
||||
// be copied as-is. If creating from a source that does not have an equivalent flags field
|
||||
// (such as a runtime representation of an OpenTelemetry span), the high 22 bits MUST
|
||||
// be set to zero.
|
||||
// Readers MUST NOT assume that bits 10-31 (22 most significant bits) will be zero.
|
||||
//
|
||||
// [Optional].
|
||||
Flags uint32 `json:"flags,omitempty"`
|
||||
// A description of the span's operation.
|
||||
//
|
||||
// For example, the name can be a qualified method name or a file name
|
||||
// and a line number where the operation is called. A best practice is to use
|
||||
// the same display name at the same call point in an application.
|
||||
// This makes it easier to correlate spans in different traces.
|
||||
//
|
||||
// This field is semantically required to be set to non-empty string.
|
||||
// Empty value is equivalent to an unknown span name.
|
||||
//
|
||||
// This field is required.
|
||||
Name string `json:"name"`
|
||||
// Distinguishes between spans generated in a particular context. For example,
|
||||
// two spans with the same name may be distinguished using `CLIENT` (caller)
|
||||
// and `SERVER` (callee) to identify queueing latency associated with the span.
|
||||
Kind SpanKind `json:"kind,omitempty"`
|
||||
// start_time_unix_nano is the start time of the span. On the client side, this is the time
|
||||
// kept by the local machine where the span execution starts. On the server side, this
|
||||
// is the time when the server's application handler starts running.
|
||||
// Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970.
|
||||
//
|
||||
// This field is semantically required and it is expected that end_time >= start_time.
|
||||
StartTime time.Time `json:"startTimeUnixNano,omitempty"`
|
||||
// end_time_unix_nano is the end time of the span. On the client side, this is the time
|
||||
// kept by the local machine where the span execution ends. On the server side, this
|
||||
// is the time when the server application handler stops running.
|
||||
// Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970.
|
||||
//
|
||||
// This field is semantically required and it is expected that end_time >= start_time.
|
||||
EndTime time.Time `json:"endTimeUnixNano,omitempty"`
|
||||
// attributes is a collection of key/value pairs. Note, global attributes
|
||||
// like server name can be set using the resource API. Examples of attributes:
|
||||
//
|
||||
// "/http/user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
|
||||
// "/http/server_latency": 300
|
||||
// "example.com/myattribute": true
|
||||
// "example.com/score": 10.239
|
||||
//
|
||||
// The OpenTelemetry API specification further restricts the allowed value types:
|
||||
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/common/README.md#attribute
|
||||
// Attribute keys MUST be unique (it is not allowed to have more than one
|
||||
// attribute with the same key).
|
||||
Attrs []Attr `json:"attributes,omitempty"`
|
||||
// dropped_attributes_count is the number of attributes that were discarded. Attributes
|
||||
// can be discarded because their keys are too long or because there are too many
|
||||
// attributes. If this value is 0, then no attributes were dropped.
|
||||
DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
|
||||
// events is a collection of Event items.
|
||||
Events []*SpanEvent `json:"events,omitempty"`
|
||||
// dropped_events_count is the number of dropped events. If the value is 0, then no
|
||||
// events were dropped.
|
||||
DroppedEvents uint32 `json:"droppedEventsCount,omitempty"`
|
||||
// links is a collection of Links, which are references from this span to a span
|
||||
// in the same or different trace.
|
||||
Links []*SpanLink `json:"links,omitempty"`
|
||||
// dropped_links_count is the number of dropped links after the maximum size was
|
||||
// enforced. If this value is 0, then no links were dropped.
|
||||
DroppedLinks uint32 `json:"droppedLinksCount,omitempty"`
|
||||
// An optional final status for this span. Semantically when Status isn't set, it means
|
||||
// span's status code is unset, i.e. assume STATUS_CODE_UNSET (code = 0).
|
||||
Status *Status `json:"status,omitempty"`
|
||||
}
|
||||
|
||||
// MarshalJSON encodes s into OTLP formatted JSON.
|
||||
func (s Span) MarshalJSON() ([]byte, error) {
|
||||
startT := s.StartTime.UnixNano()
|
||||
if s.StartTime.IsZero() || startT < 0 {
|
||||
startT = 0
|
||||
}
|
||||
|
||||
endT := s.EndTime.UnixNano()
|
||||
if s.EndTime.IsZero() || endT < 0 {
|
||||
endT = 0
|
||||
}
|
||||
|
||||
// Override non-empty default SpanID marshal and omitempty.
|
||||
var parentSpanId string
|
||||
if !s.ParentSpanID.IsEmpty() {
|
||||
b := make([]byte, hex.EncodedLen(spanIDSize))
|
||||
hex.Encode(b, s.ParentSpanID[:])
|
||||
parentSpanId = string(b)
|
||||
}
|
||||
|
||||
type Alias Span
|
||||
return json.Marshal(struct {
|
||||
Alias
|
||||
ParentSpanID string `json:"parentSpanId,omitempty"`
|
||||
StartTime uint64 `json:"startTimeUnixNano,omitempty"`
|
||||
EndTime uint64 `json:"endTimeUnixNano,omitempty"`
|
||||
}{
|
||||
Alias: Alias(s),
|
||||
ParentSpanID: parentSpanId,
|
||||
StartTime: uint64(startT), // nolint:gosec // >0 checked above.
|
||||
EndTime: uint64(endT), // nolint:gosec // >0 checked above.
|
||||
})
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes the OTLP formatted JSON contained in data into s.
|
||||
func (s *Span) UnmarshalJSON(data []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
|
||||
t, err := decoder.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t != json.Delim('{') {
|
||||
return errors.New("invalid Span type")
|
||||
}
|
||||
|
||||
for decoder.More() {
|
||||
keyIface, err := decoder.Token()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
// Empty.
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
key, ok := keyIface.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid Span field: %#v", keyIface)
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "traceId", "trace_id":
|
||||
err = decoder.Decode(&s.TraceID)
|
||||
case "spanId", "span_id":
|
||||
err = decoder.Decode(&s.SpanID)
|
||||
case "traceState", "trace_state":
|
||||
err = decoder.Decode(&s.TraceState)
|
||||
case "parentSpanId", "parent_span_id":
|
||||
err = decoder.Decode(&s.ParentSpanID)
|
||||
case "flags":
|
||||
err = decoder.Decode(&s.Flags)
|
||||
case "name":
|
||||
err = decoder.Decode(&s.Name)
|
||||
case "kind":
|
||||
err = decoder.Decode(&s.Kind)
|
||||
case "startTimeUnixNano", "start_time_unix_nano":
|
||||
var val protoUint64
|
||||
err = decoder.Decode(&val)
|
||||
v := int64(min(val.Uint64(), math.MaxInt64)) // nolint: gosec // Overflow checked.
|
||||
s.StartTime = time.Unix(0, v)
|
||||
case "endTimeUnixNano", "end_time_unix_nano":
|
||||
var val protoUint64
|
||||
err = decoder.Decode(&val)
|
||||
v := int64(min(val.Uint64(), math.MaxInt64)) // nolint: gosec // Overflow checked.
|
||||
s.EndTime = time.Unix(0, v)
|
||||
case "attributes":
|
||||
err = decoder.Decode(&s.Attrs)
|
||||
case "droppedAttributesCount", "dropped_attributes_count":
|
||||
err = decoder.Decode(&s.DroppedAttrs)
|
||||
case "events":
|
||||
err = decoder.Decode(&s.Events)
|
||||
case "droppedEventsCount", "dropped_events_count":
|
||||
err = decoder.Decode(&s.DroppedEvents)
|
||||
case "links":
|
||||
err = decoder.Decode(&s.Links)
|
||||
case "droppedLinksCount", "dropped_links_count":
|
||||
err = decoder.Decode(&s.DroppedLinks)
|
||||
case "status":
|
||||
err = decoder.Decode(&s.Status)
|
||||
default:
|
||||
// Skip unknown.
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SpanFlags represents constants used to interpret the
|
||||
// Span.flags field, which is protobuf 'fixed32' type and is to
|
||||
// be used as bit-fields. Each non-zero value defined in this enum is
|
||||
// a bit-mask. To extract the bit-field, for example, use an
|
||||
// expression like:
|
||||
//
|
||||
// (span.flags & SPAN_FLAGS_TRACE_FLAGS_MASK)
|
||||
//
|
||||
// See https://www.w3.org/TR/trace-context-2/#trace-flags for the flag definitions.
|
||||
//
|
||||
// Note that Span flags were introduced in version 1.1 of the
|
||||
// OpenTelemetry protocol. Older Span producers do not set this
|
||||
// field, consequently consumers should not rely on the absence of a
|
||||
// particular flag bit to indicate the presence of a particular feature.
|
||||
type SpanFlags int32
|
||||
|
||||
const (
|
||||
// SpanFlagsTraceFlagsMask is a mask for trace-flags.
|
||||
//
|
||||
// Bits 0-7 are used for trace flags.
|
||||
SpanFlagsTraceFlagsMask SpanFlags = 255
|
||||
// SpanFlagsContextHasIsRemoteMask is a mask for HAS_IS_REMOTE status.
|
||||
//
|
||||
// Bits 8 and 9 are used to indicate that the parent span or link span is
|
||||
// remote. Bit 8 (`HAS_IS_REMOTE`) indicates whether the value is known.
|
||||
SpanFlagsContextHasIsRemoteMask SpanFlags = 256
|
||||
// SpanFlagsContextIsRemoteMask is a mask for IS_REMOTE status.
|
||||
//
|
||||
// Bits 8 and 9 are used to indicate that the parent span or link span is
|
||||
// remote. Bit 9 (`IS_REMOTE`) indicates whether the span or link is
|
||||
// remote.
|
||||
SpanFlagsContextIsRemoteMask SpanFlags = 512
|
||||
)
|
||||
|
||||
// SpanKind is the type of span. Can be used to specify additional relationships between spans
|
||||
// in addition to a parent/child relationship.
|
||||
type SpanKind int32
|
||||
|
||||
const (
|
||||
// SpanKindInternal indicates that the span represents an internal
|
||||
// operation within an application, as opposed to an operation happening at
|
||||
// the boundaries.
|
||||
SpanKindInternal SpanKind = 1
|
||||
// SpanKindServer indicates that the span covers server-side handling of an
|
||||
// RPC or other remote network request.
|
||||
SpanKindServer SpanKind = 2
|
||||
// SpanKindClient indicates that the span describes a request to some
|
||||
// remote service.
|
||||
SpanKindClient SpanKind = 3
|
||||
// SpanKindProducer indicates that the span describes a producer sending a
|
||||
// message to a broker. Unlike SpanKindClient and SpanKindServer, there is
|
||||
// often no direct critical path latency relationship between producer and
|
||||
// consumer spans. A SpanKindProducer span ends when the message was
|
||||
// accepted by the broker while the logical processing of the message might
|
||||
// span a much longer time.
|
||||
SpanKindProducer SpanKind = 4
|
||||
// SpanKindConsumer indicates that the span describes a consumer receiving
|
||||
// a message from a broker. Like SpanKindProducer, there is often no direct
|
||||
// critical path latency relationship between producer and consumer spans.
|
||||
SpanKindConsumer SpanKind = 5
|
||||
)
|
||||
|
||||
// SpanEvent is a time-stamped annotation of the span, consisting of
|
||||
// user-supplied text description and key-value pairs.
|
||||
type SpanEvent struct {
|
||||
// time_unix_nano is the time the event occurred.
|
||||
Time time.Time `json:"timeUnixNano,omitempty"`
|
||||
// name of the event.
|
||||
// This field is semantically required to be set to non-empty string.
|
||||
Name string `json:"name,omitempty"`
|
||||
// attributes is a collection of attribute key/value pairs on the event.
|
||||
// Attribute keys MUST be unique (it is not allowed to have more than one
|
||||
// attribute with the same key).
|
||||
Attrs []Attr `json:"attributes,omitempty"`
|
||||
// dropped_attributes_count is the number of dropped attributes. If the value is 0,
|
||||
// then no attributes were dropped.
|
||||
DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
|
||||
}
|
||||
|
||||
// MarshalJSON encodes e into OTLP formatted JSON.
|
||||
func (e SpanEvent) MarshalJSON() ([]byte, error) {
|
||||
t := e.Time.UnixNano()
|
||||
if e.Time.IsZero() || t < 0 {
|
||||
t = 0
|
||||
}
|
||||
|
||||
type Alias SpanEvent
|
||||
return json.Marshal(struct {
|
||||
Alias
|
||||
Time uint64 `json:"timeUnixNano,omitempty"`
|
||||
}{
|
||||
Alias: Alias(e),
|
||||
Time: uint64(t), // nolint: gosec // >0 checked above
|
||||
})
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes the OTLP formatted JSON contained in data into se.
|
||||
func (se *SpanEvent) UnmarshalJSON(data []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
|
||||
t, err := decoder.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t != json.Delim('{') {
|
||||
return errors.New("invalid SpanEvent type")
|
||||
}
|
||||
|
||||
for decoder.More() {
|
||||
keyIface, err := decoder.Token()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
// Empty.
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
key, ok := keyIface.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid SpanEvent field: %#v", keyIface)
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "timeUnixNano", "time_unix_nano":
|
||||
var val protoUint64
|
||||
err = decoder.Decode(&val)
|
||||
v := int64(min(val.Uint64(), math.MaxInt64)) // nolint: gosec // Overflow checked.
|
||||
se.Time = time.Unix(0, v)
|
||||
case "name":
|
||||
err = decoder.Decode(&se.Name)
|
||||
case "attributes":
|
||||
err = decoder.Decode(&se.Attrs)
|
||||
case "droppedAttributesCount", "dropped_attributes_count":
|
||||
err = decoder.Decode(&se.DroppedAttrs)
|
||||
default:
|
||||
// Skip unknown.
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SpanLink is a reference from the current span to another span in the same
|
||||
// trace or in a different trace. For example, this can be used in batching
|
||||
// operations, where a single batch handler processes multiple requests from
|
||||
// different traces or when the handler receives a request from a different
|
||||
// project.
|
||||
type SpanLink struct {
|
||||
// A unique identifier of a trace that this linked span is part of. The ID is a
|
||||
// 16-byte array.
|
||||
TraceID TraceID `json:"traceId,omitempty"`
|
||||
// A unique identifier for the linked span. The ID is an 8-byte array.
|
||||
SpanID SpanID `json:"spanId,omitempty"`
|
||||
// The trace_state associated with the link.
|
||||
TraceState string `json:"traceState,omitempty"`
|
||||
// attributes is a collection of attribute key/value pairs on the link.
|
||||
// Attribute keys MUST be unique (it is not allowed to have more than one
|
||||
// attribute with the same key).
|
||||
Attrs []Attr `json:"attributes,omitempty"`
|
||||
// dropped_attributes_count is the number of dropped attributes. If the value is 0,
|
||||
// then no attributes were dropped.
|
||||
DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
|
||||
// Flags, a bit field.
|
||||
//
|
||||
// Bits 0-7 (8 least significant bits) are the trace flags as defined in W3C Trace
|
||||
// Context specification. To read the 8-bit W3C trace flag, use
|
||||
// `flags & SPAN_FLAGS_TRACE_FLAGS_MASK`.
|
||||
//
|
||||
// See https://www.w3.org/TR/trace-context-2/#trace-flags for the flag definitions.
|
||||
//
|
||||
// Bits 8 and 9 represent the 3 states of whether the link is remote.
|
||||
// The states are (unknown, is not remote, is remote).
|
||||
// To read whether the value is known, use `(flags & SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK) != 0`.
|
||||
// To read whether the link is remote, use `(flags & SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK) != 0`.
|
||||
//
|
||||
// Readers MUST NOT assume that bits 10-31 (22 most significant bits) will be zero.
|
||||
// When creating new spans, bits 10-31 (most-significant 22-bits) MUST be zero.
|
||||
//
|
||||
// [Optional].
|
||||
Flags uint32 `json:"flags,omitempty"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes the OTLP formatted JSON contained in data into sl.
|
||||
func (sl *SpanLink) UnmarshalJSON(data []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
|
||||
t, err := decoder.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t != json.Delim('{') {
|
||||
return errors.New("invalid SpanLink type")
|
||||
}
|
||||
|
||||
for decoder.More() {
|
||||
keyIface, err := decoder.Token()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
// Empty.
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
key, ok := keyIface.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid SpanLink field: %#v", keyIface)
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "traceId", "trace_id":
|
||||
err = decoder.Decode(&sl.TraceID)
|
||||
case "spanId", "span_id":
|
||||
err = decoder.Decode(&sl.SpanID)
|
||||
case "traceState", "trace_state":
|
||||
err = decoder.Decode(&sl.TraceState)
|
||||
case "attributes":
|
||||
err = decoder.Decode(&sl.Attrs)
|
||||
case "droppedAttributesCount", "dropped_attributes_count":
|
||||
err = decoder.Decode(&sl.DroppedAttrs)
|
||||
case "flags":
|
||||
err = decoder.Decode(&sl.Flags)
|
||||
default:
|
||||
// Skip unknown.
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
42
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/status.go
generated
vendored
Normal file
42
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/status.go
generated
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package telemetry // import "go.opentelemetry.io/otel/trace/internal/telemetry"
|
||||
|
||||
// StatusCode is the status of a Span.
|
||||
//
|
||||
// For the semantics of status codes see
|
||||
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#set-status
|
||||
type StatusCode int32
|
||||
|
||||
const (
|
||||
// StatusCodeUnset is the default status.
|
||||
StatusCodeUnset StatusCode = 0
|
||||
// StatusCodeOK is used when the Span has been validated by an Application
|
||||
// developer or Operator to have completed successfully.
|
||||
StatusCodeOK StatusCode = 1
|
||||
// StatusCodeError is used when the Span contains an error.
|
||||
StatusCodeError StatusCode = 2
|
||||
)
|
||||
|
||||
var statusCodeStrings = []string{
|
||||
"Unset",
|
||||
"OK",
|
||||
"Error",
|
||||
}
|
||||
|
||||
func (s StatusCode) String() string {
|
||||
if s >= 0 && int(s) < len(statusCodeStrings) {
|
||||
return statusCodeStrings[s]
|
||||
}
|
||||
return "<unknown telemetry.StatusCode>"
|
||||
}
|
||||
|
||||
// Status defines a logical error model that is suitable for different
|
||||
// programming environments, including REST APIs and RPC APIs.
|
||||
type Status struct {
|
||||
// A developer-facing human readable error message.
|
||||
Message string `json:"message,omitempty"`
|
||||
// The status code.
|
||||
Code StatusCode `json:"code,omitempty"`
|
||||
}
|
||||
189
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/traces.go
generated
vendored
Normal file
189
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/traces.go
generated
vendored
Normal file
@@ -0,0 +1,189 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package telemetry // import "go.opentelemetry.io/otel/trace/internal/telemetry"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Traces represents the traces data that can be stored in a persistent storage,
|
||||
// OR can be embedded by other protocols that transfer OTLP traces data but do
|
||||
// not implement the OTLP protocol.
|
||||
//
|
||||
// The main difference between this message and collector protocol is that
|
||||
// in this message there will not be any "control" or "metadata" specific to
|
||||
// OTLP protocol.
|
||||
//
|
||||
// When new fields are added into this message, the OTLP request MUST be updated
|
||||
// as well.
|
||||
type Traces struct {
|
||||
// An array of ResourceSpans.
|
||||
// For data coming from a single resource this array will typically contain
|
||||
// one element. Intermediary nodes that receive data from multiple origins
|
||||
// typically batch the data before forwarding further and in that case this
|
||||
// array will contain multiple elements.
|
||||
ResourceSpans []*ResourceSpans `json:"resourceSpans,omitempty"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes the OTLP formatted JSON contained in data into td.
|
||||
func (td *Traces) UnmarshalJSON(data []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
|
||||
t, err := decoder.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t != json.Delim('{') {
|
||||
return errors.New("invalid TracesData type")
|
||||
}
|
||||
|
||||
for decoder.More() {
|
||||
keyIface, err := decoder.Token()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
// Empty.
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
key, ok := keyIface.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid TracesData field: %#v", keyIface)
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "resourceSpans", "resource_spans":
|
||||
err = decoder.Decode(&td.ResourceSpans)
|
||||
default:
|
||||
// Skip unknown.
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResourceSpans is a collection of ScopeSpans from a Resource.
|
||||
type ResourceSpans struct {
|
||||
// The resource for the spans in this message.
|
||||
// If this field is not set then no resource info is known.
|
||||
Resource Resource `json:"resource"`
|
||||
// A list of ScopeSpans that originate from a resource.
|
||||
ScopeSpans []*ScopeSpans `json:"scopeSpans,omitempty"`
|
||||
// This schema_url applies to the data in the "resource" field. It does not apply
|
||||
// to the data in the "scope_spans" field which have their own schema_url field.
|
||||
SchemaURL string `json:"schemaUrl,omitempty"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes the OTLP formatted JSON contained in data into rs.
|
||||
func (rs *ResourceSpans) UnmarshalJSON(data []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
|
||||
t, err := decoder.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t != json.Delim('{') {
|
||||
return errors.New("invalid ResourceSpans type")
|
||||
}
|
||||
|
||||
for decoder.More() {
|
||||
keyIface, err := decoder.Token()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
// Empty.
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
key, ok := keyIface.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid ResourceSpans field: %#v", keyIface)
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "resource":
|
||||
err = decoder.Decode(&rs.Resource)
|
||||
case "scopeSpans", "scope_spans":
|
||||
err = decoder.Decode(&rs.ScopeSpans)
|
||||
case "schemaUrl", "schema_url":
|
||||
err = decoder.Decode(&rs.SchemaURL)
|
||||
default:
|
||||
// Skip unknown.
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ScopeSpans is a collection of Spans produced by an InstrumentationScope.
|
||||
type ScopeSpans struct {
|
||||
// The instrumentation scope information for the spans in this message.
|
||||
// Semantically when InstrumentationScope isn't set, it is equivalent with
|
||||
// an empty instrumentation scope name (unknown).
|
||||
Scope *Scope `json:"scope"`
|
||||
// A list of Spans that originate from an instrumentation scope.
|
||||
Spans []*Span `json:"spans,omitempty"`
|
||||
// The Schema URL, if known. This is the identifier of the Schema that the span data
|
||||
// is recorded in. To learn more about Schema URL see
|
||||
// https://opentelemetry.io/docs/specs/otel/schemas/#schema-url
|
||||
// This schema_url applies to all spans and span events in the "spans" field.
|
||||
SchemaURL string `json:"schemaUrl,omitempty"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes the OTLP formatted JSON contained in data into ss.
|
||||
func (ss *ScopeSpans) UnmarshalJSON(data []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
|
||||
t, err := decoder.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t != json.Delim('{') {
|
||||
return errors.New("invalid ScopeSpans type")
|
||||
}
|
||||
|
||||
for decoder.More() {
|
||||
keyIface, err := decoder.Token()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
// Empty.
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
key, ok := keyIface.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid ScopeSpans field: %#v", keyIface)
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "scope":
|
||||
err = decoder.Decode(&ss.Scope)
|
||||
case "spans":
|
||||
err = decoder.Decode(&ss.Spans)
|
||||
case "schemaUrl", "schema_url":
|
||||
err = decoder.Decode(&ss.SchemaURL)
|
||||
default:
|
||||
// Skip unknown.
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
453
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/value.go
generated
vendored
Normal file
453
vendor/go.opentelemetry.io/otel/trace/internal/telemetry/value.go
generated
vendored
Normal file
@@ -0,0 +1,453 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package telemetry // import "go.opentelemetry.io/otel/trace/internal/telemetry"
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"slices"
|
||||
"strconv"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// A Value represents a structured value.
|
||||
// A zero value is valid and represents an empty value.
|
||||
type Value struct {
|
||||
// Ensure forward compatibility by explicitly making this not comparable.
|
||||
noCmp [0]func() //nolint: unused // This is indeed used.
|
||||
|
||||
// num holds the value for Int64, Float64, and Bool. It holds the length
|
||||
// for String, Bytes, Slice, Map.
|
||||
num uint64
|
||||
// any holds either the KindBool, KindInt64, KindFloat64, stringptr,
|
||||
// bytesptr, sliceptr, or mapptr. If KindBool, KindInt64, or KindFloat64
|
||||
// then the value of Value is in num as described above. Otherwise, it
|
||||
// contains the value wrapped in the appropriate type.
|
||||
any any
|
||||
}
|
||||
|
||||
type (
|
||||
// sliceptr represents a value in Value.any for KindString Values.
|
||||
stringptr *byte
|
||||
// bytesptr represents a value in Value.any for KindBytes Values.
|
||||
bytesptr *byte
|
||||
// sliceptr represents a value in Value.any for KindSlice Values.
|
||||
sliceptr *Value
|
||||
// mapptr represents a value in Value.any for KindMap Values.
|
||||
mapptr *Attr
|
||||
)
|
||||
|
||||
// ValueKind is the kind of a [Value].
|
||||
type ValueKind int
|
||||
|
||||
// ValueKind values.
|
||||
const (
|
||||
ValueKindEmpty ValueKind = iota
|
||||
ValueKindBool
|
||||
ValueKindFloat64
|
||||
ValueKindInt64
|
||||
ValueKindString
|
||||
ValueKindBytes
|
||||
ValueKindSlice
|
||||
ValueKindMap
|
||||
)
|
||||
|
||||
var valueKindStrings = []string{
|
||||
"Empty",
|
||||
"Bool",
|
||||
"Float64",
|
||||
"Int64",
|
||||
"String",
|
||||
"Bytes",
|
||||
"Slice",
|
||||
"Map",
|
||||
}
|
||||
|
||||
func (k ValueKind) String() string {
|
||||
if k >= 0 && int(k) < len(valueKindStrings) {
|
||||
return valueKindStrings[k]
|
||||
}
|
||||
return "<unknown telemetry.ValueKind>"
|
||||
}
|
||||
|
||||
// StringValue returns a new [Value] for a string.
|
||||
func StringValue(v string) Value {
|
||||
return Value{
|
||||
num: uint64(len(v)),
|
||||
any: stringptr(unsafe.StringData(v)),
|
||||
}
|
||||
}
|
||||
|
||||
// IntValue returns a [Value] for an int.
|
||||
func IntValue(v int) Value { return Int64Value(int64(v)) }
|
||||
|
||||
// Int64Value returns a [Value] for an int64.
|
||||
func Int64Value(v int64) Value {
|
||||
return Value{
|
||||
num: uint64(v), // nolint: gosec // Store raw bytes.
|
||||
any: ValueKindInt64,
|
||||
}
|
||||
}
|
||||
|
||||
// Float64Value returns a [Value] for a float64.
|
||||
func Float64Value(v float64) Value {
|
||||
return Value{num: math.Float64bits(v), any: ValueKindFloat64}
|
||||
}
|
||||
|
||||
// BoolValue returns a [Value] for a bool.
|
||||
func BoolValue(v bool) Value { //nolint:revive // Not a control flag.
|
||||
var n uint64
|
||||
if v {
|
||||
n = 1
|
||||
}
|
||||
return Value{num: n, any: ValueKindBool}
|
||||
}
|
||||
|
||||
// BytesValue returns a [Value] for a byte slice. The passed slice must not be
|
||||
// changed after it is passed.
|
||||
func BytesValue(v []byte) Value {
|
||||
return Value{
|
||||
num: uint64(len(v)),
|
||||
any: bytesptr(unsafe.SliceData(v)),
|
||||
}
|
||||
}
|
||||
|
||||
// SliceValue returns a [Value] for a slice of [Value]. The passed slice must
|
||||
// not be changed after it is passed.
|
||||
func SliceValue(vs ...Value) Value {
|
||||
return Value{
|
||||
num: uint64(len(vs)),
|
||||
any: sliceptr(unsafe.SliceData(vs)),
|
||||
}
|
||||
}
|
||||
|
||||
// MapValue returns a new [Value] for a slice of key-value pairs. The passed
|
||||
// slice must not be changed after it is passed.
|
||||
func MapValue(kvs ...Attr) Value {
|
||||
return Value{
|
||||
num: uint64(len(kvs)),
|
||||
any: mapptr(unsafe.SliceData(kvs)),
|
||||
}
|
||||
}
|
||||
|
||||
// AsString returns the value held by v as a string.
|
||||
func (v Value) AsString() string {
|
||||
if sp, ok := v.any.(stringptr); ok {
|
||||
return unsafe.String(sp, v.num)
|
||||
}
|
||||
// TODO: error handle
|
||||
return ""
|
||||
}
|
||||
|
||||
// asString returns the value held by v as a string. It will panic if the Value
|
||||
// is not KindString.
|
||||
func (v Value) asString() string {
|
||||
return unsafe.String(v.any.(stringptr), v.num)
|
||||
}
|
||||
|
||||
// AsInt64 returns the value held by v as an int64.
|
||||
func (v Value) AsInt64() int64 {
|
||||
if v.Kind() != ValueKindInt64 {
|
||||
// TODO: error handle
|
||||
return 0
|
||||
}
|
||||
return v.asInt64()
|
||||
}
|
||||
|
||||
// asInt64 returns the value held by v as an int64. If v is not of KindInt64,
|
||||
// this will return garbage.
|
||||
func (v Value) asInt64() int64 {
|
||||
// Assumes v.num was a valid int64 (overflow not checked).
|
||||
return int64(v.num) // nolint: gosec
|
||||
}
|
||||
|
||||
// AsBool returns the value held by v as a bool.
|
||||
func (v Value) AsBool() bool {
|
||||
if v.Kind() != ValueKindBool {
|
||||
// TODO: error handle
|
||||
return false
|
||||
}
|
||||
return v.asBool()
|
||||
}
|
||||
|
||||
// asBool returns the value held by v as a bool. If v is not of KindBool, this
|
||||
// will return garbage.
|
||||
func (v Value) asBool() bool { return v.num == 1 }
|
||||
|
||||
// AsFloat64 returns the value held by v as a float64.
|
||||
func (v Value) AsFloat64() float64 {
|
||||
if v.Kind() != ValueKindFloat64 {
|
||||
// TODO: error handle
|
||||
return 0
|
||||
}
|
||||
return v.asFloat64()
|
||||
}
|
||||
|
||||
// asFloat64 returns the value held by v as a float64. If v is not of
|
||||
// KindFloat64, this will return garbage.
|
||||
func (v Value) asFloat64() float64 { return math.Float64frombits(v.num) }
|
||||
|
||||
// AsBytes returns the value held by v as a []byte.
|
||||
func (v Value) AsBytes() []byte {
|
||||
if sp, ok := v.any.(bytesptr); ok {
|
||||
return unsafe.Slice((*byte)(sp), v.num)
|
||||
}
|
||||
// TODO: error handle
|
||||
return nil
|
||||
}
|
||||
|
||||
// asBytes returns the value held by v as a []byte. It will panic if the Value
|
||||
// is not KindBytes.
|
||||
func (v Value) asBytes() []byte {
|
||||
return unsafe.Slice((*byte)(v.any.(bytesptr)), v.num)
|
||||
}
|
||||
|
||||
// AsSlice returns the value held by v as a []Value.
|
||||
func (v Value) AsSlice() []Value {
|
||||
if sp, ok := v.any.(sliceptr); ok {
|
||||
return unsafe.Slice((*Value)(sp), v.num)
|
||||
}
|
||||
// TODO: error handle
|
||||
return nil
|
||||
}
|
||||
|
||||
// asSlice returns the value held by v as a []Value. It will panic if the Value
|
||||
// is not KindSlice.
|
||||
func (v Value) asSlice() []Value {
|
||||
return unsafe.Slice((*Value)(v.any.(sliceptr)), v.num)
|
||||
}
|
||||
|
||||
// AsMap returns the value held by v as a []Attr.
|
||||
func (v Value) AsMap() []Attr {
|
||||
if sp, ok := v.any.(mapptr); ok {
|
||||
return unsafe.Slice((*Attr)(sp), v.num)
|
||||
}
|
||||
// TODO: error handle
|
||||
return nil
|
||||
}
|
||||
|
||||
// asMap returns the value held by v as a []Attr. It will panic if the
|
||||
// Value is not KindMap.
|
||||
func (v Value) asMap() []Attr {
|
||||
return unsafe.Slice((*Attr)(v.any.(mapptr)), v.num)
|
||||
}
|
||||
|
||||
// Kind returns the Kind of v.
|
||||
func (v Value) Kind() ValueKind {
|
||||
switch x := v.any.(type) {
|
||||
case ValueKind:
|
||||
return x
|
||||
case stringptr:
|
||||
return ValueKindString
|
||||
case bytesptr:
|
||||
return ValueKindBytes
|
||||
case sliceptr:
|
||||
return ValueKindSlice
|
||||
case mapptr:
|
||||
return ValueKindMap
|
||||
default:
|
||||
return ValueKindEmpty
|
||||
}
|
||||
}
|
||||
|
||||
// Empty reports whether v does not hold any value.
|
||||
func (v Value) Empty() bool { return v.Kind() == ValueKindEmpty }
|
||||
|
||||
// Equal reports whether v is equal to w.
|
||||
func (v Value) Equal(w Value) bool {
|
||||
k1 := v.Kind()
|
||||
k2 := w.Kind()
|
||||
if k1 != k2 {
|
||||
return false
|
||||
}
|
||||
switch k1 {
|
||||
case ValueKindInt64, ValueKindBool:
|
||||
return v.num == w.num
|
||||
case ValueKindString:
|
||||
return v.asString() == w.asString()
|
||||
case ValueKindFloat64:
|
||||
return v.asFloat64() == w.asFloat64()
|
||||
case ValueKindSlice:
|
||||
return slices.EqualFunc(v.asSlice(), w.asSlice(), Value.Equal)
|
||||
case ValueKindMap:
|
||||
sv := sortMap(v.asMap())
|
||||
sw := sortMap(w.asMap())
|
||||
return slices.EqualFunc(sv, sw, Attr.Equal)
|
||||
case ValueKindBytes:
|
||||
return bytes.Equal(v.asBytes(), w.asBytes())
|
||||
case ValueKindEmpty:
|
||||
return true
|
||||
default:
|
||||
// TODO: error handle
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func sortMap(m []Attr) []Attr {
|
||||
sm := make([]Attr, len(m))
|
||||
copy(sm, m)
|
||||
slices.SortFunc(sm, func(a, b Attr) int {
|
||||
return cmp.Compare(a.Key, b.Key)
|
||||
})
|
||||
|
||||
return sm
|
||||
}
|
||||
|
||||
// String returns Value's value as a string, formatted like [fmt.Sprint].
|
||||
//
|
||||
// The returned string is meant for debugging;
|
||||
// the string representation is not stable.
|
||||
func (v Value) String() string {
|
||||
switch v.Kind() {
|
||||
case ValueKindString:
|
||||
return v.asString()
|
||||
case ValueKindInt64:
|
||||
// Assumes v.num was a valid int64 (overflow not checked).
|
||||
return strconv.FormatInt(int64(v.num), 10) // nolint: gosec
|
||||
case ValueKindFloat64:
|
||||
return strconv.FormatFloat(v.asFloat64(), 'g', -1, 64)
|
||||
case ValueKindBool:
|
||||
return strconv.FormatBool(v.asBool())
|
||||
case ValueKindBytes:
|
||||
return string(v.asBytes())
|
||||
case ValueKindMap:
|
||||
return fmt.Sprint(v.asMap())
|
||||
case ValueKindSlice:
|
||||
return fmt.Sprint(v.asSlice())
|
||||
case ValueKindEmpty:
|
||||
return "<nil>"
|
||||
default:
|
||||
// Try to handle this as gracefully as possible.
|
||||
//
|
||||
// Don't panic here. The goal here is to have developers find this
|
||||
// first if a slog.Kind is is not handled. It is
|
||||
// preferable to have user's open issue asking why their attributes
|
||||
// have a "unhandled: " prefix than say that their code is panicking.
|
||||
return fmt.Sprintf("<unhandled telemetry.ValueKind: %s>", v.Kind())
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalJSON encodes v into OTLP formatted JSON.
|
||||
func (v *Value) MarshalJSON() ([]byte, error) {
|
||||
switch v.Kind() {
|
||||
case ValueKindString:
|
||||
return json.Marshal(struct {
|
||||
Value string `json:"stringValue"`
|
||||
}{v.asString()})
|
||||
case ValueKindInt64:
|
||||
return json.Marshal(struct {
|
||||
Value string `json:"intValue"`
|
||||
}{strconv.FormatInt(int64(v.num), 10)}) // nolint: gosec // From raw bytes.
|
||||
case ValueKindFloat64:
|
||||
return json.Marshal(struct {
|
||||
Value float64 `json:"doubleValue"`
|
||||
}{v.asFloat64()})
|
||||
case ValueKindBool:
|
||||
return json.Marshal(struct {
|
||||
Value bool `json:"boolValue"`
|
||||
}{v.asBool()})
|
||||
case ValueKindBytes:
|
||||
return json.Marshal(struct {
|
||||
Value []byte `json:"bytesValue"`
|
||||
}{v.asBytes()})
|
||||
case ValueKindMap:
|
||||
return json.Marshal(struct {
|
||||
Value struct {
|
||||
Values []Attr `json:"values"`
|
||||
} `json:"kvlistValue"`
|
||||
}{struct {
|
||||
Values []Attr `json:"values"`
|
||||
}{v.asMap()}})
|
||||
case ValueKindSlice:
|
||||
return json.Marshal(struct {
|
||||
Value struct {
|
||||
Values []Value `json:"values"`
|
||||
} `json:"arrayValue"`
|
||||
}{struct {
|
||||
Values []Value `json:"values"`
|
||||
}{v.asSlice()}})
|
||||
case ValueKindEmpty:
|
||||
return nil, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown Value kind: %s", v.Kind().String())
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalJSON decodes the OTLP formatted JSON contained in data into v.
|
||||
func (v *Value) UnmarshalJSON(data []byte) error {
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
|
||||
t, err := decoder.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t != json.Delim('{') {
|
||||
return errors.New("invalid Value type")
|
||||
}
|
||||
|
||||
for decoder.More() {
|
||||
keyIface, err := decoder.Token()
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
// Empty.
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
key, ok := keyIface.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("invalid Value key: %#v", keyIface)
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "stringValue", "string_value":
|
||||
var val string
|
||||
err = decoder.Decode(&val)
|
||||
*v = StringValue(val)
|
||||
case "boolValue", "bool_value":
|
||||
var val bool
|
||||
err = decoder.Decode(&val)
|
||||
*v = BoolValue(val)
|
||||
case "intValue", "int_value":
|
||||
var val protoInt64
|
||||
err = decoder.Decode(&val)
|
||||
*v = Int64Value(val.Int64())
|
||||
case "doubleValue", "double_value":
|
||||
var val float64
|
||||
err = decoder.Decode(&val)
|
||||
*v = Float64Value(val)
|
||||
case "bytesValue", "bytes_value":
|
||||
var val64 string
|
||||
if err := decoder.Decode(&val64); err != nil {
|
||||
return err
|
||||
}
|
||||
var val []byte
|
||||
val, err = base64.StdEncoding.DecodeString(val64)
|
||||
*v = BytesValue(val)
|
||||
case "arrayValue", "array_value":
|
||||
var val struct{ Values []Value }
|
||||
err = decoder.Decode(&val)
|
||||
*v = SliceValue(val.Values...)
|
||||
case "kvlistValue", "kvlist_value":
|
||||
var val struct{ Values []Attr }
|
||||
err = decoder.Decode(&val)
|
||||
*v = MapValue(val.Values...)
|
||||
default:
|
||||
// Skip unknown.
|
||||
continue
|
||||
}
|
||||
// Use first valid. Ignore the rest.
|
||||
return err
|
||||
}
|
||||
|
||||
// Only unknown fields. Return nil without unmarshaling any value.
|
||||
return nil
|
||||
}
|
||||
16
vendor/go.opentelemetry.io/otel/trace/nonrecording.go
generated
vendored
Normal file
16
vendor/go.opentelemetry.io/otel/trace/nonrecording.go
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
// nonRecordingSpan is a minimal implementation of a Span that wraps a
|
||||
// SpanContext. It performs no operations other than to return the wrapped
|
||||
// SpanContext.
|
||||
type nonRecordingSpan struct {
|
||||
noopSpan
|
||||
|
||||
sc SpanContext
|
||||
}
|
||||
|
||||
// SpanContext returns the wrapped SpanContext.
|
||||
func (s nonRecordingSpan) SpanContext() SpanContext { return s.sc }
|
||||
105
vendor/go.opentelemetry.io/otel/trace/noop.go
generated
vendored
Normal file
105
vendor/go.opentelemetry.io/otel/trace/noop.go
generated
vendored
Normal file
@@ -0,0 +1,105 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace/embedded"
|
||||
)
|
||||
|
||||
// NewNoopTracerProvider returns an implementation of TracerProvider that
|
||||
// performs no operations. The Tracer and Spans created from the returned
|
||||
// TracerProvider also perform no operations.
|
||||
//
|
||||
// Deprecated: Use [go.opentelemetry.io/otel/trace/noop.NewTracerProvider]
|
||||
// instead.
|
||||
func NewNoopTracerProvider() TracerProvider {
|
||||
return noopTracerProvider{}
|
||||
}
|
||||
|
||||
type noopTracerProvider struct{ embedded.TracerProvider }
|
||||
|
||||
var _ TracerProvider = noopTracerProvider{}
|
||||
|
||||
// Tracer returns noop implementation of Tracer.
|
||||
func (noopTracerProvider) Tracer(string, ...TracerOption) Tracer {
|
||||
return noopTracer{}
|
||||
}
|
||||
|
||||
// noopTracer is an implementation of Tracer that performs no operations.
|
||||
type noopTracer struct{ embedded.Tracer }
|
||||
|
||||
var _ Tracer = noopTracer{}
|
||||
|
||||
// Start carries forward a non-recording Span, if one is present in the context, otherwise it
|
||||
// creates a no-op Span.
|
||||
func (noopTracer) Start(ctx context.Context, _ string, _ ...SpanStartOption) (context.Context, Span) {
|
||||
span := SpanFromContext(ctx)
|
||||
if _, ok := span.(nonRecordingSpan); !ok {
|
||||
// span is likely already a noopSpan, but let's be sure
|
||||
span = noopSpanInstance
|
||||
}
|
||||
return ContextWithSpan(ctx, span), span
|
||||
}
|
||||
|
||||
// noopSpan is an implementation of Span that performs no operations.
|
||||
type noopSpan struct{ embedded.Span }
|
||||
|
||||
var noopSpanInstance Span = noopSpan{}
|
||||
|
||||
// SpanContext returns an empty span context.
|
||||
func (noopSpan) SpanContext() SpanContext { return SpanContext{} }
|
||||
|
||||
// IsRecording always returns false.
|
||||
func (noopSpan) IsRecording() bool { return false }
|
||||
|
||||
// SetStatus does nothing.
|
||||
func (noopSpan) SetStatus(codes.Code, string) {}
|
||||
|
||||
// SetError does nothing.
|
||||
func (noopSpan) SetError(bool) {}
|
||||
|
||||
// SetAttributes does nothing.
|
||||
func (noopSpan) SetAttributes(...attribute.KeyValue) {}
|
||||
|
||||
// End does nothing.
|
||||
func (noopSpan) End(...SpanEndOption) {}
|
||||
|
||||
// RecordError does nothing.
|
||||
func (noopSpan) RecordError(error, ...EventOption) {}
|
||||
|
||||
// AddEvent does nothing.
|
||||
func (noopSpan) AddEvent(string, ...EventOption) {}
|
||||
|
||||
// AddLink does nothing.
|
||||
func (noopSpan) AddLink(Link) {}
|
||||
|
||||
// SetName does nothing.
|
||||
func (noopSpan) SetName(string) {}
|
||||
|
||||
// TracerProvider returns a no-op TracerProvider.
|
||||
func (s noopSpan) TracerProvider() TracerProvider {
|
||||
return s.tracerProvider(autoInstEnabled)
|
||||
}
|
||||
|
||||
// autoInstEnabled defines if the auto-instrumentation SDK is enabled.
|
||||
//
|
||||
// The auto-instrumentation is expected to overwrite this value to true when it
|
||||
// attaches to the process.
|
||||
var autoInstEnabled = new(bool)
|
||||
|
||||
// tracerProvider return a noopTracerProvider if autoEnabled is false,
|
||||
// otherwise it will return a TracerProvider from the sdk package used in
|
||||
// auto-instrumentation.
|
||||
//
|
||||
//go:noinline
|
||||
func (noopSpan) tracerProvider(autoEnabled *bool) TracerProvider {
|
||||
if *autoEnabled {
|
||||
return newAutoTracerProvider()
|
||||
}
|
||||
return noopTracerProvider{}
|
||||
}
|
||||
3
vendor/go.opentelemetry.io/otel/trace/noop/README.md
generated
vendored
Normal file
3
vendor/go.opentelemetry.io/otel/trace/noop/README.md
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
# Trace Noop
|
||||
|
||||
[](https://pkg.go.dev/go.opentelemetry.io/otel/trace/noop)
|
||||
112
vendor/go.opentelemetry.io/otel/trace/noop/noop.go
generated
vendored
Normal file
112
vendor/go.opentelemetry.io/otel/trace/noop/noop.go
generated
vendored
Normal file
@@ -0,0 +1,112 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package noop provides an implementation of the OpenTelemetry trace API that
|
||||
// produces no telemetry and minimizes used computation resources.
|
||||
//
|
||||
// Using this package to implement the OpenTelemetry trace API will effectively
|
||||
// disable OpenTelemetry.
|
||||
//
|
||||
// This implementation can be embedded in other implementations of the
|
||||
// OpenTelemetry trace API. Doing so will mean the implementation defaults to
|
||||
// no operation for methods it does not implement.
|
||||
package noop // import "go.opentelemetry.io/otel/trace/noop"
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"go.opentelemetry.io/otel/trace/embedded"
|
||||
)
|
||||
|
||||
var (
|
||||
// Compile-time check this implements the OpenTelemetry API.
|
||||
|
||||
_ trace.TracerProvider = TracerProvider{}
|
||||
_ trace.Tracer = Tracer{}
|
||||
_ trace.Span = Span{}
|
||||
)
|
||||
|
||||
// TracerProvider is an OpenTelemetry No-Op TracerProvider.
|
||||
type TracerProvider struct{ embedded.TracerProvider }
|
||||
|
||||
// NewTracerProvider returns a TracerProvider that does not record any telemetry.
|
||||
func NewTracerProvider() TracerProvider {
|
||||
return TracerProvider{}
|
||||
}
|
||||
|
||||
// Tracer returns an OpenTelemetry Tracer that does not record any telemetry.
|
||||
func (TracerProvider) Tracer(string, ...trace.TracerOption) trace.Tracer {
|
||||
return Tracer{}
|
||||
}
|
||||
|
||||
// Tracer is an OpenTelemetry No-Op Tracer.
|
||||
type Tracer struct{ embedded.Tracer }
|
||||
|
||||
// Start creates a span. The created span will be set in a child context of ctx
|
||||
// and returned with the span.
|
||||
//
|
||||
// If ctx contains a span context, the returned span will also contain that
|
||||
// span context. If the span context in ctx is for a non-recording span, that
|
||||
// span instance will be returned directly.
|
||||
func (Tracer) Start(ctx context.Context, _ string, _ ...trace.SpanStartOption) (context.Context, trace.Span) {
|
||||
span := trace.SpanFromContext(ctx)
|
||||
|
||||
// If the parent context contains a non-zero span context, that span
|
||||
// context needs to be returned as a non-recording span
|
||||
// (https://github.com/open-telemetry/opentelemetry-specification/blob/3a1dde966a4ce87cce5adf464359fe369741bbea/specification/trace/api.md#behavior-of-the-api-in-the-absence-of-an-installed-sdk).
|
||||
var zeroSC trace.SpanContext
|
||||
if sc := span.SpanContext(); !sc.Equal(zeroSC) {
|
||||
if !span.IsRecording() {
|
||||
// If the span is not recording return it directly.
|
||||
return ctx, span
|
||||
}
|
||||
// Otherwise, return the span context needs in a non-recording span.
|
||||
span = Span{sc: sc}
|
||||
} else {
|
||||
// No parent, return a No-Op span with an empty span context.
|
||||
span = noopSpanInstance
|
||||
}
|
||||
return trace.ContextWithSpan(ctx, span), span
|
||||
}
|
||||
|
||||
var noopSpanInstance trace.Span = Span{}
|
||||
|
||||
// Span is an OpenTelemetry No-Op Span.
|
||||
type Span struct {
|
||||
embedded.Span
|
||||
|
||||
sc trace.SpanContext
|
||||
}
|
||||
|
||||
// SpanContext returns an empty span context.
|
||||
func (s Span) SpanContext() trace.SpanContext { return s.sc }
|
||||
|
||||
// IsRecording always returns false.
|
||||
func (Span) IsRecording() bool { return false }
|
||||
|
||||
// SetStatus does nothing.
|
||||
func (Span) SetStatus(codes.Code, string) {}
|
||||
|
||||
// SetAttributes does nothing.
|
||||
func (Span) SetAttributes(...attribute.KeyValue) {}
|
||||
|
||||
// End does nothing.
|
||||
func (Span) End(...trace.SpanEndOption) {}
|
||||
|
||||
// RecordError does nothing.
|
||||
func (Span) RecordError(error, ...trace.EventOption) {}
|
||||
|
||||
// AddEvent does nothing.
|
||||
func (Span) AddEvent(string, ...trace.EventOption) {}
|
||||
|
||||
// AddLink does nothing.
|
||||
func (Span) AddLink(trace.Link) {}
|
||||
|
||||
// SetName does nothing.
|
||||
func (Span) SetName(string) {}
|
||||
|
||||
// TracerProvider returns a No-Op TracerProvider.
|
||||
func (Span) TracerProvider() trace.TracerProvider { return TracerProvider{} }
|
||||
59
vendor/go.opentelemetry.io/otel/trace/provider.go
generated
vendored
Normal file
59
vendor/go.opentelemetry.io/otel/trace/provider.go
generated
vendored
Normal file
@@ -0,0 +1,59 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
import "go.opentelemetry.io/otel/trace/embedded"
|
||||
|
||||
// TracerProvider provides Tracers that are used by instrumentation code to
|
||||
// trace computational workflows.
|
||||
//
|
||||
// A TracerProvider is the collection destination of all Spans from Tracers it
|
||||
// provides, it represents a unique telemetry collection pipeline. How that
|
||||
// pipeline is defined, meaning how those Spans are collected, processed, and
|
||||
// where they are exported, depends on its implementation. Instrumentation
|
||||
// authors do not need to define this implementation, rather just use the
|
||||
// provided Tracers to instrument code.
|
||||
//
|
||||
// Commonly, instrumentation code will accept a TracerProvider implementation
|
||||
// at runtime from its users or it can simply use the globally registered one
|
||||
// (see https://pkg.go.dev/go.opentelemetry.io/otel#GetTracerProvider).
|
||||
//
|
||||
// Warning: Methods may be added to this interface in minor releases. See
|
||||
// package documentation on API implementation for information on how to set
|
||||
// default behavior for unimplemented methods.
|
||||
type TracerProvider interface {
|
||||
// Users of the interface can ignore this. This embedded type is only used
|
||||
// by implementations of this interface. See the "API Implementations"
|
||||
// section of the package documentation for more information.
|
||||
embedded.TracerProvider
|
||||
|
||||
// Tracer returns a unique Tracer scoped to be used by instrumentation code
|
||||
// to trace computational workflows. The scope and identity of that
|
||||
// instrumentation code is uniquely defined by the name and options passed.
|
||||
//
|
||||
// The passed name needs to uniquely identify instrumentation code.
|
||||
// Therefore, it is recommended that name is the Go package name of the
|
||||
// library providing instrumentation (note: not the code being
|
||||
// instrumented). Instrumentation libraries can have multiple versions,
|
||||
// therefore, the WithInstrumentationVersion option should be used to
|
||||
// distinguish these different codebases. Additionally, instrumentation
|
||||
// libraries may sometimes use traces to communicate different domains of
|
||||
// workflow data (i.e. using spans to communicate workflow events only). If
|
||||
// this is the case, the WithScopeAttributes option should be used to
|
||||
// uniquely identify Tracers that handle the different domains of workflow
|
||||
// data.
|
||||
//
|
||||
// If the same name and options are passed multiple times, the same Tracer
|
||||
// will be returned (it is up to the implementation if this will be the
|
||||
// same underlying instance of that Tracer or not). It is not necessary to
|
||||
// call this multiple times with the same name and options to get an
|
||||
// up-to-date Tracer. All implementations will ensure any TracerProvider
|
||||
// configuration changes are propagated to all provided Tracers.
|
||||
//
|
||||
// If name is empty, then an implementation defined default name will be
|
||||
// used instead.
|
||||
//
|
||||
// This method is safe to call concurrently.
|
||||
Tracer(name string, options ...TracerOption) Tracer
|
||||
}
|
||||
181
vendor/go.opentelemetry.io/otel/trace/span.go
generated
vendored
Normal file
181
vendor/go.opentelemetry.io/otel/trace/span.go
generated
vendored
Normal file
@@ -0,0 +1,181 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace/embedded"
|
||||
)
|
||||
|
||||
// Span is the individual component of a trace. It represents a single named
|
||||
// and timed operation of a workflow that is traced. A Tracer is used to
|
||||
// create a Span and it is then up to the operation the Span represents to
|
||||
// properly end the Span when the operation itself ends.
|
||||
//
|
||||
// Warning: Methods may be added to this interface in minor releases. See
|
||||
// package documentation on API implementation for information on how to set
|
||||
// default behavior for unimplemented methods.
|
||||
type Span interface {
|
||||
// Users of the interface can ignore this. This embedded type is only used
|
||||
// by implementations of this interface. See the "API Implementations"
|
||||
// section of the package documentation for more information.
|
||||
embedded.Span
|
||||
|
||||
// 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 ...SpanEndOption)
|
||||
|
||||
// AddEvent adds an event with the provided name and options.
|
||||
AddEvent(name string, options ...EventOption)
|
||||
|
||||
// AddLink adds a link.
|
||||
// Adding links at span creation using WithLinks is preferred to calling AddLink
|
||||
// later, for contexts that are available during span creation, because head
|
||||
// sampling decisions can only consider information present during span creation.
|
||||
AddLink(link Link)
|
||||
|
||||
// IsRecording returns the recording state of the Span. It will return
|
||||
// true if the Span is active and events can be recorded.
|
||||
IsRecording() bool
|
||||
|
||||
// RecordError will record err as an exception span event for this span. An
|
||||
// additional call to SetStatus is required if the Status of the Span should
|
||||
// be set to Error, as this method does not change the Span status. If this
|
||||
// span is not being recorded or err is nil then this method does nothing.
|
||||
RecordError(err error, options ...EventOption)
|
||||
|
||||
// SpanContext returns the SpanContext of the Span. The returned SpanContext
|
||||
// is usable even after the End method has been called for the Span.
|
||||
SpanContext() SpanContext
|
||||
|
||||
// SetStatus sets the status of the Span in the form of a code and a
|
||||
// description, provided the status hasn't already been set to a higher
|
||||
// value before (OK > Error > Unset). The description is only included in a
|
||||
// status when the code is for an error.
|
||||
SetStatus(code codes.Code, description string)
|
||||
|
||||
// SetName sets the Span name.
|
||||
SetName(name string)
|
||||
|
||||
// SetAttributes sets kv as attributes of the Span. If a key from kv
|
||||
// already exists for an attribute of the Span it will be overwritten with
|
||||
// the value contained in kv.
|
||||
//
|
||||
// Note that adding attributes at span creation using [WithAttributes] is preferred
|
||||
// to calling SetAttribute later, as samplers can only consider information
|
||||
// already present during span creation.
|
||||
SetAttributes(kv ...attribute.KeyValue)
|
||||
|
||||
// TracerProvider returns a TracerProvider that can be used to generate
|
||||
// additional Spans on the same telemetry pipeline as the current Span.
|
||||
TracerProvider() TracerProvider
|
||||
}
|
||||
|
||||
// Link is the relationship between two Spans. The relationship can be within
|
||||
// the same Trace or across different Traces.
|
||||
//
|
||||
// For example, a Link is used in the following situations:
|
||||
//
|
||||
// 1. Batch Processing: A batch of operations may contain operations
|
||||
// associated with one or more traces/spans. Since there can only be one
|
||||
// parent SpanContext, a Link is used to keep reference to the
|
||||
// SpanContext of all operations in the batch.
|
||||
// 2. Public Endpoint: A SpanContext for an in incoming client request on a
|
||||
// public endpoint should be considered untrusted. In such a case, a new
|
||||
// trace with its own identity and sampling decision needs to be created,
|
||||
// but this new trace needs to be related to the original trace in some
|
||||
// form. A Link is used to keep reference to the original SpanContext and
|
||||
// track the relationship.
|
||||
type Link struct {
|
||||
// SpanContext of the linked Span.
|
||||
SpanContext SpanContext
|
||||
|
||||
// Attributes describe the aspects of the link.
|
||||
Attributes []attribute.KeyValue
|
||||
}
|
||||
|
||||
// LinkFromContext returns a link encapsulating the SpanContext in the provided
|
||||
// ctx.
|
||||
func LinkFromContext(ctx context.Context, attrs ...attribute.KeyValue) Link {
|
||||
return Link{
|
||||
SpanContext: SpanContextFromContext(ctx),
|
||||
Attributes: attrs,
|
||||
}
|
||||
}
|
||||
|
||||
// SpanKind is the role a Span plays in a Trace.
|
||||
type SpanKind int
|
||||
|
||||
// As a convenience, these match the proto definition, see
|
||||
// https://github.com/open-telemetry/opentelemetry-proto/blob/30d237e1ff3ab7aa50e0922b5bebdd93505090af/opentelemetry/proto/trace/v1/trace.proto#L101-L129
|
||||
//
|
||||
// The unspecified value is not a valid `SpanKind`. Use `ValidateSpanKind()`
|
||||
// to coerce a span kind to a valid value.
|
||||
const (
|
||||
// SpanKindUnspecified is an unspecified SpanKind and is not a valid
|
||||
// SpanKind. SpanKindUnspecified should be replaced with SpanKindInternal
|
||||
// if it is received.
|
||||
SpanKindUnspecified SpanKind = 0
|
||||
// SpanKindInternal is a SpanKind for a Span that represents an internal
|
||||
// operation within an application.
|
||||
SpanKindInternal SpanKind = 1
|
||||
// SpanKindServer is a SpanKind for a Span that represents the operation
|
||||
// of handling a request from a client.
|
||||
SpanKindServer SpanKind = 2
|
||||
// SpanKindClient is a SpanKind for a Span that represents the operation
|
||||
// of client making a request to a server.
|
||||
SpanKindClient SpanKind = 3
|
||||
// SpanKindProducer is a SpanKind for a Span that represents the operation
|
||||
// of a producer sending a message to a message broker. Unlike
|
||||
// SpanKindClient and SpanKindServer, there is often no direct
|
||||
// relationship between this kind of Span and a SpanKindConsumer kind. A
|
||||
// SpanKindProducer Span will end once the message is accepted by the
|
||||
// message broker which might not overlap with the processing of that
|
||||
// message.
|
||||
SpanKindProducer SpanKind = 4
|
||||
// SpanKindConsumer is a SpanKind for a Span that represents the operation
|
||||
// of a consumer receiving a message from a message broker. Like
|
||||
// SpanKindProducer Spans, there is often no direct relationship between
|
||||
// this Span and the Span that produced the message.
|
||||
SpanKindConsumer SpanKind = 5
|
||||
)
|
||||
|
||||
// ValidateSpanKind returns a valid span kind value. This will coerce
|
||||
// invalid values into the default value, SpanKindInternal.
|
||||
func ValidateSpanKind(spanKind SpanKind) SpanKind {
|
||||
switch spanKind {
|
||||
case SpanKindInternal,
|
||||
SpanKindServer,
|
||||
SpanKindClient,
|
||||
SpanKindProducer,
|
||||
SpanKindConsumer:
|
||||
// valid
|
||||
return spanKind
|
||||
default:
|
||||
return SpanKindInternal
|
||||
}
|
||||
}
|
||||
|
||||
// String returns the specified name of the SpanKind in lower-case.
|
||||
func (sk SpanKind) String() string {
|
||||
switch sk {
|
||||
case SpanKindInternal:
|
||||
return "internal"
|
||||
case SpanKindServer:
|
||||
return "server"
|
||||
case SpanKindClient:
|
||||
return "client"
|
||||
case SpanKindProducer:
|
||||
return "producer"
|
||||
case SpanKindConsumer:
|
||||
return "consumer"
|
||||
default:
|
||||
return "unspecified"
|
||||
}
|
||||
}
|
||||
365
vendor/go.opentelemetry.io/otel/trace/trace.go
generated
vendored
Normal file
365
vendor/go.opentelemetry.io/otel/trace/trace.go
generated
vendored
Normal file
@@ -0,0 +1,365 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
const (
|
||||
// FlagsSampled is a bitmask with the sampled bit set. A SpanContext
|
||||
// with the sampling bit set means the span is sampled.
|
||||
FlagsSampled = TraceFlags(0x01)
|
||||
|
||||
errInvalidHexID errorConst = "trace-id and span-id can only contain [0-9a-f] characters, all lowercase"
|
||||
|
||||
errInvalidTraceIDLength errorConst = "hex encoded trace-id must have length equals to 32"
|
||||
errNilTraceID errorConst = "trace-id can't be all zero"
|
||||
|
||||
errInvalidSpanIDLength errorConst = "hex encoded span-id must have length equals to 16"
|
||||
errNilSpanID errorConst = "span-id can't be all zero"
|
||||
)
|
||||
|
||||
type errorConst string
|
||||
|
||||
func (e errorConst) Error() string {
|
||||
return string(e)
|
||||
}
|
||||
|
||||
// TraceID is a unique identity of a trace.
|
||||
// nolint:revive // revive complains about stutter of `trace.TraceID`.
|
||||
type TraceID [16]byte
|
||||
|
||||
var (
|
||||
nilTraceID TraceID
|
||||
_ json.Marshaler = nilTraceID
|
||||
)
|
||||
|
||||
// IsValid reports whether the trace TraceID is valid. A valid trace ID does
|
||||
// not consist of zeros only.
|
||||
func (t TraceID) IsValid() bool {
|
||||
return t != nilTraceID
|
||||
}
|
||||
|
||||
// MarshalJSON implements a custom marshal function to encode TraceID
|
||||
// as a hex string.
|
||||
func (t TraceID) MarshalJSON() ([]byte, error) {
|
||||
b := [32 + 2]byte{0: '"', 33: '"'}
|
||||
h := t.hexBytes()
|
||||
copy(b[1:], h[:])
|
||||
return b[:], nil
|
||||
}
|
||||
|
||||
// String returns the hex string representation form of a TraceID.
|
||||
func (t TraceID) String() string {
|
||||
h := t.hexBytes()
|
||||
return string(h[:])
|
||||
}
|
||||
|
||||
// hexBytes returns the hex string representation form of a TraceID.
|
||||
func (t TraceID) hexBytes() [32]byte {
|
||||
return [32]byte{
|
||||
hexLU[t[0x0]>>4], hexLU[t[0x0]&0xf],
|
||||
hexLU[t[0x1]>>4], hexLU[t[0x1]&0xf],
|
||||
hexLU[t[0x2]>>4], hexLU[t[0x2]&0xf],
|
||||
hexLU[t[0x3]>>4], hexLU[t[0x3]&0xf],
|
||||
hexLU[t[0x4]>>4], hexLU[t[0x4]&0xf],
|
||||
hexLU[t[0x5]>>4], hexLU[t[0x5]&0xf],
|
||||
hexLU[t[0x6]>>4], hexLU[t[0x6]&0xf],
|
||||
hexLU[t[0x7]>>4], hexLU[t[0x7]&0xf],
|
||||
hexLU[t[0x8]>>4], hexLU[t[0x8]&0xf],
|
||||
hexLU[t[0x9]>>4], hexLU[t[0x9]&0xf],
|
||||
hexLU[t[0xa]>>4], hexLU[t[0xa]&0xf],
|
||||
hexLU[t[0xb]>>4], hexLU[t[0xb]&0xf],
|
||||
hexLU[t[0xc]>>4], hexLU[t[0xc]&0xf],
|
||||
hexLU[t[0xd]>>4], hexLU[t[0xd]&0xf],
|
||||
hexLU[t[0xe]>>4], hexLU[t[0xe]&0xf],
|
||||
hexLU[t[0xf]>>4], hexLU[t[0xf]&0xf],
|
||||
}
|
||||
}
|
||||
|
||||
// SpanID is a unique identity of a span in a trace.
|
||||
type SpanID [8]byte
|
||||
|
||||
var (
|
||||
nilSpanID SpanID
|
||||
_ json.Marshaler = nilSpanID
|
||||
)
|
||||
|
||||
// IsValid reports whether the SpanID is valid. A valid SpanID does not consist
|
||||
// of zeros only.
|
||||
func (s SpanID) IsValid() bool {
|
||||
return s != nilSpanID
|
||||
}
|
||||
|
||||
// MarshalJSON implements a custom marshal function to encode SpanID
|
||||
// as a hex string.
|
||||
func (s SpanID) MarshalJSON() ([]byte, error) {
|
||||
b := [16 + 2]byte{0: '"', 17: '"'}
|
||||
h := s.hexBytes()
|
||||
copy(b[1:], h[:])
|
||||
return b[:], nil
|
||||
}
|
||||
|
||||
// String returns the hex string representation form of a SpanID.
|
||||
func (s SpanID) String() string {
|
||||
b := s.hexBytes()
|
||||
return string(b[:])
|
||||
}
|
||||
|
||||
func (s SpanID) hexBytes() [16]byte {
|
||||
return [16]byte{
|
||||
hexLU[s[0]>>4], hexLU[s[0]&0xf],
|
||||
hexLU[s[1]>>4], hexLU[s[1]&0xf],
|
||||
hexLU[s[2]>>4], hexLU[s[2]&0xf],
|
||||
hexLU[s[3]>>4], hexLU[s[3]&0xf],
|
||||
hexLU[s[4]>>4], hexLU[s[4]&0xf],
|
||||
hexLU[s[5]>>4], hexLU[s[5]&0xf],
|
||||
hexLU[s[6]>>4], hexLU[s[6]&0xf],
|
||||
hexLU[s[7]>>4], hexLU[s[7]&0xf],
|
||||
}
|
||||
}
|
||||
|
||||
// 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:revive // revive complains about stutter of `trace.TraceIDFromHex`.
|
||||
func TraceIDFromHex(h string) (TraceID, error) {
|
||||
if len(h) != 32 {
|
||||
return [16]byte{}, errInvalidTraceIDLength
|
||||
}
|
||||
var b [16]byte
|
||||
invalidMark := byte(0)
|
||||
for i := 0; i < len(h); i += 4 {
|
||||
b[i/2] = (hexRev[h[i]] << 4) | hexRev[h[i+1]]
|
||||
b[i/2+1] = (hexRev[h[i+2]] << 4) | hexRev[h[i+3]]
|
||||
invalidMark |= hexRev[h[i]] | hexRev[h[i+1]] | hexRev[h[i+2]] | hexRev[h[i+3]]
|
||||
}
|
||||
// If the upper 4 bits of any byte are not zero, there was an invalid hex
|
||||
// character since invalid hex characters are 0xff in hexRev.
|
||||
if invalidMark&0xf0 != 0 {
|
||||
return [16]byte{}, errInvalidHexID
|
||||
}
|
||||
// If we didn't set any bits, then h was all zeros.
|
||||
if invalidMark == 0 {
|
||||
return [16]byte{}, errNilTraceID
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// SpanIDFromHex returns a SpanID from a hex string if it is compliant
|
||||
// with the w3c trace-context specification.
|
||||
// See more at https://www.w3.org/TR/trace-context/#parent-id
|
||||
func SpanIDFromHex(h string) (SpanID, error) {
|
||||
if len(h) != 16 {
|
||||
return [8]byte{}, errInvalidSpanIDLength
|
||||
}
|
||||
var b [8]byte
|
||||
invalidMark := byte(0)
|
||||
for i := 0; i < len(h); i += 4 {
|
||||
b[i/2] = (hexRev[h[i]] << 4) | hexRev[h[i+1]]
|
||||
b[i/2+1] = (hexRev[h[i+2]] << 4) | hexRev[h[i+3]]
|
||||
invalidMark |= hexRev[h[i]] | hexRev[h[i+1]] | hexRev[h[i+2]] | hexRev[h[i+3]]
|
||||
}
|
||||
// If the upper 4 bits of any byte are not zero, there was an invalid hex
|
||||
// character since invalid hex characters are 0xff in hexRev.
|
||||
if invalidMark&0xf0 != 0 {
|
||||
return [8]byte{}, errInvalidHexID
|
||||
}
|
||||
// If we didn't set any bits, then h was all zeros.
|
||||
if invalidMark == 0 {
|
||||
return [8]byte{}, errNilSpanID
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// TraceFlags contains flags that can be set on a SpanContext.
|
||||
type TraceFlags byte //nolint:revive // revive complains about stutter of `trace.TraceFlags`.
|
||||
|
||||
// IsSampled reports whether the sampling bit is set in the TraceFlags.
|
||||
func (tf TraceFlags) IsSampled() bool {
|
||||
return tf&FlagsSampled == FlagsSampled
|
||||
}
|
||||
|
||||
// WithSampled sets the sampling bit in a new copy of the TraceFlags.
|
||||
func (tf TraceFlags) WithSampled(sampled bool) TraceFlags { // nolint:revive // sampled is not a control flag.
|
||||
if sampled {
|
||||
return tf | FlagsSampled
|
||||
}
|
||||
|
||||
return tf &^ FlagsSampled
|
||||
}
|
||||
|
||||
// MarshalJSON implements a custom marshal function to encode TraceFlags
|
||||
// as a hex string.
|
||||
func (tf TraceFlags) MarshalJSON() ([]byte, error) {
|
||||
b := [2 + 2]byte{0: '"', 3: '"'}
|
||||
h := tf.hexBytes()
|
||||
copy(b[1:], h[:])
|
||||
return b[:], nil
|
||||
}
|
||||
|
||||
// String returns the hex string representation form of TraceFlags.
|
||||
func (tf TraceFlags) String() string {
|
||||
h := tf.hexBytes()
|
||||
return string(h[:])
|
||||
}
|
||||
|
||||
func (tf TraceFlags) hexBytes() [2]byte {
|
||||
return [2]byte{hexLU[tf>>4], hexLU[tf&0xf]}
|
||||
}
|
||||
|
||||
// SpanContextConfig contains mutable fields usable for constructing
|
||||
// an immutable SpanContext.
|
||||
type SpanContextConfig struct {
|
||||
TraceID TraceID
|
||||
SpanID SpanID
|
||||
TraceFlags TraceFlags
|
||||
TraceState TraceState
|
||||
Remote bool
|
||||
}
|
||||
|
||||
// NewSpanContext constructs a SpanContext using values from the provided
|
||||
// SpanContextConfig.
|
||||
func NewSpanContext(config SpanContextConfig) SpanContext {
|
||||
return SpanContext{
|
||||
traceID: config.TraceID,
|
||||
spanID: config.SpanID,
|
||||
traceFlags: config.TraceFlags,
|
||||
traceState: config.TraceState,
|
||||
remote: config.Remote,
|
||||
}
|
||||
}
|
||||
|
||||
// SpanContext contains identifying trace information about a Span.
|
||||
type SpanContext struct {
|
||||
traceID TraceID
|
||||
spanID SpanID
|
||||
traceFlags TraceFlags
|
||||
traceState TraceState
|
||||
remote bool
|
||||
}
|
||||
|
||||
var _ json.Marshaler = SpanContext{}
|
||||
|
||||
// IsValid reports whether the SpanContext is valid. A valid span context has a
|
||||
// valid TraceID and SpanID.
|
||||
func (sc SpanContext) IsValid() bool {
|
||||
return sc.HasTraceID() && sc.HasSpanID()
|
||||
}
|
||||
|
||||
// IsRemote reports whether the SpanContext represents a remotely-created Span.
|
||||
func (sc SpanContext) IsRemote() bool {
|
||||
return sc.remote
|
||||
}
|
||||
|
||||
// WithRemote returns a copy of sc with the Remote property set to remote.
|
||||
func (sc SpanContext) WithRemote(remote bool) SpanContext {
|
||||
return SpanContext{
|
||||
traceID: sc.traceID,
|
||||
spanID: sc.spanID,
|
||||
traceFlags: sc.traceFlags,
|
||||
traceState: sc.traceState,
|
||||
remote: remote,
|
||||
}
|
||||
}
|
||||
|
||||
// TraceID returns the TraceID from the SpanContext.
|
||||
func (sc SpanContext) TraceID() TraceID {
|
||||
return sc.traceID
|
||||
}
|
||||
|
||||
// HasTraceID reports whether the SpanContext has a valid TraceID.
|
||||
func (sc SpanContext) HasTraceID() bool {
|
||||
return sc.traceID.IsValid()
|
||||
}
|
||||
|
||||
// WithTraceID returns a new SpanContext with the TraceID replaced.
|
||||
func (sc SpanContext) WithTraceID(traceID TraceID) SpanContext {
|
||||
return SpanContext{
|
||||
traceID: traceID,
|
||||
spanID: sc.spanID,
|
||||
traceFlags: sc.traceFlags,
|
||||
traceState: sc.traceState,
|
||||
remote: sc.remote,
|
||||
}
|
||||
}
|
||||
|
||||
// SpanID returns the SpanID from the SpanContext.
|
||||
func (sc SpanContext) SpanID() SpanID {
|
||||
return sc.spanID
|
||||
}
|
||||
|
||||
// HasSpanID reports whether the SpanContext has a valid SpanID.
|
||||
func (sc SpanContext) HasSpanID() bool {
|
||||
return sc.spanID.IsValid()
|
||||
}
|
||||
|
||||
// WithSpanID returns a new SpanContext with the SpanID replaced.
|
||||
func (sc SpanContext) WithSpanID(spanID SpanID) SpanContext {
|
||||
return SpanContext{
|
||||
traceID: sc.traceID,
|
||||
spanID: spanID,
|
||||
traceFlags: sc.traceFlags,
|
||||
traceState: sc.traceState,
|
||||
remote: sc.remote,
|
||||
}
|
||||
}
|
||||
|
||||
// TraceFlags returns the flags from the SpanContext.
|
||||
func (sc SpanContext) TraceFlags() TraceFlags {
|
||||
return sc.traceFlags
|
||||
}
|
||||
|
||||
// IsSampled reports whether the sampling bit is set in the SpanContext's TraceFlags.
|
||||
func (sc SpanContext) IsSampled() bool {
|
||||
return sc.traceFlags.IsSampled()
|
||||
}
|
||||
|
||||
// WithTraceFlags returns a new SpanContext with the TraceFlags replaced.
|
||||
func (sc SpanContext) WithTraceFlags(flags TraceFlags) SpanContext {
|
||||
return SpanContext{
|
||||
traceID: sc.traceID,
|
||||
spanID: sc.spanID,
|
||||
traceFlags: flags,
|
||||
traceState: sc.traceState,
|
||||
remote: sc.remote,
|
||||
}
|
||||
}
|
||||
|
||||
// TraceState returns the TraceState from the SpanContext.
|
||||
func (sc SpanContext) TraceState() TraceState {
|
||||
return sc.traceState
|
||||
}
|
||||
|
||||
// WithTraceState returns a new SpanContext with the TraceState replaced.
|
||||
func (sc SpanContext) WithTraceState(state TraceState) SpanContext {
|
||||
return SpanContext{
|
||||
traceID: sc.traceID,
|
||||
spanID: sc.spanID,
|
||||
traceFlags: sc.traceFlags,
|
||||
traceState: state,
|
||||
remote: sc.remote,
|
||||
}
|
||||
}
|
||||
|
||||
// Equal reports whether two SpanContext values are equal.
|
||||
func (sc SpanContext) Equal(other SpanContext) bool {
|
||||
return sc.traceID == other.traceID &&
|
||||
sc.spanID == other.spanID &&
|
||||
sc.traceFlags == other.traceFlags &&
|
||||
sc.traceState.String() == other.traceState.String() &&
|
||||
sc.remote == other.remote
|
||||
}
|
||||
|
||||
// MarshalJSON implements a custom marshal function to encode a SpanContext.
|
||||
func (sc SpanContext) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(SpanContextConfig{
|
||||
TraceID: sc.traceID,
|
||||
SpanID: sc.spanID,
|
||||
TraceFlags: sc.traceFlags,
|
||||
TraceState: sc.traceState,
|
||||
Remote: sc.remote,
|
||||
})
|
||||
}
|
||||
37
vendor/go.opentelemetry.io/otel/trace/tracer.go
generated
vendored
Normal file
37
vendor/go.opentelemetry.io/otel/trace/tracer.go
generated
vendored
Normal file
@@ -0,0 +1,37 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/trace/embedded"
|
||||
)
|
||||
|
||||
// Tracer is the creator of Spans.
|
||||
//
|
||||
// Warning: Methods may be added to this interface in minor releases. See
|
||||
// package documentation on API implementation for information on how to set
|
||||
// default behavior for unimplemented methods.
|
||||
type Tracer interface {
|
||||
// Users of the interface can ignore this. This embedded type is only used
|
||||
// by implementations of this interface. See the "API Implementations"
|
||||
// section of the package documentation for more information.
|
||||
embedded.Tracer
|
||||
|
||||
// Start creates a span and a context.Context containing the newly-created span.
|
||||
//
|
||||
// If the context.Context provided in `ctx` contains a Span then the newly-created
|
||||
// Span will be a child of that span, otherwise it will be a root span. This behavior
|
||||
// can be overridden by providing `WithNewRoot()` as a SpanOption, causing the
|
||||
// newly-created Span to be a root span even if `ctx` contains a Span.
|
||||
//
|
||||
// When creating a Span it is recommended to provide all known span attributes using
|
||||
// the `WithAttributes()` SpanOption as samplers will only have access to the
|
||||
// attributes provided when a Span is created.
|
||||
//
|
||||
// Any Span that is created MUST also be ended. This is the responsibility of the user.
|
||||
// Implementations of this API may leak memory or other resources if Spans are not ended.
|
||||
Start(ctx context.Context, spanName string, opts ...SpanStartOption) (context.Context, Span)
|
||||
}
|
||||
330
vendor/go.opentelemetry.io/otel/trace/tracestate.go
generated
vendored
Normal file
330
vendor/go.opentelemetry.io/otel/trace/tracestate.go
generated
vendored
Normal file
@@ -0,0 +1,330 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package trace // import "go.opentelemetry.io/otel/trace"
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
maxListMembers = 32
|
||||
|
||||
listDelimiters = ","
|
||||
memberDelimiter = "="
|
||||
|
||||
errInvalidKey errorConst = "invalid tracestate key"
|
||||
errInvalidValue errorConst = "invalid tracestate value"
|
||||
errInvalidMember errorConst = "invalid tracestate list-member"
|
||||
errMemberNumber errorConst = "too many list-members in tracestate"
|
||||
errDuplicate errorConst = "duplicate list-member in tracestate"
|
||||
)
|
||||
|
||||
type member struct {
|
||||
Key string
|
||||
Value string
|
||||
}
|
||||
|
||||
// according to (chr = %x20 / (nblk-char = %x21-2B / %x2D-3C / %x3E-7E) )
|
||||
// means (chr = %x20-2B / %x2D-3C / %x3E-7E) .
|
||||
func checkValueChar(v byte) bool {
|
||||
return v >= '\x20' && v <= '\x7e' && v != '\x2c' && v != '\x3d'
|
||||
}
|
||||
|
||||
// according to (nblk-chr = %x21-2B / %x2D-3C / %x3E-7E) .
|
||||
func checkValueLast(v byte) bool {
|
||||
return v >= '\x21' && v <= '\x7e' && v != '\x2c' && v != '\x3d'
|
||||
}
|
||||
|
||||
// based on the W3C Trace Context specification
|
||||
//
|
||||
// value = (0*255(chr)) nblk-chr
|
||||
// nblk-chr = %x21-2B / %x2D-3C / %x3E-7E
|
||||
// chr = %x20 / nblk-chr
|
||||
//
|
||||
// see https://www.w3.org/TR/trace-context-1/#value
|
||||
func checkValue(val string) bool {
|
||||
n := len(val)
|
||||
if n == 0 || n > 256 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < n-1; i++ {
|
||||
if !checkValueChar(val[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return checkValueLast(val[n-1])
|
||||
}
|
||||
|
||||
func checkKeyRemain(key string) bool {
|
||||
// ( lcalpha / DIGIT / "_" / "-"/ "*" / "/" )
|
||||
for _, v := range key {
|
||||
if isAlphaNum(byte(v)) {
|
||||
continue
|
||||
}
|
||||
switch v {
|
||||
case '_', '-', '*', '/':
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// according to
|
||||
//
|
||||
// simple-key = lcalpha (0*255( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ))
|
||||
// system-id = lcalpha (0*13( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ))
|
||||
//
|
||||
// param n is remain part length, should be 255 in simple-key or 13 in system-id.
|
||||
func checkKeyPart(key string, n int) bool {
|
||||
if key == "" {
|
||||
return false
|
||||
}
|
||||
first := key[0] // key's first char
|
||||
ret := len(key[1:]) <= n
|
||||
ret = ret && first >= 'a' && first <= 'z'
|
||||
return ret && checkKeyRemain(key[1:])
|
||||
}
|
||||
|
||||
func isAlphaNum(c byte) bool {
|
||||
if c >= 'a' && c <= 'z' {
|
||||
return true
|
||||
}
|
||||
return c >= '0' && c <= '9'
|
||||
}
|
||||
|
||||
// according to
|
||||
//
|
||||
// tenant-id = ( lcalpha / DIGIT ) 0*240( lcalpha / DIGIT / "_" / "-"/ "*" / "/" )
|
||||
//
|
||||
// param n is remain part length, should be 240 exactly.
|
||||
func checkKeyTenant(key string, n int) bool {
|
||||
if key == "" {
|
||||
return false
|
||||
}
|
||||
return isAlphaNum(key[0]) && len(key[1:]) <= n && checkKeyRemain(key[1:])
|
||||
}
|
||||
|
||||
// based on the W3C Trace Context specification
|
||||
//
|
||||
// key = simple-key / multi-tenant-key
|
||||
// simple-key = lcalpha (0*255( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ))
|
||||
// multi-tenant-key = tenant-id "@" system-id
|
||||
// tenant-id = ( lcalpha / DIGIT ) (0*240( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ))
|
||||
// system-id = lcalpha (0*13( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ))
|
||||
// lcalpha = %x61-7A ; a-z
|
||||
//
|
||||
// see https://www.w3.org/TR/trace-context-1/#tracestate-header.
|
||||
func checkKey(key string) bool {
|
||||
tenant, system, ok := strings.Cut(key, "@")
|
||||
if !ok {
|
||||
return checkKeyPart(key, 255)
|
||||
}
|
||||
return checkKeyTenant(tenant, 240) && checkKeyPart(system, 13)
|
||||
}
|
||||
|
||||
func newMember(key, value string) (member, error) {
|
||||
if !checkKey(key) {
|
||||
return member{}, errInvalidKey
|
||||
}
|
||||
if !checkValue(value) {
|
||||
return member{}, errInvalidValue
|
||||
}
|
||||
return member{Key: key, Value: value}, nil
|
||||
}
|
||||
|
||||
func parseMember(m string) (member, error) {
|
||||
key, val, ok := strings.Cut(m, memberDelimiter)
|
||||
if !ok {
|
||||
return member{}, fmt.Errorf("%w: %s", errInvalidMember, m)
|
||||
}
|
||||
key = strings.TrimLeft(key, " \t")
|
||||
val = strings.TrimRight(val, " \t")
|
||||
result, e := newMember(key, val)
|
||||
if e != nil {
|
||||
return member{}, fmt.Errorf("%w: %s", errInvalidMember, m)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// String encodes member into a string compliant with the W3C Trace Context
|
||||
// specification.
|
||||
func (m member) String() string {
|
||||
return m.Key + "=" + m.Value
|
||||
}
|
||||
|
||||
// TraceState provides additional vendor-specific trace identification
|
||||
// information across different distributed tracing systems. It represents an
|
||||
// immutable list consisting of key/value pairs, each pair is referred to as a
|
||||
// list-member.
|
||||
//
|
||||
// TraceState conforms to the W3C Trace Context specification
|
||||
// (https://www.w3.org/TR/trace-context-1). All operations that create or copy
|
||||
// a TraceState do so by validating all input and will only produce TraceState
|
||||
// that conform to the specification. Specifically, this means that all
|
||||
// list-member's key/value pairs are valid, no duplicate list-members exist,
|
||||
// and the maximum number of list-members (32) is not exceeded.
|
||||
type TraceState struct { //nolint:revive // revive complains about stutter of `trace.TraceState`
|
||||
// list is the members in order.
|
||||
list []member
|
||||
}
|
||||
|
||||
var _ json.Marshaler = TraceState{}
|
||||
|
||||
// ParseTraceState attempts to decode a TraceState from the passed
|
||||
// string. It returns an error if the input is invalid according to the W3C
|
||||
// Trace Context specification.
|
||||
func ParseTraceState(ts string) (TraceState, error) {
|
||||
if ts == "" {
|
||||
return TraceState{}, nil
|
||||
}
|
||||
|
||||
wrapErr := func(err error) error {
|
||||
return fmt.Errorf("failed to parse tracestate: %w", err)
|
||||
}
|
||||
|
||||
var members []member
|
||||
found := make(map[string]struct{})
|
||||
for ts != "" {
|
||||
var memberStr string
|
||||
memberStr, ts, _ = strings.Cut(ts, listDelimiters)
|
||||
if memberStr == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
m, err := parseMember(memberStr)
|
||||
if err != nil {
|
||||
return TraceState{}, wrapErr(err)
|
||||
}
|
||||
|
||||
if _, ok := found[m.Key]; ok {
|
||||
return TraceState{}, wrapErr(errDuplicate)
|
||||
}
|
||||
found[m.Key] = struct{}{}
|
||||
|
||||
members = append(members, m)
|
||||
if n := len(members); n > maxListMembers {
|
||||
return TraceState{}, wrapErr(errMemberNumber)
|
||||
}
|
||||
}
|
||||
|
||||
return TraceState{list: members}, nil
|
||||
}
|
||||
|
||||
// MarshalJSON marshals the TraceState into JSON.
|
||||
func (ts TraceState) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(ts.String())
|
||||
}
|
||||
|
||||
// String encodes the TraceState into a string compliant with the W3C
|
||||
// Trace Context specification. The returned string will be invalid if the
|
||||
// TraceState contains any invalid members.
|
||||
func (ts TraceState) String() string {
|
||||
if len(ts.list) == 0 {
|
||||
return ""
|
||||
}
|
||||
var n int
|
||||
n += len(ts.list) // member delimiters: '='
|
||||
n += len(ts.list) - 1 // list delimiters: ','
|
||||
for _, mem := range ts.list {
|
||||
n += len(mem.Key)
|
||||
n += len(mem.Value)
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
sb.Grow(n)
|
||||
_, _ = sb.WriteString(ts.list[0].Key)
|
||||
_ = sb.WriteByte('=')
|
||||
_, _ = sb.WriteString(ts.list[0].Value)
|
||||
for i := 1; i < len(ts.list); i++ {
|
||||
_ = sb.WriteByte(listDelimiters[0])
|
||||
_, _ = sb.WriteString(ts.list[i].Key)
|
||||
_ = sb.WriteByte('=')
|
||||
_, _ = sb.WriteString(ts.list[i].Value)
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// Get returns the value paired with key from the corresponding TraceState
|
||||
// list-member if it exists, otherwise an empty string is returned.
|
||||
func (ts TraceState) Get(key string) string {
|
||||
for _, member := range ts.list {
|
||||
if member.Key == key {
|
||||
return member.Value
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// Walk walks all key value pairs in the TraceState by calling f
|
||||
// Iteration stops if f returns false.
|
||||
func (ts TraceState) Walk(f func(key, value string) bool) {
|
||||
for _, m := range ts.list {
|
||||
if !f(m.Key, m.Value) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Insert adds a new list-member defined by the key/value pair to the
|
||||
// TraceState. If a list-member already exists for the given key, that
|
||||
// list-member's value is updated. The new or updated list-member is always
|
||||
// moved to the beginning of the TraceState as specified by the W3C Trace
|
||||
// Context specification.
|
||||
//
|
||||
// If key or value are invalid according to the W3C Trace Context
|
||||
// specification an error is returned with the original TraceState.
|
||||
//
|
||||
// If adding a new list-member means the TraceState would have more members
|
||||
// then is allowed, the new list-member will be inserted and the right-most
|
||||
// list-member will be dropped in the returned TraceState.
|
||||
func (ts TraceState) Insert(key, value string) (TraceState, error) {
|
||||
m, err := newMember(key, value)
|
||||
if err != nil {
|
||||
return ts, err
|
||||
}
|
||||
n := len(ts.list)
|
||||
found := n
|
||||
for i := range ts.list {
|
||||
if ts.list[i].Key == key {
|
||||
found = i
|
||||
}
|
||||
}
|
||||
cTS := TraceState{}
|
||||
if found == n && n < maxListMembers {
|
||||
cTS.list = make([]member, n+1)
|
||||
} else {
|
||||
cTS.list = make([]member, n)
|
||||
}
|
||||
cTS.list[0] = m
|
||||
// When the number of members exceeds capacity, drop the "right-most".
|
||||
copy(cTS.list[1:], ts.list[0:found])
|
||||
if found < n {
|
||||
copy(cTS.list[1+found:], ts.list[found+1:])
|
||||
}
|
||||
return cTS, nil
|
||||
}
|
||||
|
||||
// Delete returns a copy of the TraceState with the list-member identified by
|
||||
// key removed.
|
||||
func (ts TraceState) Delete(key string) TraceState {
|
||||
members := make([]member, ts.Len())
|
||||
copy(members, ts.list)
|
||||
for i, member := range ts.list {
|
||||
if member.Key == key {
|
||||
members = append(members[:i], members[i+1:]...)
|
||||
// TraceState should contain no duplicate members.
|
||||
break
|
||||
}
|
||||
}
|
||||
return TraceState{list: members}
|
||||
}
|
||||
|
||||
// Len returns the number of list-members in the TraceState.
|
||||
func (ts TraceState) Len() int {
|
||||
return len(ts.list)
|
||||
}
|
||||
Reference in New Issue
Block a user