Initial QSfera import
This commit is contained in:
Generated
Vendored
+231
@@ -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.
|
||||
Generated
Vendored
+257
@@ -0,0 +1,257 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"google.golang.org/grpc/stats"
|
||||
)
|
||||
|
||||
// ScopeName is the instrumentation scope name.
|
||||
const ScopeName = "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
|
||||
// InterceptorFilter is a predicate used to determine whether a given request in
|
||||
// interceptor info should be instrumented. A InterceptorFilter must return true if
|
||||
// the request should be traced.
|
||||
//
|
||||
// Deprecated: Use stats handlers instead.
|
||||
type InterceptorFilter func(*InterceptorInfo) bool
|
||||
|
||||
// Filter is a predicate used to determine whether a given request in
|
||||
// should be instrumented by the attached RPC tag info.
|
||||
// A Filter must return true if the request should be instrumented.
|
||||
type Filter func(*stats.RPCTagInfo) bool
|
||||
|
||||
type semconvMode int
|
||||
|
||||
const (
|
||||
semconvModeNew semconvMode = iota // Default
|
||||
semconvModeOld
|
||||
semconvModeDup
|
||||
)
|
||||
|
||||
// config is a group of options for this instrumentation.
|
||||
type config struct {
|
||||
Filter Filter
|
||||
InterceptorFilter InterceptorFilter
|
||||
Propagators propagation.TextMapPropagator
|
||||
TracerProvider trace.TracerProvider
|
||||
MeterProvider metric.MeterProvider
|
||||
SpanKind trace.SpanKind
|
||||
SpanStartOptions []trace.SpanStartOption
|
||||
SpanAttributes []attribute.KeyValue
|
||||
MetricAttributes []attribute.KeyValue
|
||||
MetricAttributesFn func(ctx context.Context) []attribute.KeyValue
|
||||
|
||||
PublicEndpoint bool
|
||||
PublicEndpointFn func(ctx context.Context, info *stats.RPCTagInfo) bool
|
||||
|
||||
ReceivedEvent bool
|
||||
SentEvent bool
|
||||
|
||||
semconvMode semconvMode
|
||||
}
|
||||
|
||||
// Option applies an option value for a config.
|
||||
type Option interface {
|
||||
apply(*config)
|
||||
}
|
||||
|
||||
type optionFunc func(*config)
|
||||
|
||||
func (f optionFunc) apply(c *config) {
|
||||
f(c)
|
||||
}
|
||||
|
||||
// newConfig returns a config configured with all the passed Options.
|
||||
func newConfig(opts []Option) *config {
|
||||
c := &config{
|
||||
Propagators: otel.GetTextMapPropagator(),
|
||||
TracerProvider: otel.GetTracerProvider(),
|
||||
MeterProvider: otel.GetMeterProvider(),
|
||||
semconvMode: parseSemconvMode(),
|
||||
}
|
||||
for _, o := range opts {
|
||||
o.apply(c)
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func parseSemconvMode() semconvMode {
|
||||
val := os.Getenv("OTEL_SEMCONV_STABILITY_OPT_IN")
|
||||
if val == "" {
|
||||
return semconvModeNew
|
||||
}
|
||||
parts := strings.SplitSeq(val, ",")
|
||||
for p := range parts {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "rpc/dup" {
|
||||
return semconvModeDup
|
||||
}
|
||||
if p == "rpc/old" {
|
||||
return semconvModeOld
|
||||
}
|
||||
}
|
||||
return semconvModeNew
|
||||
}
|
||||
|
||||
// WithPublicEndpoint configures the Handler to link the span with an incoming
|
||||
// span context. If this option is not provided, then the association is a child
|
||||
// association instead of a link.
|
||||
func WithPublicEndpoint() Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.PublicEndpoint = true
|
||||
})
|
||||
}
|
||||
|
||||
// WithPublicEndpointFn runs with every request, and allows conditionally
|
||||
// configuring the Handler to link the span with an incoming span context. If
|
||||
// this option is not provided or returns false, then the association is a
|
||||
// child association instead of a link.
|
||||
// Note: WithPublicEndpoint takes precedence over WithPublicEndpointFn.
|
||||
func WithPublicEndpointFn(fn func(context.Context, *stats.RPCTagInfo) bool) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.PublicEndpointFn = fn
|
||||
})
|
||||
}
|
||||
|
||||
// WithPropagators returns an Option to use the Propagators when extracting
|
||||
// and injecting trace context from requests.
|
||||
func WithPropagators(p propagation.TextMapPropagator) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
if p != nil {
|
||||
c.Propagators = p
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithInterceptorFilter returns an Option to use the request filter.
|
||||
//
|
||||
// Deprecated: Use stats handlers instead.
|
||||
func WithInterceptorFilter(f InterceptorFilter) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
if f != nil {
|
||||
c.InterceptorFilter = f
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithFilter returns an Option to use the request filter.
|
||||
func WithFilter(f Filter) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
if f != nil {
|
||||
c.Filter = f
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithTracerProvider returns an Option to use the TracerProvider when
|
||||
// creating a Tracer.
|
||||
func WithTracerProvider(tp trace.TracerProvider) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
if tp != nil {
|
||||
c.TracerProvider = tp
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMeterProvider returns an Option to use the MeterProvider when
|
||||
// creating a Meter. If this option is not provide the global MeterProvider will be used.
|
||||
func WithMeterProvider(mp metric.MeterProvider) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
if mp != nil {
|
||||
c.MeterProvider = mp
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Event type that can be recorded, see WithMessageEvents.
|
||||
type Event int
|
||||
|
||||
// Different types of events that can be recorded, see WithMessageEvents.
|
||||
const (
|
||||
ReceivedEvents Event = iota
|
||||
SentEvents
|
||||
)
|
||||
|
||||
// WithMessageEvents configures the Handler to record the specified events
|
||||
// (span.AddEvent) on spans. By default only summary attributes are added at the
|
||||
// end of the request.
|
||||
//
|
||||
// Valid events are:
|
||||
// - ReceivedEvents: Record the number of bytes read after every gRPC read operation.
|
||||
// - SentEvents: Record the number of bytes written after every gRPC write operation.
|
||||
func WithMessageEvents(events ...Event) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
for _, e := range events {
|
||||
switch e {
|
||||
case ReceivedEvents:
|
||||
c.ReceivedEvent = true
|
||||
case SentEvents:
|
||||
c.SentEvent = true
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithSpanOptions configures an additional set of
|
||||
// trace.SpanOptions, which are applied to each new span.
|
||||
//
|
||||
// Deprecated: It is only used by the deprecated interceptor, and is unused by [NewClientHandler] and [NewServerHandler].
|
||||
func WithSpanOptions(opts ...trace.SpanStartOption) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.SpanStartOptions = append(c.SpanStartOptions, opts...)
|
||||
})
|
||||
}
|
||||
|
||||
// WithSpanKind returns an Option to set the span kind for spans created by
|
||||
// the handler.
|
||||
//
|
||||
// By default, [NewServerHandler] creates spans with
|
||||
// [trace.SpanKindServer] and [NewClientHandler] creates spans with
|
||||
// [trace.SpanKindClient].
|
||||
func WithSpanKind(sk trace.SpanKind) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.SpanKind = sk
|
||||
})
|
||||
}
|
||||
|
||||
// WithSpanAttributes returns an Option to add custom attributes to the spans.
|
||||
func WithSpanAttributes(a ...attribute.KeyValue) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
if a != nil {
|
||||
c.SpanAttributes = a
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMetricAttributes returns an Option to add custom attributes to the metrics.
|
||||
func WithMetricAttributes(a ...attribute.KeyValue) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
if a != nil {
|
||||
c.MetricAttributes = append(c.MetricAttributes, a...)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMetricAttributesFn returns an Option to add dynamic custom attributes to the handler's metrics.
|
||||
// The function is called once per RPC and the returned attributes are applied to all metrics recorded by this handler.
|
||||
//
|
||||
// The context parameter is the standard gRPC request context and provides access to request-scoped data.
|
||||
func WithMetricAttributesFn(fn func(ctx context.Context) []attribute.KeyValue) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
if fn != nil {
|
||||
c.MetricAttributesFn = fn
|
||||
}
|
||||
})
|
||||
}
|
||||
Generated
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
/*
|
||||
Package otelgrpc is the instrumentation library for [google.golang.org/grpc].
|
||||
|
||||
Use [NewClientHandler] with [grpc.WithStatsHandler] to instrument a gRPC client.
|
||||
|
||||
Use [NewServerHandler] with [grpc.StatsHandler] to instrument a gRPC server.
|
||||
*/
|
||||
package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
Generated
Vendored
+57
@@ -0,0 +1,57 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
|
||||
// gRPC tracing middleware
|
||||
// https://opentelemetry.io/docs/specs/semconv/rpc/
|
||||
import (
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
grpc_codes "google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// serverAddrAttrs returns the server address attributes for the hostport.
|
||||
func serverAddrAttrs(hostport string) []attribute.KeyValue {
|
||||
h, pStr, err := net.SplitHostPort(hostport)
|
||||
if err != nil {
|
||||
// The server.address attribute is required.
|
||||
return []attribute.KeyValue{semconv.ServerAddress(hostport)}
|
||||
}
|
||||
p, err := strconv.Atoi(pStr)
|
||||
if err != nil {
|
||||
return []attribute.KeyValue{semconv.ServerAddress(h)}
|
||||
}
|
||||
return []attribute.KeyValue{
|
||||
semconv.ServerAddress(h),
|
||||
semconv.ServerPort(p),
|
||||
}
|
||||
}
|
||||
|
||||
// serverStatus returns a span status code and message for a given gRPC
|
||||
// status code. It maps specific gRPC status codes to a corresponding span
|
||||
// status code and message. This function is intended for use on the server
|
||||
// side of a gRPC connection.
|
||||
//
|
||||
// If the gRPC status code is Unknown, DeadlineExceeded, Unimplemented,
|
||||
// Internal, Unavailable, or DataLoss, it returns a span status code of Error
|
||||
// and the message from the gRPC status. Otherwise, it returns a span status
|
||||
// code of Unset and an empty message.
|
||||
func serverStatus(grpcStatus *status.Status) (codes.Code, string) {
|
||||
switch grpcStatus.Code() {
|
||||
case grpc_codes.Unknown,
|
||||
grpc_codes.DeadlineExceeded,
|
||||
grpc_codes.Unimplemented,
|
||||
grpc_codes.Internal,
|
||||
grpc_codes.Unavailable,
|
||||
grpc_codes.DataLoss:
|
||||
return codes.Error, grpcStatus.Message()
|
||||
default:
|
||||
return codes.Unset, ""
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+39
@@ -0,0 +1,39 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// InterceptorType is the flag to define which gRPC interceptor
|
||||
// the InterceptorInfo object is.
|
||||
type InterceptorType uint8
|
||||
|
||||
const (
|
||||
// UndefinedInterceptor is the type for the interceptor information that is not
|
||||
// well initialized or categorized to other types.
|
||||
UndefinedInterceptor InterceptorType = iota
|
||||
// UnaryClient is the type for grpc.UnaryClient interceptor.
|
||||
UnaryClient
|
||||
// StreamClient is the type for grpc.StreamClient interceptor.
|
||||
StreamClient
|
||||
// UnaryServer is the type for grpc.UnaryServer interceptor.
|
||||
UnaryServer
|
||||
// StreamServer is the type for grpc.StreamServer interceptor.
|
||||
StreamServer
|
||||
)
|
||||
|
||||
// InterceptorInfo is the union of some arguments to four types of
|
||||
// gRPC interceptors.
|
||||
type InterceptorInfo struct {
|
||||
// Method is method name registered to UnaryClient and StreamClient
|
||||
Method string
|
||||
// UnaryServerInfo is the metadata for UnaryServer
|
||||
UnaryServerInfo *grpc.UnaryServerInfo
|
||||
// StreamServerInfo if the metadata for StreamServer
|
||||
StreamServerInfo *grpc.StreamServerInfo
|
||||
// Type is the type for interceptor
|
||||
Type InterceptorType
|
||||
}
|
||||
Generated
Vendored
+53
@@ -0,0 +1,53 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package internal provides internal functionality for the otelgrpc package.
|
||||
package internal // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal"
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
oldsemconv "go.opentelemetry.io/otel/semconv/v1.37.0" //nolint:depguard // Use of v1.37.0 is required for backward compatibility stability opt-in.
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
)
|
||||
|
||||
// ParseFullMethod returns a span name following the OpenTelemetry semantic
|
||||
// conventions as well as all applicable span attribute.KeyValue attributes based
|
||||
// on a gRPC's FullMethod.
|
||||
//
|
||||
// Parsing is consistent with grpc-go implementation:
|
||||
// https://github.com/grpc/grpc-go/blob/v1.57.0/internal/grpcutil/method.go#L26-L39
|
||||
func ParseFullMethod(fullMethod string) (string, []attribute.KeyValue) {
|
||||
if !strings.HasPrefix(fullMethod, "/") {
|
||||
// Invalid format, does not follow `/package.service/method`.
|
||||
return fullMethod, nil
|
||||
}
|
||||
name := fullMethod[1:]
|
||||
return name, []attribute.KeyValue{semconv.RPCMethod(name)}
|
||||
}
|
||||
|
||||
// ParseFullMethodOld returns a span name following the old OpenTelemetry semantic
|
||||
// conventions as well as all applicable span attribute.KeyValue attributes based
|
||||
// on a gRPC's FullMethod.
|
||||
// Based on the implementation in:
|
||||
// https://github.com/open-telemetry/opentelemetry-go-contrib/blob/072dcf8ad7e5e48b506e05720b29d8b078759606/instrumentation/google.golang.org/grpc/otelgrpc/internal/parse.go#L20
|
||||
func ParseFullMethodOld(fullMethod string) (string, []attribute.KeyValue) {
|
||||
if !strings.HasPrefix(fullMethod, "/") {
|
||||
return fullMethod, nil
|
||||
}
|
||||
name := fullMethod[1:]
|
||||
parts := strings.Split(name, "/")
|
||||
if len(parts) < 2 {
|
||||
return name, []attribute.KeyValue{
|
||||
attribute.String("rpc.system", "grpc"),
|
||||
}
|
||||
}
|
||||
service := parts[0]
|
||||
method := parts[1]
|
||||
return name, []attribute.KeyValue{
|
||||
oldsemconv.RPCSystemKey.String("grpc"),
|
||||
oldsemconv.RPCServiceKey.String(service),
|
||||
oldsemconv.RPCMethodKey.String(method),
|
||||
}
|
||||
}
|
||||
Generated
Vendored
+60
@@ -0,0 +1,60 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"google.golang.org/grpc/metadata"
|
||||
)
|
||||
|
||||
type metadataSupplier struct {
|
||||
metadata metadata.MD
|
||||
}
|
||||
|
||||
// assert that metadataSupplier implements the TextMapCarrier interface.
|
||||
var _ propagation.TextMapCarrier = metadataSupplier{}
|
||||
|
||||
func (s metadataSupplier) Get(key string) string {
|
||||
values := s.metadata.Get(key)
|
||||
if len(values) == 0 {
|
||||
return ""
|
||||
}
|
||||
return values[0]
|
||||
}
|
||||
|
||||
func (s metadataSupplier) Set(key, value string) {
|
||||
s.metadata.Set(key, value)
|
||||
}
|
||||
|
||||
func (s metadataSupplier) Keys() []string {
|
||||
out := make([]string, 0, len(s.metadata))
|
||||
for key := range s.metadata {
|
||||
out = append(out, key)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func inject(ctx context.Context, propagators propagation.TextMapPropagator) context.Context {
|
||||
md, ok := metadata.FromOutgoingContext(ctx)
|
||||
if !ok {
|
||||
md = metadata.MD{}
|
||||
}
|
||||
propagators.Inject(ctx, metadataSupplier{
|
||||
metadata: md,
|
||||
})
|
||||
return metadata.NewOutgoingContext(ctx, md)
|
||||
}
|
||||
|
||||
func extract(ctx context.Context, propagators propagation.TextMapPropagator) context.Context {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
md = metadata.MD{}
|
||||
}
|
||||
|
||||
return propagators.Extract(ctx, metadataSupplier{
|
||||
metadata: md,
|
||||
})
|
||||
}
|
||||
Generated
Vendored
+437
@@ -0,0 +1,437 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
oldrpcconv "go.opentelemetry.io/otel/semconv/v1.37.0/rpcconv" //nolint:depguard // Use of v1.37.0 is required for backward compatibility stability opt-in.
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
"go.opentelemetry.io/otel/semconv/v1.40.0/rpcconv"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
grpc_codes "google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/stats"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/internal"
|
||||
)
|
||||
|
||||
type gRPCContextKey struct{}
|
||||
|
||||
type gRPCContext struct {
|
||||
metricAttrs []attribute.KeyValue
|
||||
record bool
|
||||
}
|
||||
|
||||
type serverHandler struct {
|
||||
*config
|
||||
|
||||
tracer trace.Tracer
|
||||
|
||||
duration rpcconv.ServerCallDuration
|
||||
oldDuration oldrpcconv.ServerDuration
|
||||
}
|
||||
|
||||
// NewServerHandler creates a stats.Handler for a gRPC server.
|
||||
func NewServerHandler(opts ...Option) stats.Handler {
|
||||
c := newConfig(opts)
|
||||
if c.SpanKind == trace.SpanKindUnspecified {
|
||||
c.SpanKind = trace.SpanKindServer
|
||||
}
|
||||
|
||||
h := &serverHandler{config: c}
|
||||
|
||||
h.tracer = c.TracerProvider.Tracer(
|
||||
ScopeName,
|
||||
trace.WithInstrumentationVersion(Version),
|
||||
)
|
||||
|
||||
meter := c.MeterProvider.Meter(
|
||||
ScopeName,
|
||||
metric.WithInstrumentationVersion(Version),
|
||||
metric.WithSchemaURL(semconv.SchemaURL),
|
||||
)
|
||||
|
||||
var err error
|
||||
if c.semconvMode == semconvModeOld || c.semconvMode == semconvModeDup {
|
||||
oldDur, err := oldrpcconv.NewServerDuration(meter)
|
||||
if err != nil {
|
||||
otel.Handle(err)
|
||||
} else {
|
||||
h.oldDuration = oldDur
|
||||
}
|
||||
}
|
||||
|
||||
if c.semconvMode == semconvModeNew || c.semconvMode == semconvModeDup {
|
||||
h.duration, err = rpcconv.NewServerCallDuration(
|
||||
meter,
|
||||
metric.WithExplicitBucketBoundaries(
|
||||
0.005, 0.01, 0.025, 0.05, 0.075, 0.1,
|
||||
0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10,
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
otel.Handle(err)
|
||||
}
|
||||
}
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
// TagConn can attach some information to the given context.
|
||||
func (*serverHandler) TagConn(ctx context.Context, _ *stats.ConnTagInfo) context.Context {
|
||||
return ctx
|
||||
}
|
||||
|
||||
// HandleConn processes the Conn stats.
|
||||
func (*serverHandler) HandleConn(context.Context, stats.ConnStats) {
|
||||
}
|
||||
|
||||
// TagRPC can attach some information to the given context.
|
||||
func (h *serverHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {
|
||||
ctx = extract(ctx, h.Propagators)
|
||||
|
||||
var name string
|
||||
var attrs []attribute.KeyValue
|
||||
|
||||
switch h.semconvMode {
|
||||
case semconvModeOld:
|
||||
name, attrs = internal.ParseFullMethodOld(info.FullMethodName)
|
||||
case semconvModeDup:
|
||||
var attrsNew, attrsOld []attribute.KeyValue
|
||||
name, attrsNew = internal.ParseFullMethod(info.FullMethodName)
|
||||
_, attrsOld = internal.ParseFullMethodOld(info.FullMethodName)
|
||||
// Combine both. We append New last so its rpc.method (fully qualified) wins when deduplicated.
|
||||
attrs = append(append([]attribute.KeyValue{}, attrsOld...), attrsNew...)
|
||||
attrs = append(attrs, semconv.RPCSystemNameGRPC) // New convention
|
||||
default: // semconvModeNew
|
||||
name, attrs = internal.ParseFullMethod(info.FullMethodName)
|
||||
attrs = append(attrs, semconv.RPCSystemNameGRPC)
|
||||
}
|
||||
|
||||
record := true
|
||||
if h.Filter != nil {
|
||||
record = h.Filter(info)
|
||||
}
|
||||
|
||||
if record {
|
||||
// Make a new slice to avoid aliasing into the same attrs slice used by metrics.
|
||||
spanAttributes := make([]attribute.KeyValue, 0, len(attrs)+len(h.SpanAttributes))
|
||||
spanAttributes = append(append(spanAttributes, attrs...), h.SpanAttributes...)
|
||||
opts := []trace.SpanStartOption{
|
||||
trace.WithSpanKind(h.SpanKind),
|
||||
trace.WithAttributes(spanAttributes...),
|
||||
}
|
||||
if h.PublicEndpoint || (h.PublicEndpointFn != nil && h.PublicEndpointFn(ctx, info)) {
|
||||
opts = append(opts, trace.WithNewRoot())
|
||||
// Linking incoming span context if any for public endpoint.
|
||||
if s := trace.SpanContextFromContext(ctx); s.IsValid() && s.IsRemote() {
|
||||
opts = append(opts, trace.WithLinks(trace.Link{SpanContext: s}))
|
||||
}
|
||||
}
|
||||
ctx, _ = h.tracer.Start(
|
||||
trace.ContextWithRemoteSpanContext(ctx, trace.SpanContextFromContext(ctx)),
|
||||
name,
|
||||
opts...,
|
||||
)
|
||||
}
|
||||
|
||||
gctx := gRPCContext{
|
||||
metricAttrs: append(attrs, h.MetricAttributes...),
|
||||
record: record,
|
||||
}
|
||||
|
||||
if h.MetricAttributesFn != nil {
|
||||
extraAttrs := h.MetricAttributesFn(ctx)
|
||||
gctx.metricAttrs = append(gctx.metricAttrs, extraAttrs...)
|
||||
}
|
||||
|
||||
return context.WithValue(ctx, gRPCContextKey{}, &gctx)
|
||||
}
|
||||
|
||||
// HandleRPC processes the RPC stats.
|
||||
func (h *serverHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) {
|
||||
var dur metric.Float64Histogram
|
||||
if h.semconvMode == semconvModeNew || h.semconvMode == semconvModeDup {
|
||||
dur = h.duration.Inst()
|
||||
}
|
||||
var oldDur metric.Float64Histogram
|
||||
if h.semconvMode == semconvModeOld || h.semconvMode == semconvModeDup {
|
||||
oldDur = h.oldDuration.Inst()
|
||||
}
|
||||
h.handleRPC(
|
||||
ctx,
|
||||
rs,
|
||||
dur,
|
||||
oldDur,
|
||||
serverStatus,
|
||||
)
|
||||
}
|
||||
|
||||
type clientHandler struct {
|
||||
*config
|
||||
|
||||
tracer trace.Tracer
|
||||
|
||||
duration rpcconv.ClientCallDuration
|
||||
oldDuration oldrpcconv.ClientDuration
|
||||
}
|
||||
|
||||
// NewClientHandler creates a stats.Handler for a gRPC client.
|
||||
func NewClientHandler(opts ...Option) stats.Handler {
|
||||
c := newConfig(opts)
|
||||
if c.SpanKind == trace.SpanKindUnspecified {
|
||||
c.SpanKind = trace.SpanKindClient
|
||||
}
|
||||
|
||||
h := &clientHandler{config: c}
|
||||
|
||||
h.tracer = c.TracerProvider.Tracer(
|
||||
ScopeName,
|
||||
trace.WithInstrumentationVersion(Version),
|
||||
)
|
||||
|
||||
meter := c.MeterProvider.Meter(
|
||||
ScopeName,
|
||||
metric.WithInstrumentationVersion(Version),
|
||||
metric.WithSchemaURL(semconv.SchemaURL),
|
||||
)
|
||||
|
||||
var err error
|
||||
if c.semconvMode == semconvModeOld || c.semconvMode == semconvModeDup {
|
||||
oldDur, err := oldrpcconv.NewClientDuration(meter)
|
||||
if err != nil {
|
||||
otel.Handle(err)
|
||||
} else {
|
||||
h.oldDuration = oldDur
|
||||
}
|
||||
}
|
||||
|
||||
if c.semconvMode == semconvModeNew || c.semconvMode == semconvModeDup {
|
||||
h.duration, err = rpcconv.NewClientCallDuration(
|
||||
meter,
|
||||
metric.WithExplicitBucketBoundaries(
|
||||
0.005, 0.01, 0.025, 0.05, 0.075, 0.1,
|
||||
0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10,
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
otel.Handle(err)
|
||||
}
|
||||
}
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
// TagRPC can attach some information to the given context.
|
||||
func (h *clientHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) context.Context {
|
||||
var name string
|
||||
var attrs []attribute.KeyValue
|
||||
|
||||
switch h.semconvMode {
|
||||
case semconvModeOld:
|
||||
name, attrs = internal.ParseFullMethodOld(info.FullMethodName)
|
||||
case semconvModeDup:
|
||||
var attrsNew, attrsOld []attribute.KeyValue
|
||||
name, attrsNew = internal.ParseFullMethod(info.FullMethodName)
|
||||
_, attrsOld = internal.ParseFullMethodOld(info.FullMethodName)
|
||||
// Combine both. We append New last so its rpc.method (fully qualified) wins when deduplicated.
|
||||
attrs = append(append([]attribute.KeyValue{}, attrsOld...), attrsNew...)
|
||||
attrs = append(attrs, semconv.RPCSystemNameGRPC) // New convention
|
||||
default: // semconvModeNew
|
||||
name, attrs = internal.ParseFullMethod(info.FullMethodName)
|
||||
attrs = append(attrs, semconv.RPCSystemNameGRPC)
|
||||
}
|
||||
|
||||
record := true
|
||||
if h.Filter != nil {
|
||||
record = h.Filter(info)
|
||||
}
|
||||
|
||||
if record {
|
||||
// Make a new slice to avoid aliasing into the same attrs slice used by metrics.
|
||||
spanAttributes := make([]attribute.KeyValue, 0, len(attrs)+len(h.SpanAttributes))
|
||||
spanAttributes = append(append(spanAttributes, attrs...), h.SpanAttributes...)
|
||||
ctx, _ = h.tracer.Start(
|
||||
ctx,
|
||||
name,
|
||||
trace.WithSpanKind(h.SpanKind),
|
||||
trace.WithAttributes(spanAttributes...),
|
||||
)
|
||||
}
|
||||
|
||||
gctx := gRPCContext{
|
||||
metricAttrs: append(attrs, h.MetricAttributes...),
|
||||
record: record,
|
||||
}
|
||||
|
||||
if h.MetricAttributesFn != nil {
|
||||
extraAttrs := h.MetricAttributesFn(ctx)
|
||||
gctx.metricAttrs = append(gctx.metricAttrs, extraAttrs...)
|
||||
}
|
||||
|
||||
return inject(context.WithValue(ctx, gRPCContextKey{}, &gctx), h.Propagators)
|
||||
}
|
||||
|
||||
// HandleRPC processes the RPC stats.
|
||||
func (h *clientHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) {
|
||||
var dur metric.Float64Histogram
|
||||
if h.semconvMode == semconvModeNew || h.semconvMode == semconvModeDup {
|
||||
dur = h.duration.Inst()
|
||||
}
|
||||
var oldDur metric.Float64Histogram
|
||||
if h.semconvMode == semconvModeOld || h.semconvMode == semconvModeDup {
|
||||
oldDur = h.oldDuration.Inst()
|
||||
}
|
||||
h.handleRPC(
|
||||
ctx,
|
||||
rs,
|
||||
dur,
|
||||
oldDur,
|
||||
func(s *status.Status) (codes.Code, string) {
|
||||
return codes.Error, s.Message()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// TagConn can attach some information to the given context.
|
||||
func (*clientHandler) TagConn(ctx context.Context, _ *stats.ConnTagInfo) context.Context {
|
||||
return ctx
|
||||
}
|
||||
|
||||
// HandleConn processes the Conn stats.
|
||||
func (*clientHandler) HandleConn(context.Context, stats.ConnStats) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
func (*config) handleRPC(
|
||||
ctx context.Context,
|
||||
rs stats.RPCStats,
|
||||
duration metric.Float64Histogram,
|
||||
oldDuration metric.Float64Histogram,
|
||||
recordStatus func(*status.Status) (codes.Code, string),
|
||||
) {
|
||||
gctx, _ := ctx.Value(gRPCContextKey{}).(*gRPCContext)
|
||||
if gctx != nil && !gctx.record {
|
||||
return
|
||||
}
|
||||
|
||||
span := trace.SpanFromContext(ctx)
|
||||
|
||||
switch rs := rs.(type) {
|
||||
case *stats.Begin:
|
||||
case *stats.InPayload:
|
||||
case *stats.InHeader:
|
||||
if !rs.Client && rs.LocalAddr != nil {
|
||||
if span.IsRecording() {
|
||||
span.SetAttributes(serverAddrAttrs(rs.LocalAddr.String())...)
|
||||
}
|
||||
// TODO: add server.address and server.port to metrics once the API supports opt-in attributes.
|
||||
}
|
||||
case *stats.OutPayload:
|
||||
case *stats.OutTrailer:
|
||||
case *stats.OutHeader:
|
||||
if rs.Client && rs.RemoteAddr != nil && (span.IsRecording() || gctx != nil) {
|
||||
attrs := serverAddrAttrs(rs.RemoteAddr.String())
|
||||
if span.IsRecording() {
|
||||
span.SetAttributes(attrs...)
|
||||
}
|
||||
if gctx != nil {
|
||||
gctx.metricAttrs = append(gctx.metricAttrs, attrs...)
|
||||
}
|
||||
}
|
||||
case *stats.End:
|
||||
var rpcStatusAttr attribute.KeyValue
|
||||
|
||||
var s *status.Status
|
||||
if rs.Error != nil {
|
||||
s, _ = status.FromError(rs.Error)
|
||||
rpcStatusAttr = semconv.RPCResponseStatusCode(canonicalString(s.Code()))
|
||||
} else {
|
||||
rpcStatusAttr = semconv.RPCResponseStatusCode(canonicalString(grpc_codes.OK))
|
||||
}
|
||||
if span.IsRecording() {
|
||||
if s != nil {
|
||||
c, m := recordStatus(s)
|
||||
span.SetStatus(c, m)
|
||||
}
|
||||
span.SetAttributes(rpcStatusAttr)
|
||||
span.End()
|
||||
}
|
||||
|
||||
var metricAttrs []attribute.KeyValue
|
||||
if gctx != nil {
|
||||
// Don't use gctx.metricAttrSet here, because it requires passing
|
||||
// multiple RecordOptions, which would call metric.mergeSets and
|
||||
// allocate a new set for each Record call.
|
||||
metricAttrs = make([]attribute.KeyValue, 0, len(gctx.metricAttrs)+1)
|
||||
metricAttrs = append(metricAttrs, gctx.metricAttrs...)
|
||||
}
|
||||
metricAttrs = append(metricAttrs, rpcStatusAttr)
|
||||
// Allocate vararg slice once.
|
||||
recordOpts := []metric.RecordOption{metric.WithAttributeSet(attribute.NewSet(metricAttrs...))}
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
// Measure right before calling Record() to capture as much elapsed time as possible.
|
||||
elapsedTime := float64(rs.EndTime.Sub(rs.BeginTime)) / float64(time.Second)
|
||||
|
||||
if duration != nil {
|
||||
duration.Record(ctx, elapsedTime, recordOpts...)
|
||||
}
|
||||
if oldDuration != nil {
|
||||
oldDuration.Record(ctx, elapsedTime*1000.0, recordOpts...)
|
||||
}
|
||||
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func canonicalString(code grpc_codes.Code) string {
|
||||
switch code {
|
||||
case grpc_codes.OK:
|
||||
return "OK"
|
||||
case grpc_codes.Canceled:
|
||||
return "CANCELLED"
|
||||
case grpc_codes.Unknown:
|
||||
return "UNKNOWN"
|
||||
case grpc_codes.InvalidArgument:
|
||||
return "INVALID_ARGUMENT"
|
||||
case grpc_codes.DeadlineExceeded:
|
||||
return "DEADLINE_EXCEEDED"
|
||||
case grpc_codes.NotFound:
|
||||
return "NOT_FOUND"
|
||||
case grpc_codes.AlreadyExists:
|
||||
return "ALREADY_EXISTS"
|
||||
case grpc_codes.PermissionDenied:
|
||||
return "PERMISSION_DENIED"
|
||||
case grpc_codes.ResourceExhausted:
|
||||
return "RESOURCE_EXHAUSTED"
|
||||
case grpc_codes.FailedPrecondition:
|
||||
return "FAILED_PRECONDITION"
|
||||
case grpc_codes.Aborted:
|
||||
return "ABORTED"
|
||||
case grpc_codes.OutOfRange:
|
||||
return "OUT_OF_RANGE"
|
||||
case grpc_codes.Unimplemented:
|
||||
return "UNIMPLEMENTED"
|
||||
case grpc_codes.Internal:
|
||||
return "INTERNAL"
|
||||
case grpc_codes.Unavailable:
|
||||
return "UNAVAILABLE"
|
||||
case grpc_codes.DataLoss:
|
||||
return "DATA_LOSS"
|
||||
case grpc_codes.Unauthenticated:
|
||||
return "UNAUTHENTICATED"
|
||||
default:
|
||||
return "CODE(" + strconv.FormatInt(int64(code), 10) + ")"
|
||||
}
|
||||
}
|
||||
Server/vendor/go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc/version.go
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelgrpc // import "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
|
||||
|
||||
// Version is the current release version of the gRPC instrumentation.
|
||||
const Version = "0.68.0"
|
||||
Generated
Vendored
+231
@@ -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.
|
||||
Generated
Vendored
+27
@@ -0,0 +1,27 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// Attribute keys that can be added to a span.
|
||||
const (
|
||||
ReadBytesKey = attribute.Key("http.read_bytes") // if anything was read from the request body, the total number of bytes read
|
||||
ReadErrorKey = attribute.Key("http.read_error") // If an error occurred while reading a request, the string of the error (io.EOF is not recorded)
|
||||
WroteBytesKey = attribute.Key("http.wrote_bytes") // if anything was written to the response writer, the total number of bytes written
|
||||
WriteErrorKey = attribute.Key("http.write_error") // if an error occurred while writing a reply, the string of the error (io.EOF is not recorded)
|
||||
)
|
||||
|
||||
// Filter is a predicate used to determine whether a given http.request should
|
||||
// be traced. A Filter must return true if the request should be traced.
|
||||
type Filter func(*http.Request) bool
|
||||
|
||||
func newTracer(tp trace.TracerProvider) trace.Tracer {
|
||||
return tp.Tracer(ScopeName, trace.WithInstrumentationVersion(Version))
|
||||
}
|
||||
Generated
Vendored
+204
@@ -0,0 +1,204 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptrace"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// ScopeName is the instrumentation scope name.
|
||||
const ScopeName = "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
|
||||
// config represents the configuration options available for the http.Handler
|
||||
// and http.Transport types.
|
||||
type config struct {
|
||||
ServerName string
|
||||
Tracer trace.Tracer
|
||||
Meter metric.Meter
|
||||
Propagators propagation.TextMapPropagator
|
||||
SpanStartOptions []trace.SpanStartOption
|
||||
PublicEndpointFn func(*http.Request) bool
|
||||
ReadEvent bool
|
||||
WriteEvent bool
|
||||
Filters []Filter
|
||||
SpanNameFormatter func(string, *http.Request) string
|
||||
ClientTrace func(context.Context) *httptrace.ClientTrace
|
||||
|
||||
TracerProvider trace.TracerProvider
|
||||
MeterProvider metric.MeterProvider
|
||||
MetricAttributesFn func(*http.Request) []attribute.KeyValue
|
||||
}
|
||||
|
||||
// Option interface used for setting optional config properties.
|
||||
type Option interface {
|
||||
apply(*config)
|
||||
}
|
||||
|
||||
type optionFunc func(*config)
|
||||
|
||||
func (o optionFunc) apply(c *config) {
|
||||
o(c)
|
||||
}
|
||||
|
||||
// newConfig creates a new config struct and applies opts to it.
|
||||
func newConfig(opts ...Option) *config {
|
||||
c := &config{
|
||||
Propagators: otel.GetTextMapPropagator(),
|
||||
MeterProvider: otel.GetMeterProvider(),
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt.apply(c)
|
||||
}
|
||||
|
||||
// Tracer is only initialized if manually specified. Otherwise, can be passed with the tracing context.
|
||||
if c.TracerProvider != nil {
|
||||
c.Tracer = newTracer(c.TracerProvider)
|
||||
}
|
||||
|
||||
c.Meter = c.MeterProvider.Meter(
|
||||
ScopeName,
|
||||
metric.WithInstrumentationVersion(Version),
|
||||
)
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
// WithTracerProvider specifies a tracer provider to use for creating a tracer.
|
||||
// If none is specified, the global provider is used.
|
||||
func WithTracerProvider(provider trace.TracerProvider) Option {
|
||||
return optionFunc(func(cfg *config) {
|
||||
if provider != nil {
|
||||
cfg.TracerProvider = provider
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMeterProvider specifies a meter provider to use for creating a meter.
|
||||
// If none is specified, the global provider is used.
|
||||
func WithMeterProvider(provider metric.MeterProvider) Option {
|
||||
return optionFunc(func(cfg *config) {
|
||||
if provider != nil {
|
||||
cfg.MeterProvider = provider
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithPublicEndpointFn runs with every request, and allows conditionally
|
||||
// configuring the Handler to link the span with an incoming span context. If
|
||||
// this option is not provided or returns false, then the association is a
|
||||
// child association instead of a link.
|
||||
func WithPublicEndpointFn(fn func(*http.Request) bool) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.PublicEndpointFn = fn
|
||||
})
|
||||
}
|
||||
|
||||
// WithPropagators configures specific propagators. If this
|
||||
// option isn't specified, then the global TextMapPropagator is used.
|
||||
func WithPropagators(ps propagation.TextMapPropagator) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
if ps != nil {
|
||||
c.Propagators = ps
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithSpanOptions configures an additional set of
|
||||
// trace.SpanOptions, which are applied to each new span.
|
||||
func WithSpanOptions(opts ...trace.SpanStartOption) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.SpanStartOptions = append(c.SpanStartOptions, opts...)
|
||||
})
|
||||
}
|
||||
|
||||
// WithFilter adds a filter to the list of filters used by the handler.
|
||||
// If any filter indicates to exclude a request then the request will not be
|
||||
// traced. All filters must allow a request to be traced for a Span to be created.
|
||||
// If no filters are provided then all requests are traced.
|
||||
// Filters will be invoked for each processed request, it is advised to make them
|
||||
// simple and fast.
|
||||
func WithFilter(f Filter) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.Filters = append(c.Filters, f)
|
||||
})
|
||||
}
|
||||
|
||||
// Event represents message event types for [WithMessageEvents].
|
||||
type Event int
|
||||
|
||||
// Different types of events that can be recorded, see WithMessageEvents.
|
||||
const (
|
||||
unspecifiedEvents Event = iota
|
||||
ReadEvents
|
||||
WriteEvents
|
||||
)
|
||||
|
||||
// WithMessageEvents configures the Handler to record the specified events
|
||||
// (span.AddEvent) on spans. By default only summary attributes are added at the
|
||||
// end of the request.
|
||||
//
|
||||
// Valid events are:
|
||||
// - ReadEvents: Record the number of bytes read after every http.Request.Body.Read
|
||||
// using the ReadBytesKey
|
||||
// - WriteEvents: Record the number of bytes written after every http.ResponeWriter.Write
|
||||
// using the WriteBytesKey
|
||||
func WithMessageEvents(events ...Event) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
for _, e := range events {
|
||||
switch e {
|
||||
case ReadEvents:
|
||||
c.ReadEvent = true
|
||||
case WriteEvents:
|
||||
c.WriteEvent = true
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithSpanNameFormatter takes a function that will be called on every
|
||||
// request and the returned string will become the Span Name.
|
||||
//
|
||||
// When using [http.ServeMux] (or any middleware that sets the Pattern of [http.Request]),
|
||||
// the span name formatter will run twice. Once when the span is created, and
|
||||
// second time after the middleware, so the pattern can be used.
|
||||
func WithSpanNameFormatter(f func(operation string, r *http.Request) string) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.SpanNameFormatter = f
|
||||
})
|
||||
}
|
||||
|
||||
// WithClientTrace takes a function that returns client trace instance that will be
|
||||
// applied to the requests sent through the otelhttp Transport.
|
||||
func WithClientTrace(f func(context.Context) *httptrace.ClientTrace) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.ClientTrace = f
|
||||
})
|
||||
}
|
||||
|
||||
// WithServerName returns an Option that sets the name of the (virtual) server
|
||||
// handling requests.
|
||||
func WithServerName(server string) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.ServerName = server
|
||||
})
|
||||
}
|
||||
|
||||
// WithMetricAttributesFn returns an Option to set a function that maps an HTTP request to a slice of attribute.KeyValue.
|
||||
// These attributes will be included in metrics for every request.
|
||||
//
|
||||
// Deprecated: WithMetricAttributesFn is deprecated and will be removed in a
|
||||
// future release. Use [Labeler] instead.
|
||||
func WithMetricAttributesFn(metricAttributesFn func(r *http.Request) []attribute.KeyValue) Option {
|
||||
return optionFunc(func(c *config) {
|
||||
c.MetricAttributesFn = metricAttributesFn
|
||||
})
|
||||
}
|
||||
Generated
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package otelhttp provides an http.Handler and functions that are intended
|
||||
// to be used to add tracing by wrapping existing handlers.
|
||||
package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
Generated
Vendored
+217
@@ -0,0 +1,217 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/felixge/httpsnoop"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request"
|
||||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv"
|
||||
)
|
||||
|
||||
// middleware is an http middleware which wraps the next handler in a span.
|
||||
type middleware struct {
|
||||
operation string
|
||||
server string
|
||||
|
||||
tracer trace.Tracer
|
||||
propagators propagation.TextMapPropagator
|
||||
spanStartOptions []trace.SpanStartOption
|
||||
readEvent bool
|
||||
writeEvent bool
|
||||
filters []Filter
|
||||
spanNameFormatter func(string, *http.Request) string
|
||||
publicEndpointFn func(*http.Request) bool
|
||||
metricAttributesFn func(*http.Request) []attribute.KeyValue
|
||||
|
||||
semconv semconv.HTTPServer
|
||||
}
|
||||
|
||||
func defaultHandlerFormatter(operation string, _ *http.Request) string {
|
||||
return operation
|
||||
}
|
||||
|
||||
// NewHandler wraps the passed handler in a span named after the operation and
|
||||
// enriches it with metrics.
|
||||
func NewHandler(handler http.Handler, operation string, opts ...Option) http.Handler {
|
||||
return NewMiddleware(operation, opts...)(handler)
|
||||
}
|
||||
|
||||
// NewMiddleware returns a tracing and metrics instrumentation middleware.
|
||||
// The handler returned by the middleware wraps a handler
|
||||
// in a span named after the operation and enriches it with metrics.
|
||||
func NewMiddleware(operation string, opts ...Option) func(http.Handler) http.Handler {
|
||||
h := middleware{
|
||||
operation: operation,
|
||||
}
|
||||
|
||||
defaultOpts := []Option{
|
||||
WithSpanOptions(trace.WithSpanKind(trace.SpanKindServer)),
|
||||
WithSpanNameFormatter(defaultHandlerFormatter),
|
||||
}
|
||||
|
||||
c := newConfig(append(defaultOpts, opts...)...)
|
||||
h.configure(c)
|
||||
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h.serveHTTP(w, r, next)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (h *middleware) configure(c *config) {
|
||||
h.tracer = c.Tracer
|
||||
h.propagators = c.Propagators
|
||||
h.spanStartOptions = c.SpanStartOptions
|
||||
h.readEvent = c.ReadEvent
|
||||
h.writeEvent = c.WriteEvent
|
||||
h.filters = c.Filters
|
||||
h.spanNameFormatter = c.SpanNameFormatter
|
||||
h.publicEndpointFn = c.PublicEndpointFn
|
||||
h.server = c.ServerName
|
||||
h.semconv = semconv.NewHTTPServer(c.Meter)
|
||||
h.metricAttributesFn = c.MetricAttributesFn
|
||||
}
|
||||
|
||||
// serveHTTP sets up tracing and calls the given next http.Handler with the span
|
||||
// context injected into the request context.
|
||||
func (h *middleware) serveHTTP(w http.ResponseWriter, r *http.Request, next http.Handler) {
|
||||
requestStartTime := time.Now()
|
||||
for _, f := range h.filters {
|
||||
if !f(r) {
|
||||
// Simply pass through to the handler if a filter rejects the request
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
ctx := h.propagators.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||
opts := []trace.SpanStartOption{
|
||||
trace.WithAttributes(h.semconv.RequestTraceAttrs(h.server, r, semconv.RequestTraceAttrsOpts{})...),
|
||||
}
|
||||
|
||||
opts = append(opts, h.spanStartOptions...)
|
||||
if h.publicEndpointFn != nil && h.publicEndpointFn(r.WithContext(ctx)) {
|
||||
opts = append(opts, trace.WithNewRoot())
|
||||
// Linking incoming span context if any for public endpoint.
|
||||
if s := trace.SpanContextFromContext(ctx); s.IsValid() && s.IsRemote() {
|
||||
opts = append(opts, trace.WithLinks(trace.Link{SpanContext: s}))
|
||||
}
|
||||
}
|
||||
|
||||
tracer := h.tracer
|
||||
|
||||
if tracer == nil {
|
||||
if span := trace.SpanFromContext(r.Context()); span.SpanContext().IsValid() {
|
||||
tracer = newTracer(span.TracerProvider())
|
||||
} else {
|
||||
tracer = newTracer(otel.GetTracerProvider())
|
||||
}
|
||||
}
|
||||
|
||||
if startTime := StartTimeFromContext(ctx); !startTime.IsZero() {
|
||||
opts = append(opts, trace.WithTimestamp(startTime))
|
||||
requestStartTime = startTime
|
||||
}
|
||||
|
||||
ctx, span := tracer.Start(ctx, h.spanNameFormatter(h.operation, r), opts...)
|
||||
defer span.End()
|
||||
|
||||
readRecordFunc := func(int64) {}
|
||||
if h.readEvent {
|
||||
readRecordFunc = func(n int64) {
|
||||
span.AddEvent("read", trace.WithAttributes(ReadBytesKey.Int64(n)))
|
||||
}
|
||||
}
|
||||
|
||||
// if request body is nil or NoBody, we don't want to mutate the body as it
|
||||
// will affect the identity of it in an unforeseeable way because we assert
|
||||
// ReadCloser fulfills a certain interface and it is indeed nil or NoBody.
|
||||
bw := request.NewBodyWrapper(r.Body, readRecordFunc)
|
||||
if r.Body != nil && r.Body != http.NoBody {
|
||||
r.Body = bw
|
||||
}
|
||||
|
||||
writeRecordFunc := func(int64) {}
|
||||
if h.writeEvent {
|
||||
writeRecordFunc = func(n int64) {
|
||||
span.AddEvent("write", trace.WithAttributes(WroteBytesKey.Int64(n)))
|
||||
}
|
||||
}
|
||||
|
||||
rww := request.NewRespWriterWrapper(w, writeRecordFunc)
|
||||
|
||||
// Wrap w to use our ResponseWriter methods while also exposing
|
||||
// other interfaces that w may implement (http.CloseNotifier,
|
||||
// http.Flusher, http.Hijacker, http.Pusher, io.ReaderFrom).
|
||||
|
||||
w = httpsnoop.Wrap(w, httpsnoop.Hooks{
|
||||
Header: func(httpsnoop.HeaderFunc) httpsnoop.HeaderFunc {
|
||||
return rww.Header
|
||||
},
|
||||
Write: func(httpsnoop.WriteFunc) httpsnoop.WriteFunc {
|
||||
return rww.Write
|
||||
},
|
||||
WriteHeader: func(httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {
|
||||
return rww.WriteHeader
|
||||
},
|
||||
Flush: func(httpsnoop.FlushFunc) httpsnoop.FlushFunc {
|
||||
return rww.Flush
|
||||
},
|
||||
})
|
||||
|
||||
labeler, found := LabelerFromContext(ctx)
|
||||
if !found {
|
||||
ctx = ContextWithLabeler(ctx, labeler)
|
||||
}
|
||||
|
||||
r = r.WithContext(ctx)
|
||||
next.ServeHTTP(w, r)
|
||||
|
||||
if r.Pattern != "" {
|
||||
span.SetName(h.spanNameFormatter(h.operation, r))
|
||||
}
|
||||
|
||||
statusCode := rww.StatusCode()
|
||||
bytesWritten := rww.BytesWritten()
|
||||
span.SetStatus(h.semconv.Status(statusCode))
|
||||
bytesRead := bw.BytesRead()
|
||||
span.SetAttributes(h.semconv.ResponseTraceAttrs(semconv.ResponseTelemetry{
|
||||
StatusCode: statusCode,
|
||||
ReadBytes: bytesRead,
|
||||
ReadError: bw.Error(),
|
||||
WriteBytes: bytesWritten,
|
||||
WriteError: rww.Error(),
|
||||
})...)
|
||||
|
||||
h.semconv.RecordMetrics(ctx, semconv.ServerMetricData{
|
||||
ServerName: h.server,
|
||||
ResponseSize: bytesWritten,
|
||||
MetricAttributes: semconv.MetricAttributes{
|
||||
Req: r,
|
||||
StatusCode: statusCode,
|
||||
AdditionalAttributes: append(labeler.Get(), h.metricAttributesFromRequest(r)...),
|
||||
},
|
||||
MetricData: semconv.MetricData{
|
||||
RequestSize: bytesRead,
|
||||
RequestDuration: time.Since(requestStartTime),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (h *middleware) metricAttributesFromRequest(r *http.Request) []attribute.KeyValue {
|
||||
var attributeForRequest []attribute.KeyValue
|
||||
if h.metricAttributesFn != nil {
|
||||
attributeForRequest = h.metricAttributesFn(r)
|
||||
}
|
||||
return attributeForRequest
|
||||
}
|
||||
Generated
Vendored
+80
@@ -0,0 +1,80 @@
|
||||
// Code generated by gotmpl. DO NOT MODIFY.
|
||||
// source: internal/shared/request/body_wrapper.go.tmpl
|
||||
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package request provides types and functionality to handle HTTP request
|
||||
// handling.
|
||||
package request // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request"
|
||||
|
||||
import (
|
||||
"io"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var _ io.ReadCloser = &BodyWrapper{}
|
||||
|
||||
// BodyWrapper wraps a http.Request.Body (an io.ReadCloser) to track the number
|
||||
// of bytes read and the last error.
|
||||
type BodyWrapper struct {
|
||||
io.ReadCloser
|
||||
OnRead func(n int64) // must not be nil
|
||||
|
||||
mu sync.Mutex
|
||||
read int64
|
||||
err error
|
||||
}
|
||||
|
||||
// NewBodyWrapper creates a new BodyWrapper.
|
||||
//
|
||||
// The onRead attribute is a callback that will be called every time the data
|
||||
// is read, with the number of bytes being read.
|
||||
func NewBodyWrapper(body io.ReadCloser, onRead func(int64)) *BodyWrapper {
|
||||
return &BodyWrapper{
|
||||
ReadCloser: body,
|
||||
OnRead: onRead,
|
||||
}
|
||||
}
|
||||
|
||||
// Read reads the data from the io.ReadCloser, and stores the number of bytes
|
||||
// read and the error.
|
||||
func (w *BodyWrapper) Read(b []byte) (int, error) {
|
||||
n, err := w.ReadCloser.Read(b)
|
||||
n1 := int64(n)
|
||||
|
||||
w.updateReadData(n1, err)
|
||||
w.OnRead(n1)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (w *BodyWrapper) updateReadData(n int64, err error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
|
||||
w.read += n
|
||||
if err != nil {
|
||||
w.err = err
|
||||
}
|
||||
}
|
||||
|
||||
// Close closes the io.ReadCloser.
|
||||
func (w *BodyWrapper) Close() error {
|
||||
return w.ReadCloser.Close()
|
||||
}
|
||||
|
||||
// BytesRead returns the number of bytes read up to this point.
|
||||
func (w *BodyWrapper) BytesRead() int64 {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
|
||||
return w.read
|
||||
}
|
||||
|
||||
// Error returns the last error.
|
||||
func (w *BodyWrapper) Error() error {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
|
||||
return w.err
|
||||
}
|
||||
Generated
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package request // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request"
|
||||
|
||||
// Generate request package:
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/request/body_wrapper.go.tmpl "--data={}" --out=body_wrapper.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/request/body_wrapper_test.go.tmpl "--data={}" --out=body_wrapper_test.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/request/resp_writer_wrapper.go.tmpl "--data={}" --out=resp_writer_wrapper.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/request/resp_writer_wrapper_test.go.tmpl "--data={}" --out=resp_writer_wrapper_test.go
|
||||
Generated
Vendored
+129
@@ -0,0 +1,129 @@
|
||||
// Code generated by gotmpl. DO NOT MODIFY.
|
||||
// source: internal/shared/request/resp_writer_wrapper.go.tmpl
|
||||
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package request // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request"
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var _ http.ResponseWriter = &RespWriterWrapper{}
|
||||
|
||||
// RespWriterWrapper wraps a http.ResponseWriter in order to track the number of
|
||||
// bytes written, the last error, and to catch the first written statusCode.
|
||||
// TODO: The wrapped http.ResponseWriter doesn't implement any of the optional
|
||||
// types (http.Hijacker, http.Pusher, http.CloseNotifier, etc)
|
||||
// that may be useful when using it in real life situations.
|
||||
type RespWriterWrapper struct {
|
||||
http.ResponseWriter
|
||||
OnWrite func(n int64) // must not be nil
|
||||
|
||||
mu sync.RWMutex
|
||||
written int64
|
||||
statusCode int
|
||||
err error
|
||||
wroteHeader bool
|
||||
}
|
||||
|
||||
// NewRespWriterWrapper creates a new RespWriterWrapper.
|
||||
//
|
||||
// The onWrite attribute is a callback that will be called every time the data
|
||||
// is written, with the number of bytes that were written.
|
||||
func NewRespWriterWrapper(w http.ResponseWriter, onWrite func(int64)) *RespWriterWrapper {
|
||||
return &RespWriterWrapper{
|
||||
ResponseWriter: w,
|
||||
OnWrite: onWrite,
|
||||
statusCode: http.StatusOK, // default status code in case the Handler doesn't write anything
|
||||
}
|
||||
}
|
||||
|
||||
// Write writes the bytes array into the [ResponseWriter], and tracks the
|
||||
// number of bytes written and last error.
|
||||
func (w *RespWriterWrapper) Write(p []byte) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
|
||||
if !w.wroteHeader {
|
||||
w.writeHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
n, err := w.ResponseWriter.Write(p)
|
||||
n1 := int64(n)
|
||||
w.OnWrite(n1)
|
||||
w.written += n1
|
||||
w.err = err
|
||||
return n, err
|
||||
}
|
||||
|
||||
// WriteHeader persists initial statusCode for span attribution.
|
||||
// All calls to WriteHeader will be propagated to the underlying ResponseWriter
|
||||
// and will persist the statusCode from the first call (except for informational response status codes).
|
||||
// Blocking consecutive calls to WriteHeader alters expected behavior and will
|
||||
// remove warning logs from net/http where developers will notice incorrect handler implementations.
|
||||
func (w *RespWriterWrapper) WriteHeader(statusCode int) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
|
||||
w.writeHeader(statusCode)
|
||||
}
|
||||
|
||||
// writeHeader persists the status code for span attribution, and propagates
|
||||
// the call to the underlying ResponseWriter.
|
||||
// It does not acquire a lock, and therefore assumes that is being handled by a
|
||||
// parent method.
|
||||
func (w *RespWriterWrapper) writeHeader(statusCode int) {
|
||||
if !w.wroteHeader {
|
||||
// Ignore informational response status codes.
|
||||
// Based on https://github.com/golang/go/blob/go1.24.1/src/net/http/server.go#L1216
|
||||
if statusCode >= 100 && statusCode <= 199 && statusCode != http.StatusSwitchingProtocols {
|
||||
w.ResponseWriter.WriteHeader(statusCode)
|
||||
return
|
||||
}
|
||||
|
||||
w.wroteHeader = true
|
||||
w.statusCode = statusCode
|
||||
}
|
||||
w.ResponseWriter.WriteHeader(statusCode)
|
||||
}
|
||||
|
||||
// Flush implements [http.Flusher].
|
||||
func (w *RespWriterWrapper) Flush() {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
|
||||
if !w.wroteHeader {
|
||||
w.writeHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
if f, ok := w.ResponseWriter.(http.Flusher); ok {
|
||||
f.Flush()
|
||||
}
|
||||
}
|
||||
|
||||
// BytesWritten returns the number of bytes written.
|
||||
func (w *RespWriterWrapper) BytesWritten() int64 {
|
||||
w.mu.RLock()
|
||||
defer w.mu.RUnlock()
|
||||
|
||||
return w.written
|
||||
}
|
||||
|
||||
// StatusCode returns the HTTP status code that was sent.
|
||||
func (w *RespWriterWrapper) StatusCode() int {
|
||||
w.mu.RLock()
|
||||
defer w.mu.RUnlock()
|
||||
|
||||
return w.statusCode
|
||||
}
|
||||
|
||||
// Error returns the last error.
|
||||
func (w *RespWriterWrapper) Error() error {
|
||||
w.mu.RLock()
|
||||
defer w.mu.RUnlock()
|
||||
|
||||
return w.err
|
||||
}
|
||||
Generated
Vendored
+291
@@ -0,0 +1,291 @@
|
||||
// Code generated by gotmpl. DO NOT MODIFY.
|
||||
// source: internal/shared/semconv/client.go.tmpl
|
||||
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package semconv provides OpenTelemetry semantic convention types and
|
||||
// functionality.
|
||||
package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
"go.opentelemetry.io/otel/semconv/v1.40.0/httpconv"
|
||||
)
|
||||
|
||||
type HTTPClient struct {
|
||||
requestBodySize httpconv.ClientRequestBodySize
|
||||
requestDuration httpconv.ClientRequestDuration
|
||||
}
|
||||
|
||||
func NewHTTPClient(meter metric.Meter) HTTPClient {
|
||||
client := HTTPClient{}
|
||||
|
||||
var err error
|
||||
client.requestBodySize, err = httpconv.NewClientRequestBodySize(meter)
|
||||
handleErr(err)
|
||||
|
||||
client.requestDuration, err = httpconv.NewClientRequestDuration(
|
||||
meter,
|
||||
metric.WithExplicitBucketBoundaries(0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10),
|
||||
)
|
||||
handleErr(err)
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
func (n HTTPClient) Status(code int) (codes.Code, string) {
|
||||
if code < 100 || code >= 600 {
|
||||
return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code)
|
||||
}
|
||||
if code >= 400 {
|
||||
return codes.Error, ""
|
||||
}
|
||||
return codes.Unset, ""
|
||||
}
|
||||
|
||||
// RequestTraceAttrs returns trace attributes for an HTTP request made by a client.
|
||||
func (n HTTPClient) RequestTraceAttrs(req *http.Request) []attribute.KeyValue {
|
||||
/*
|
||||
below attributes are returned:
|
||||
- http.request.method
|
||||
- http.request.method.original
|
||||
- url.full
|
||||
- server.address
|
||||
- server.port
|
||||
- network.protocol.name
|
||||
- network.protocol.version
|
||||
*/
|
||||
numOfAttributes := 3 // URL, server address, proto, and method.
|
||||
|
||||
var urlHost string
|
||||
if req.URL != nil {
|
||||
urlHost = req.URL.Host
|
||||
}
|
||||
var requestHost string
|
||||
var requestPort int
|
||||
for _, hostport := range []string{urlHost, req.Header.Get("Host")} {
|
||||
requestHost, requestPort = SplitHostPort(hostport)
|
||||
if requestHost != "" || requestPort > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
eligiblePort := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort)
|
||||
if eligiblePort > 0 {
|
||||
numOfAttributes++
|
||||
}
|
||||
useragent := req.UserAgent()
|
||||
if useragent != "" {
|
||||
numOfAttributes++
|
||||
}
|
||||
|
||||
protoName, protoVersion := netProtocol(req.Proto)
|
||||
if protoName != "" && protoName != "http" {
|
||||
numOfAttributes++
|
||||
}
|
||||
if protoVersion != "" {
|
||||
numOfAttributes++
|
||||
}
|
||||
|
||||
method, originalMethod := n.method(req.Method)
|
||||
if originalMethod != (attribute.KeyValue{}) {
|
||||
numOfAttributes++
|
||||
}
|
||||
|
||||
attrs := make([]attribute.KeyValue, 0, numOfAttributes)
|
||||
|
||||
attrs = append(attrs, method)
|
||||
if originalMethod != (attribute.KeyValue{}) {
|
||||
attrs = append(attrs, originalMethod)
|
||||
}
|
||||
|
||||
var u string
|
||||
if req.URL != nil {
|
||||
// Remove any username/password info that may be in the URL.
|
||||
userinfo := req.URL.User
|
||||
req.URL.User = nil
|
||||
u = req.URL.String()
|
||||
// Restore any username/password info that was removed.
|
||||
req.URL.User = userinfo
|
||||
}
|
||||
attrs = append(attrs, semconv.URLFull(u))
|
||||
|
||||
attrs = append(attrs, semconv.ServerAddress(requestHost))
|
||||
if eligiblePort > 0 {
|
||||
attrs = append(attrs, semconv.ServerPort(eligiblePort))
|
||||
}
|
||||
|
||||
if protoName != "" && protoName != "http" {
|
||||
attrs = append(attrs, semconv.NetworkProtocolName(protoName))
|
||||
}
|
||||
if protoVersion != "" {
|
||||
attrs = append(attrs, semconv.NetworkProtocolVersion(protoVersion))
|
||||
}
|
||||
|
||||
return attrs
|
||||
}
|
||||
|
||||
// ResponseTraceAttrs returns trace attributes for an HTTP response made by a client.
|
||||
func (n HTTPClient) ResponseTraceAttrs(resp *http.Response) []attribute.KeyValue {
|
||||
/*
|
||||
below attributes are returned:
|
||||
- http.response.status_code
|
||||
- error.type
|
||||
*/
|
||||
var count int
|
||||
if resp.StatusCode > 0 {
|
||||
count++
|
||||
}
|
||||
|
||||
if isErrorStatusCode(resp.StatusCode) {
|
||||
count++
|
||||
}
|
||||
|
||||
attrs := make([]attribute.KeyValue, 0, count)
|
||||
if resp.StatusCode > 0 {
|
||||
attrs = append(attrs, semconv.HTTPResponseStatusCode(resp.StatusCode))
|
||||
}
|
||||
|
||||
if isErrorStatusCode(resp.StatusCode) {
|
||||
errorType := strconv.Itoa(resp.StatusCode)
|
||||
attrs = append(attrs, semconv.ErrorTypeKey.String(errorType))
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
func (n HTTPClient) method(method string) (attribute.KeyValue, attribute.KeyValue) {
|
||||
if method == "" {
|
||||
return semconv.HTTPRequestMethodGet, attribute.KeyValue{}
|
||||
}
|
||||
if attr, ok := methodLookup[method]; ok {
|
||||
return attr, attribute.KeyValue{}
|
||||
}
|
||||
|
||||
orig := semconv.HTTPRequestMethodOriginal(method)
|
||||
if attr, ok := methodLookup[strings.ToUpper(method)]; ok {
|
||||
return attr, orig
|
||||
}
|
||||
return semconv.HTTPRequestMethodGet, orig
|
||||
}
|
||||
|
||||
func (n HTTPClient) MetricAttributes(req *http.Request, statusCode int, additionalAttributes []attribute.KeyValue) []attribute.KeyValue {
|
||||
num := len(additionalAttributes) + 2
|
||||
var h string
|
||||
if req.URL != nil {
|
||||
h = req.URL.Host
|
||||
}
|
||||
var requestHost string
|
||||
var requestPort int
|
||||
for _, hostport := range []string{h, req.Header.Get("Host")} {
|
||||
requestHost, requestPort = SplitHostPort(hostport)
|
||||
if requestHost != "" || requestPort > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
port := requiredHTTPPort(req.URL != nil && req.URL.Scheme == "https", requestPort)
|
||||
if port > 0 {
|
||||
num++
|
||||
}
|
||||
|
||||
protoName, protoVersion := netProtocol(req.Proto)
|
||||
if protoName != "" {
|
||||
num++
|
||||
}
|
||||
if protoVersion != "" {
|
||||
num++
|
||||
}
|
||||
|
||||
if statusCode > 0 {
|
||||
num++
|
||||
}
|
||||
|
||||
attributes := slices.Grow(additionalAttributes, num)
|
||||
attributes = append(attributes,
|
||||
semconv.HTTPRequestMethodKey.String(standardizeHTTPMethod(req.Method)),
|
||||
semconv.ServerAddress(requestHost),
|
||||
n.scheme(req),
|
||||
)
|
||||
|
||||
if port > 0 {
|
||||
attributes = append(attributes, semconv.ServerPort(port))
|
||||
}
|
||||
if protoName != "" {
|
||||
attributes = append(attributes, semconv.NetworkProtocolName(protoName))
|
||||
}
|
||||
if protoVersion != "" {
|
||||
attributes = append(attributes, semconv.NetworkProtocolVersion(protoVersion))
|
||||
}
|
||||
|
||||
if statusCode > 0 {
|
||||
attributes = append(attributes, semconv.HTTPResponseStatusCode(statusCode))
|
||||
}
|
||||
return attributes
|
||||
}
|
||||
|
||||
type MetricOpts struct {
|
||||
measurement metric.MeasurementOption
|
||||
addOptions metric.AddOption
|
||||
}
|
||||
|
||||
func (o MetricOpts) MeasurementOption() metric.MeasurementOption {
|
||||
return o.measurement
|
||||
}
|
||||
|
||||
func (o MetricOpts) AddOptions() metric.AddOption {
|
||||
return o.addOptions
|
||||
}
|
||||
|
||||
func (n HTTPClient) MetricOptions(ma MetricAttributes) MetricOpts {
|
||||
attributes := n.MetricAttributes(ma.Req, ma.StatusCode, ma.AdditionalAttributes)
|
||||
set := metric.WithAttributeSet(attribute.NewSet(attributes...))
|
||||
|
||||
return MetricOpts{
|
||||
measurement: set,
|
||||
addOptions: set,
|
||||
}
|
||||
}
|
||||
|
||||
func (n HTTPClient) RecordMetrics(ctx context.Context, md MetricData, opts MetricOpts) {
|
||||
recordOpts := metricRecordOptionPool.Get().(*[]metric.RecordOption)
|
||||
defer func() {
|
||||
*recordOpts = (*recordOpts)[:0]
|
||||
metricRecordOptionPool.Put(recordOpts)
|
||||
}()
|
||||
*recordOpts = append(*recordOpts, opts.MeasurementOption())
|
||||
|
||||
n.requestBodySize.Inst().Record(ctx, md.RequestSize, *recordOpts...)
|
||||
n.requestDuration.Inst().Record(ctx, durationToSeconds(md.RequestDuration), *recordOpts...)
|
||||
}
|
||||
|
||||
// TraceAttributes returns attributes for httptrace.
|
||||
func (n HTTPClient) TraceAttributes(host string) []attribute.KeyValue {
|
||||
return []attribute.KeyValue{
|
||||
semconv.ServerAddress(host),
|
||||
}
|
||||
}
|
||||
|
||||
func (n HTTPClient) scheme(req *http.Request) attribute.KeyValue {
|
||||
if req.URL != nil && req.URL.Scheme != "" {
|
||||
return semconv.URLScheme(req.URL.Scheme)
|
||||
}
|
||||
if req.TLS != nil {
|
||||
return semconv.URLScheme("https")
|
||||
}
|
||||
return semconv.URLScheme("http")
|
||||
}
|
||||
|
||||
func isErrorStatusCode(code int) bool {
|
||||
return code >= 400 || code < 100
|
||||
}
|
||||
Generated
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv"
|
||||
|
||||
// Generate semconv package:
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconv/bench_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=bench_test.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconv/common_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=common_test.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconv/server.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=server.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconv/server_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=server_test.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconv/client.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=client.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconv/client_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=client_test.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconv/httpconvtest_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=httpconvtest_test.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconv/util.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=util.go
|
||||
//go:generate gotmpl --body=../../../../../../internal/shared/semconv/util_test.go.tmpl "--data={ \"pkg\": \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\" }" --out=util_test.go
|
||||
Generated
Vendored
+396
@@ -0,0 +1,396 @@
|
||||
// Code generated by gotmpl. DO NOT MODIFY.
|
||||
// source: internal/shared/semconv/server.go.tmpl
|
||||
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package semconv provides OpenTelemetry semantic convention types and
|
||||
// functionality.
|
||||
package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
"go.opentelemetry.io/otel/semconv/v1.40.0/httpconv"
|
||||
)
|
||||
|
||||
type RequestTraceAttrsOpts struct {
|
||||
// If set, this is used as value for the "http.client_ip" attribute.
|
||||
HTTPClientIP string
|
||||
}
|
||||
|
||||
type ResponseTelemetry struct {
|
||||
StatusCode int
|
||||
ReadBytes int64
|
||||
ReadError error
|
||||
WriteBytes int64
|
||||
WriteError error
|
||||
}
|
||||
|
||||
type HTTPServer struct {
|
||||
requestBodySizeHistogram httpconv.ServerRequestBodySize
|
||||
responseBodySizeHistogram httpconv.ServerResponseBodySize
|
||||
requestDurationHistogram httpconv.ServerRequestDuration
|
||||
}
|
||||
|
||||
func NewHTTPServer(meter metric.Meter) HTTPServer {
|
||||
server := HTTPServer{}
|
||||
|
||||
var err error
|
||||
server.requestBodySizeHistogram, err = httpconv.NewServerRequestBodySize(meter)
|
||||
handleErr(err)
|
||||
|
||||
server.responseBodySizeHistogram, err = httpconv.NewServerResponseBodySize(meter)
|
||||
handleErr(err)
|
||||
|
||||
server.requestDurationHistogram, err = httpconv.NewServerRequestDuration(
|
||||
meter,
|
||||
metric.WithExplicitBucketBoundaries(
|
||||
0.005, 0.01, 0.025, 0.05, 0.075, 0.1,
|
||||
0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10,
|
||||
),
|
||||
)
|
||||
handleErr(err)
|
||||
return server
|
||||
}
|
||||
|
||||
// Status returns a span status code and message for an HTTP status code
|
||||
// value returned by a server. Status codes in the 400-499 range are not
|
||||
// returned as errors.
|
||||
func (n HTTPServer) Status(code int) (codes.Code, string) {
|
||||
if code < 100 || code >= 600 {
|
||||
return codes.Error, fmt.Sprintf("Invalid HTTP status code %d", code)
|
||||
}
|
||||
if code >= 500 {
|
||||
return codes.Error, ""
|
||||
}
|
||||
return codes.Unset, ""
|
||||
}
|
||||
|
||||
// RequestTraceAttrs returns trace attributes for an HTTP request received by a
|
||||
// server.
|
||||
//
|
||||
// The server must be the primary server name if it is known. For example this
|
||||
// would be the ServerName directive
|
||||
// (https://httpd.apache.org/docs/2.4/mod/core.html#servername) for an Apache
|
||||
// server, and the server_name directive
|
||||
// (http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name) for an
|
||||
// nginx server. More generically, the primary server name would be the host
|
||||
// header value that matches the default virtual host of an HTTP server. It
|
||||
// should include the host identifier and if a port is used to route to the
|
||||
// server that port identifier should be included as an appropriate port
|
||||
// suffix.
|
||||
//
|
||||
// If the primary server name is not known, server should be an empty string.
|
||||
// The req Host will be used to determine the server instead.
|
||||
func (n HTTPServer) RequestTraceAttrs(server string, req *http.Request, opts RequestTraceAttrsOpts) []attribute.KeyValue {
|
||||
count := 3 // ServerAddress, Method, Scheme
|
||||
|
||||
var host string
|
||||
var p int
|
||||
if server == "" {
|
||||
host, p = SplitHostPort(req.Host)
|
||||
} else {
|
||||
// Prioritize the primary server name.
|
||||
host, p = SplitHostPort(server)
|
||||
if p < 0 {
|
||||
_, p = SplitHostPort(req.Host)
|
||||
}
|
||||
}
|
||||
|
||||
hostPort := requiredHTTPPort(req.TLS != nil, p)
|
||||
if hostPort > 0 {
|
||||
count++
|
||||
}
|
||||
|
||||
method, methodOriginal := n.method(req.Method)
|
||||
if methodOriginal != (attribute.KeyValue{}) {
|
||||
count++
|
||||
}
|
||||
|
||||
scheme := n.scheme(req.TLS != nil)
|
||||
|
||||
peer, peerPort := SplitHostPort(req.RemoteAddr)
|
||||
if peer != "" {
|
||||
// The Go HTTP server sets RemoteAddr to "IP:port", this will not be a
|
||||
// file-path that would be interpreted with a sock family.
|
||||
count++
|
||||
if peerPort > 0 {
|
||||
count++
|
||||
}
|
||||
}
|
||||
|
||||
useragent := req.UserAgent()
|
||||
if useragent != "" {
|
||||
count++
|
||||
}
|
||||
|
||||
// For client IP, use, in order:
|
||||
// 1. The value passed in the options
|
||||
// 2. The value in the X-Forwarded-For header
|
||||
// 3. The peer address
|
||||
clientIP := opts.HTTPClientIP
|
||||
if clientIP == "" {
|
||||
clientIP = serverClientIP(req.Header.Get("X-Forwarded-For"))
|
||||
if clientIP == "" {
|
||||
clientIP = peer
|
||||
}
|
||||
}
|
||||
if clientIP != "" {
|
||||
count++
|
||||
}
|
||||
|
||||
if req.URL != nil && req.URL.Path != "" {
|
||||
count++
|
||||
}
|
||||
|
||||
protoName, protoVersion := netProtocol(req.Proto)
|
||||
if protoName != "" && protoName != "http" {
|
||||
count++
|
||||
}
|
||||
if protoVersion != "" {
|
||||
count++
|
||||
}
|
||||
|
||||
route := httpRoute(req.Pattern)
|
||||
if route != "" {
|
||||
count++
|
||||
}
|
||||
|
||||
attrs := make([]attribute.KeyValue, 0, count)
|
||||
attrs = append(attrs,
|
||||
semconv.ServerAddress(host),
|
||||
method,
|
||||
scheme,
|
||||
)
|
||||
|
||||
if hostPort > 0 {
|
||||
attrs = append(attrs, semconv.ServerPort(hostPort))
|
||||
}
|
||||
if methodOriginal != (attribute.KeyValue{}) {
|
||||
attrs = append(attrs, methodOriginal)
|
||||
}
|
||||
|
||||
if peer, peerPort := SplitHostPort(req.RemoteAddr); peer != "" {
|
||||
// The Go HTTP server sets RemoteAddr to "IP:port", this will not be a
|
||||
// file-path that would be interpreted with a sock family.
|
||||
attrs = append(attrs, semconv.NetworkPeerAddress(peer))
|
||||
if peerPort > 0 {
|
||||
attrs = append(attrs, semconv.NetworkPeerPort(peerPort))
|
||||
}
|
||||
}
|
||||
|
||||
if useragent != "" {
|
||||
attrs = append(attrs, semconv.UserAgentOriginal(useragent))
|
||||
}
|
||||
|
||||
if clientIP != "" {
|
||||
attrs = append(attrs, semconv.ClientAddress(clientIP))
|
||||
}
|
||||
|
||||
if req.URL != nil && req.URL.Path != "" {
|
||||
attrs = append(attrs, semconv.URLPath(req.URL.Path))
|
||||
}
|
||||
|
||||
if protoName != "" && protoName != "http" {
|
||||
attrs = append(attrs, semconv.NetworkProtocolName(protoName))
|
||||
}
|
||||
if protoVersion != "" {
|
||||
attrs = append(attrs, semconv.NetworkProtocolVersion(protoVersion))
|
||||
}
|
||||
|
||||
if route != "" {
|
||||
attrs = append(attrs, n.Route(route))
|
||||
}
|
||||
|
||||
return attrs
|
||||
}
|
||||
|
||||
func (s HTTPServer) NetworkTransportAttr(network string) []attribute.KeyValue {
|
||||
attr := semconv.NetworkTransportPipe
|
||||
switch network {
|
||||
case "tcp", "tcp4", "tcp6":
|
||||
attr = semconv.NetworkTransportTCP
|
||||
case "udp", "udp4", "udp6":
|
||||
attr = semconv.NetworkTransportUDP
|
||||
case "unix", "unixgram", "unixpacket":
|
||||
attr = semconv.NetworkTransportUnix
|
||||
}
|
||||
|
||||
return []attribute.KeyValue{attr}
|
||||
}
|
||||
|
||||
type ServerMetricData struct {
|
||||
ServerName string
|
||||
ResponseSize int64
|
||||
|
||||
MetricData
|
||||
MetricAttributes
|
||||
}
|
||||
|
||||
type MetricAttributes struct {
|
||||
Req *http.Request
|
||||
StatusCode int
|
||||
Route string
|
||||
AdditionalAttributes []attribute.KeyValue
|
||||
}
|
||||
|
||||
type MetricData struct {
|
||||
RequestSize int64
|
||||
RequestDuration time.Duration
|
||||
}
|
||||
|
||||
var (
|
||||
metricRecordOptionPool = &sync.Pool{
|
||||
New: func() any {
|
||||
return &[]metric.RecordOption{}
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
func (n HTTPServer) RecordMetrics(ctx context.Context, md ServerMetricData) {
|
||||
attributes := n.MetricAttributes(md.ServerName, md.Req, md.StatusCode, md.Route, md.AdditionalAttributes)
|
||||
o := metric.WithAttributeSet(attribute.NewSet(attributes...))
|
||||
recordOpts := metricRecordOptionPool.Get().(*[]metric.RecordOption)
|
||||
*recordOpts = append(*recordOpts, o)
|
||||
n.requestBodySizeHistogram.Inst().Record(ctx, md.RequestSize, *recordOpts...)
|
||||
n.responseBodySizeHistogram.Inst().Record(ctx, md.ResponseSize, *recordOpts...)
|
||||
n.requestDurationHistogram.Inst().Record(ctx, durationToSeconds(md.RequestDuration), o)
|
||||
*recordOpts = (*recordOpts)[:0]
|
||||
metricRecordOptionPool.Put(recordOpts)
|
||||
}
|
||||
|
||||
func (n HTTPServer) method(method string) (attribute.KeyValue, attribute.KeyValue) {
|
||||
if method == "" {
|
||||
return semconv.HTTPRequestMethodGet, attribute.KeyValue{}
|
||||
}
|
||||
if attr, ok := methodLookup[method]; ok {
|
||||
return attr, attribute.KeyValue{}
|
||||
}
|
||||
|
||||
orig := semconv.HTTPRequestMethodOriginal(method)
|
||||
if attr, ok := methodLookup[strings.ToUpper(method)]; ok {
|
||||
return attr, orig
|
||||
}
|
||||
return semconv.HTTPRequestMethodGet, orig
|
||||
}
|
||||
|
||||
func (n HTTPServer) scheme(https bool) attribute.KeyValue { //nolint:revive // ignore linter
|
||||
if https {
|
||||
return semconv.URLScheme("https")
|
||||
}
|
||||
return semconv.URLScheme("http")
|
||||
}
|
||||
|
||||
// ResponseTraceAttrs returns trace attributes for telemetry from an HTTP
|
||||
// response.
|
||||
//
|
||||
// If any of the fields in the ResponseTelemetry are not set the attribute will
|
||||
// be omitted.
|
||||
func (n HTTPServer) ResponseTraceAttrs(resp ResponseTelemetry) []attribute.KeyValue {
|
||||
var count int
|
||||
|
||||
if resp.ReadBytes > 0 {
|
||||
count++
|
||||
}
|
||||
if resp.WriteBytes > 0 {
|
||||
count++
|
||||
}
|
||||
if resp.StatusCode > 0 {
|
||||
count++
|
||||
}
|
||||
|
||||
attributes := make([]attribute.KeyValue, 0, count)
|
||||
|
||||
if resp.ReadBytes > 0 {
|
||||
attributes = append(attributes,
|
||||
semconv.HTTPRequestBodySize(int(resp.ReadBytes)),
|
||||
)
|
||||
}
|
||||
if resp.WriteBytes > 0 {
|
||||
attributes = append(attributes,
|
||||
semconv.HTTPResponseBodySize(int(resp.WriteBytes)),
|
||||
)
|
||||
}
|
||||
if resp.StatusCode > 0 {
|
||||
attributes = append(attributes,
|
||||
semconv.HTTPResponseStatusCode(resp.StatusCode),
|
||||
)
|
||||
}
|
||||
|
||||
return attributes
|
||||
}
|
||||
|
||||
// Route returns the attribute for the route.
|
||||
func (n HTTPServer) Route(route string) attribute.KeyValue {
|
||||
return semconv.HTTPRoute(route)
|
||||
}
|
||||
|
||||
func (n HTTPServer) MetricAttributes(server string, req *http.Request, statusCode int, route string, additionalAttributes []attribute.KeyValue) []attribute.KeyValue {
|
||||
num := len(additionalAttributes) + 3
|
||||
var host string
|
||||
var p int
|
||||
if server == "" {
|
||||
host, p = SplitHostPort(req.Host)
|
||||
} else {
|
||||
// Prioritize the primary server name.
|
||||
host, p = SplitHostPort(server)
|
||||
if p < 0 {
|
||||
_, p = SplitHostPort(req.Host)
|
||||
}
|
||||
}
|
||||
hostPort := requiredHTTPPort(req.TLS != nil, p)
|
||||
if hostPort > 0 {
|
||||
num++
|
||||
}
|
||||
protoName, protoVersion := netProtocol(req.Proto)
|
||||
if protoName != "" {
|
||||
num++
|
||||
}
|
||||
if protoVersion != "" {
|
||||
num++
|
||||
}
|
||||
|
||||
if statusCode > 0 {
|
||||
num++
|
||||
}
|
||||
|
||||
if route != "" {
|
||||
num++
|
||||
}
|
||||
|
||||
attributes := slices.Grow(additionalAttributes, num)
|
||||
attributes = append(attributes,
|
||||
semconv.HTTPRequestMethodKey.String(standardizeHTTPMethod(req.Method)),
|
||||
n.scheme(req.TLS != nil),
|
||||
semconv.ServerAddress(host))
|
||||
|
||||
if hostPort > 0 {
|
||||
attributes = append(attributes, semconv.ServerPort(hostPort))
|
||||
}
|
||||
if protoName != "" {
|
||||
attributes = append(attributes, semconv.NetworkProtocolName(protoName))
|
||||
}
|
||||
if protoVersion != "" {
|
||||
attributes = append(attributes, semconv.NetworkProtocolVersion(protoVersion))
|
||||
}
|
||||
|
||||
if statusCode > 0 {
|
||||
attributes = append(attributes, semconv.HTTPResponseStatusCode(statusCode))
|
||||
}
|
||||
|
||||
if route != "" {
|
||||
attributes = append(attributes, semconv.HTTPRoute(route))
|
||||
}
|
||||
return attributes
|
||||
}
|
||||
Server/vendor/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv/util.go
Generated
Vendored
+133
@@ -0,0 +1,133 @@
|
||||
// Code generated by gotmpl. DO NOT MODIFY.
|
||||
// source: internal/shared/semconv/util.go.tmpl
|
||||
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package semconv // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv"
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
semconvNew "go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
)
|
||||
|
||||
// SplitHostPort splits a network address hostport of the form "host",
|
||||
// "host%zone", "[host]", "[host%zone], "host:port", "host%zone:port",
|
||||
// "[host]:port", "[host%zone]:port", or ":port" into host or host%zone and
|
||||
// port.
|
||||
//
|
||||
// An empty host is returned if it is not provided or unparsable. A negative
|
||||
// port is returned if it is not provided or unparsable.
|
||||
func SplitHostPort(hostport string) (host string, port int) {
|
||||
port = -1
|
||||
|
||||
if strings.HasPrefix(hostport, "[") {
|
||||
addrEnd := strings.LastIndexByte(hostport, ']')
|
||||
if addrEnd < 0 {
|
||||
// Invalid hostport.
|
||||
return
|
||||
}
|
||||
if i := strings.LastIndexByte(hostport[addrEnd:], ':'); i < 0 {
|
||||
host = hostport[1:addrEnd]
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if i := strings.LastIndexByte(hostport, ':'); i < 0 {
|
||||
host = hostport
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
host, pStr, err := net.SplitHostPort(hostport)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
p, err := strconv.ParseUint(pStr, 10, 16)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
return host, int(p) //nolint:gosec // Byte size checked 16 above.
|
||||
}
|
||||
|
||||
func requiredHTTPPort(https bool, port int) int { //nolint:revive // ignore linter
|
||||
if https {
|
||||
if port > 0 && port != 443 {
|
||||
return port
|
||||
}
|
||||
} else {
|
||||
if port > 0 && port != 80 {
|
||||
return port
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func serverClientIP(xForwardedFor string) string {
|
||||
if idx := strings.IndexByte(xForwardedFor, ','); idx >= 0 {
|
||||
xForwardedFor = xForwardedFor[:idx]
|
||||
}
|
||||
return xForwardedFor
|
||||
}
|
||||
|
||||
func httpRoute(pattern string) string {
|
||||
if idx := strings.IndexByte(pattern, '/'); idx >= 0 {
|
||||
return pattern[idx:]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func netProtocol(proto string) (name string, version string) {
|
||||
name, version, _ = strings.Cut(proto, "/")
|
||||
switch name {
|
||||
case "HTTP":
|
||||
name = "http"
|
||||
case "QUIC":
|
||||
name = "quic"
|
||||
case "SPDY":
|
||||
name = "spdy"
|
||||
default:
|
||||
name = strings.ToLower(name)
|
||||
}
|
||||
return name, version
|
||||
}
|
||||
|
||||
var methodLookup = map[string]attribute.KeyValue{
|
||||
http.MethodConnect: semconvNew.HTTPRequestMethodConnect,
|
||||
http.MethodDelete: semconvNew.HTTPRequestMethodDelete,
|
||||
http.MethodGet: semconvNew.HTTPRequestMethodGet,
|
||||
http.MethodHead: semconvNew.HTTPRequestMethodHead,
|
||||
http.MethodOptions: semconvNew.HTTPRequestMethodOptions,
|
||||
http.MethodPatch: semconvNew.HTTPRequestMethodPatch,
|
||||
http.MethodPost: semconvNew.HTTPRequestMethodPost,
|
||||
http.MethodPut: semconvNew.HTTPRequestMethodPut,
|
||||
http.MethodTrace: semconvNew.HTTPRequestMethodTrace,
|
||||
}
|
||||
|
||||
func handleErr(err error) {
|
||||
if err != nil {
|
||||
otel.Handle(err)
|
||||
}
|
||||
}
|
||||
|
||||
func standardizeHTTPMethod(method string) string {
|
||||
method = strings.ToUpper(method)
|
||||
switch method {
|
||||
case http.MethodConnect, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPatch, http.MethodPost, http.MethodPut, http.MethodTrace:
|
||||
default:
|
||||
method = "_OTHER"
|
||||
}
|
||||
return method
|
||||
}
|
||||
|
||||
func durationToSeconds(d time.Duration) float64 {
|
||||
// Use floating point division here for higher precision (instead of Seconds method).
|
||||
return float64(d) / float64(time.Second)
|
||||
}
|
||||
Generated
Vendored
+58
@@ -0,0 +1,58 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
)
|
||||
|
||||
// Labeler is used to allow instrumented HTTP handlers to add custom attributes to
|
||||
// the metrics recorded by the net/http instrumentation.
|
||||
type Labeler struct {
|
||||
mu sync.Mutex
|
||||
attributes []attribute.KeyValue
|
||||
}
|
||||
|
||||
// Add attributes to a Labeler.
|
||||
func (l *Labeler) Add(ls ...attribute.KeyValue) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.attributes = append(l.attributes, ls...)
|
||||
}
|
||||
|
||||
// Get returns a copy of the attributes added to the Labeler.
|
||||
func (l *Labeler) Get() []attribute.KeyValue {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
ret := make([]attribute.KeyValue, len(l.attributes))
|
||||
copy(ret, l.attributes)
|
||||
return ret
|
||||
}
|
||||
|
||||
type labelerContextKeyType int
|
||||
|
||||
const labelerContextKey labelerContextKeyType = 0
|
||||
|
||||
// ContextWithLabeler returns a new context with the provided Labeler instance.
|
||||
// Attributes added to the specified labeler will be injected into metrics
|
||||
// emitted by the instrumentation. Only one labeller can be injected into the
|
||||
// context. Injecting it multiple times will override the previous calls.
|
||||
func ContextWithLabeler(parent context.Context, l *Labeler) context.Context {
|
||||
return context.WithValue(parent, labelerContextKey, l)
|
||||
}
|
||||
|
||||
// LabelerFromContext retrieves a Labeler instance from the provided context if
|
||||
// one is available. If no Labeler was found in the provided context a new, empty
|
||||
// Labeler is returned and the second return value is false. In this case it is
|
||||
// safe to use the Labeler but any attributes added to it will not be used.
|
||||
func LabelerFromContext(ctx context.Context) (*Labeler, bool) {
|
||||
l, ok := ctx.Value(labelerContextKey).(*Labeler)
|
||||
if !ok {
|
||||
l = &Labeler{}
|
||||
}
|
||||
return l, ok
|
||||
}
|
||||
Generated
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type startTimeContextKeyType int
|
||||
|
||||
const startTimeContextKey startTimeContextKeyType = 0
|
||||
|
||||
// ContextWithStartTime returns a new context with the provided start time. The
|
||||
// start time will be used for metrics and traces emitted by the
|
||||
// instrumentation. Only one labeller can be injected into the context.
|
||||
// Injecting it multiple times will override the previous calls.
|
||||
func ContextWithStartTime(parent context.Context, start time.Time) context.Context {
|
||||
return context.WithValue(parent, startTimeContextKey, start)
|
||||
}
|
||||
|
||||
// StartTimeFromContext retrieves a time.Time from the provided context if one
|
||||
// is available. If no start time was found in the provided context, a new,
|
||||
// zero start time is returned and the second return value is false.
|
||||
func StartTimeFromContext(ctx context.Context) time.Time {
|
||||
t, _ := ctx.Value(startTimeContextKey).(time.Time)
|
||||
return t
|
||||
}
|
||||
Generated
Vendored
+274
@@ -0,0 +1,274 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptrace"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
otelsemconv "go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/request"
|
||||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp/internal/semconv"
|
||||
)
|
||||
|
||||
// Transport implements the http.RoundTripper interface and wraps
|
||||
// outbound HTTP(S) requests with a span and enriches it with metrics.
|
||||
type Transport struct {
|
||||
rt http.RoundTripper
|
||||
|
||||
tracer trace.Tracer
|
||||
propagators propagation.TextMapPropagator
|
||||
spanStartOptions []trace.SpanStartOption
|
||||
filters []Filter
|
||||
spanNameFormatter func(string, *http.Request) string
|
||||
clientTrace func(context.Context) *httptrace.ClientTrace
|
||||
metricAttributesFn func(*http.Request) []attribute.KeyValue
|
||||
|
||||
semconv semconv.HTTPClient
|
||||
}
|
||||
|
||||
var _ http.RoundTripper = &Transport{}
|
||||
|
||||
// NewTransport wraps the provided http.RoundTripper with one that
|
||||
// starts a span, injects the span context into the outbound request headers,
|
||||
// and enriches it with metrics.
|
||||
//
|
||||
// If the provided http.RoundTripper is nil, http.DefaultTransport will be used
|
||||
// as the base http.RoundTripper.
|
||||
func NewTransport(base http.RoundTripper, opts ...Option) *Transport {
|
||||
if base == nil {
|
||||
base = http.DefaultTransport
|
||||
}
|
||||
|
||||
t := Transport{
|
||||
rt: base,
|
||||
}
|
||||
|
||||
defaultOpts := []Option{
|
||||
WithSpanOptions(trace.WithSpanKind(trace.SpanKindClient)),
|
||||
WithSpanNameFormatter(defaultTransportFormatter),
|
||||
}
|
||||
|
||||
c := newConfig(append(defaultOpts, opts...)...)
|
||||
t.applyConfig(c)
|
||||
|
||||
return &t
|
||||
}
|
||||
|
||||
func (t *Transport) applyConfig(c *config) {
|
||||
t.tracer = c.Tracer
|
||||
t.propagators = c.Propagators
|
||||
t.spanStartOptions = c.SpanStartOptions
|
||||
t.filters = c.Filters
|
||||
t.spanNameFormatter = c.SpanNameFormatter
|
||||
t.clientTrace = c.ClientTrace
|
||||
t.semconv = semconv.NewHTTPClient(c.Meter)
|
||||
t.metricAttributesFn = c.MetricAttributesFn
|
||||
}
|
||||
|
||||
func defaultTransportFormatter(_ string, r *http.Request) string {
|
||||
return "HTTP " + r.Method
|
||||
}
|
||||
|
||||
// RoundTrip creates a Span and propagates its context via the provided request's headers
|
||||
// before handing the request to the configured base RoundTripper. The created span will
|
||||
// end when the response body is closed or when a read from the body returns io.EOF.
|
||||
func (t *Transport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
requestStartTime := time.Now()
|
||||
for _, f := range t.filters {
|
||||
if !f(r) {
|
||||
// Simply pass through to the base RoundTripper if a filter rejects the request
|
||||
return t.rt.RoundTrip(r)
|
||||
}
|
||||
}
|
||||
|
||||
tracer := t.tracer
|
||||
|
||||
if tracer == nil {
|
||||
if span := trace.SpanFromContext(r.Context()); span.SpanContext().IsValid() {
|
||||
tracer = newTracer(span.TracerProvider())
|
||||
} else {
|
||||
tracer = newTracer(otel.GetTracerProvider())
|
||||
}
|
||||
}
|
||||
|
||||
ctx, span := tracer.Start(r.Context(), t.spanNameFormatter("", r), t.spanStartOptions...)
|
||||
|
||||
if t.clientTrace != nil {
|
||||
ctx = httptrace.WithClientTrace(ctx, t.clientTrace(ctx))
|
||||
}
|
||||
|
||||
labeler, found := LabelerFromContext(ctx)
|
||||
if !found {
|
||||
ctx = ContextWithLabeler(ctx, labeler)
|
||||
}
|
||||
|
||||
r = r.Clone(ctx) // According to RoundTripper spec, we shouldn't modify the origin request.
|
||||
|
||||
var lastBW *request.BodyWrapper // Records the last body wrapper. Can be nil.
|
||||
maybeWrapBody := func(body io.ReadCloser) io.ReadCloser {
|
||||
if body == nil || body == http.NoBody {
|
||||
return body
|
||||
}
|
||||
bw := request.NewBodyWrapper(body, func(int64) {})
|
||||
lastBW = bw
|
||||
return bw
|
||||
}
|
||||
r.Body = maybeWrapBody(r.Body)
|
||||
if r.GetBody != nil {
|
||||
originalGetBody := r.GetBody
|
||||
r.GetBody = func() (io.ReadCloser, error) {
|
||||
b, err := originalGetBody()
|
||||
if err != nil {
|
||||
lastBW = nil // The underlying transport will fail to make a retry request, hence, record no data.
|
||||
return nil, err
|
||||
}
|
||||
return maybeWrapBody(b), nil
|
||||
}
|
||||
}
|
||||
|
||||
span.SetAttributes(t.semconv.RequestTraceAttrs(r)...)
|
||||
t.propagators.Inject(ctx, propagation.HeaderCarrier(r.Header))
|
||||
|
||||
res, err := t.rt.RoundTrip(r)
|
||||
|
||||
// Record the metrics on error or no error.
|
||||
statusCode := 0
|
||||
if err == nil {
|
||||
statusCode = res.StatusCode
|
||||
}
|
||||
var requestSize int64
|
||||
if lastBW != nil {
|
||||
requestSize = lastBW.BytesRead()
|
||||
}
|
||||
t.semconv.RecordMetrics(
|
||||
ctx,
|
||||
semconv.MetricData{
|
||||
RequestSize: requestSize,
|
||||
RequestDuration: time.Since(requestStartTime),
|
||||
},
|
||||
t.semconv.MetricOptions(semconv.MetricAttributes{
|
||||
Req: r,
|
||||
StatusCode: statusCode,
|
||||
AdditionalAttributes: append(labeler.Get(), t.metricAttributesFromRequest(r)...),
|
||||
}),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
span.SetAttributes(otelsemconv.ErrorType(err))
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
span.End()
|
||||
|
||||
return res, err
|
||||
}
|
||||
|
||||
readRecordFunc := func(int64) {}
|
||||
res.Body = newWrappedBody(span, readRecordFunc, res.Body)
|
||||
// traces
|
||||
span.SetAttributes(t.semconv.ResponseTraceAttrs(res)...)
|
||||
span.SetStatus(t.semconv.Status(res.StatusCode))
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (t *Transport) metricAttributesFromRequest(r *http.Request) []attribute.KeyValue {
|
||||
var attributeForRequest []attribute.KeyValue
|
||||
if t.metricAttributesFn != nil {
|
||||
attributeForRequest = t.metricAttributesFn(r)
|
||||
}
|
||||
return attributeForRequest
|
||||
}
|
||||
|
||||
// newWrappedBody returns a new and appropriately scoped *wrappedBody as an
|
||||
// io.ReadCloser. If the passed body implements io.Writer, the returned value
|
||||
// will implement io.ReadWriteCloser.
|
||||
func newWrappedBody(span trace.Span, record func(n int64), body io.ReadCloser) io.ReadCloser {
|
||||
// The successful protocol switch responses will have a body that
|
||||
// implement an io.ReadWriteCloser. Ensure this interface type continues
|
||||
// to be satisfied if that is the case.
|
||||
if _, ok := body.(io.ReadWriteCloser); ok {
|
||||
return &wrappedBody{span: span, record: record, body: body}
|
||||
}
|
||||
|
||||
// Remove the implementation of the io.ReadWriteCloser and only implement
|
||||
// the io.ReadCloser.
|
||||
return struct{ io.ReadCloser }{&wrappedBody{span: span, record: record, body: body}}
|
||||
}
|
||||
|
||||
// wrappedBody is the response body type returned by the transport
|
||||
// instrumentation to complete a span. Errors encountered when using the
|
||||
// response body are recorded in span tracking the response.
|
||||
//
|
||||
// The span tracking the response is ended when this body is closed.
|
||||
//
|
||||
// If the response body implements the io.Writer interface (i.e. for
|
||||
// successful protocol switches), the wrapped body also will.
|
||||
type wrappedBody struct {
|
||||
span trace.Span
|
||||
recorded atomic.Bool
|
||||
record func(n int64)
|
||||
body io.ReadCloser
|
||||
read atomic.Int64
|
||||
}
|
||||
|
||||
var _ io.ReadWriteCloser = &wrappedBody{}
|
||||
|
||||
func (wb *wrappedBody) Write(p []byte) (int, error) {
|
||||
// This will not panic given the guard in newWrappedBody.
|
||||
n, err := wb.body.(io.Writer).Write(p)
|
||||
if err != nil {
|
||||
wb.span.SetAttributes(otelsemconv.ErrorType(err))
|
||||
wb.span.SetStatus(codes.Error, err.Error())
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (wb *wrappedBody) Read(b []byte) (int, error) {
|
||||
n, err := wb.body.Read(b)
|
||||
// Record the number of bytes read
|
||||
wb.read.Add(int64(n))
|
||||
|
||||
switch err {
|
||||
case nil:
|
||||
// nothing to do here but fall through to the return
|
||||
case io.EOF:
|
||||
wb.recordBytesRead()
|
||||
wb.span.End()
|
||||
default:
|
||||
wb.span.SetAttributes(otelsemconv.ErrorType(err))
|
||||
wb.span.SetStatus(codes.Error, err.Error())
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
// recordBytesRead is a function that ensures the number of bytes read is recorded once and only once.
|
||||
func (wb *wrappedBody) recordBytesRead() {
|
||||
// note: it is more performant (and equally correct) to use atomic.Bool over sync.Once here. In the event that
|
||||
// two goroutines are racing to call this method, the number of bytes read will no longer increase. Using
|
||||
// CompareAndSwap allows later goroutines to return quickly and not block waiting for the race winner to finish
|
||||
// calling wb.record(wb.read.Load()).
|
||||
if wb.recorded.CompareAndSwap(false, true) {
|
||||
// Record the total number of bytes read
|
||||
wb.record(wb.read.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func (wb *wrappedBody) Close() error {
|
||||
wb.recordBytesRead()
|
||||
wb.span.End()
|
||||
if wb.body != nil {
|
||||
return wb.body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Generated
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
|
||||
// Version is the current release version of the otelhttp instrumentation.
|
||||
const Version = "0.67.0"
|
||||
+231
@@ -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.
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package zpages // import "go.opentelemetry.io/contrib/zpages"
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
zeroDuration = time.Duration(0)
|
||||
maxDuration = time.Duration(1<<63 - 1)
|
||||
)
|
||||
|
||||
var defaultBoundaries = newBoundaries([]time.Duration{
|
||||
10 * time.Microsecond,
|
||||
100 * time.Microsecond,
|
||||
time.Millisecond,
|
||||
10 * time.Millisecond,
|
||||
100 * time.Millisecond,
|
||||
time.Second,
|
||||
10 * time.Second,
|
||||
100 * time.Second,
|
||||
})
|
||||
|
||||
// boundaries represents the interval bounds for the latency based samples.
|
||||
type boundaries struct {
|
||||
durations []time.Duration
|
||||
}
|
||||
|
||||
// newBoundaries returns a new boundaries.
|
||||
func newBoundaries(durations []time.Duration) *boundaries {
|
||||
slices.Sort(durations)
|
||||
return &boundaries{durations: durations}
|
||||
}
|
||||
|
||||
// numBuckets returns the number of buckets needed for these boundaries.
|
||||
func (lb boundaries) numBuckets() int {
|
||||
return len(lb.durations) + 1
|
||||
}
|
||||
|
||||
// getBucketIndex returns the appropriate bucket index for a given latency.
|
||||
func (lb boundaries) getBucketIndex(latency time.Duration) int {
|
||||
i := 0
|
||||
for i < len(lb.durations) && latency >= lb.durations[i] {
|
||||
i++
|
||||
}
|
||||
return i
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Copyright 2017, OpenCensus Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package zpages // import "go.opentelemetry.io/contrib/zpages"
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultBucketCapacity is the default capacity for every bucket (latency or error based).
|
||||
defaultBucketCapacity = 10
|
||||
// samplePeriod is the minimum time between accepting spans in a single bucket.
|
||||
samplePeriod = time.Second
|
||||
)
|
||||
|
||||
// bucket is a container for a set of spans for latency buckets or errored spans.
|
||||
type bucket struct {
|
||||
nextTime time.Time // next time we can accept a span
|
||||
buffer []sdktrace.ReadOnlySpan // circular buffer of spans
|
||||
nextIndex int // location next ReadOnlySpan should be placed in buffer
|
||||
overflow bool // whether the circular buffer has wrapped around
|
||||
}
|
||||
|
||||
// newBucket returns a new bucket with the given capacity.
|
||||
func newBucket(capacity uint) *bucket {
|
||||
return &bucket{
|
||||
buffer: make([]sdktrace.ReadOnlySpan, capacity),
|
||||
}
|
||||
}
|
||||
|
||||
// add adds a span to the bucket, if nextTime has been reached.
|
||||
func (b *bucket) add(s sdktrace.ReadOnlySpan) {
|
||||
if s.EndTime().Before(b.nextTime) {
|
||||
return
|
||||
}
|
||||
if len(b.buffer) == 0 {
|
||||
return
|
||||
}
|
||||
b.nextTime = s.EndTime().Add(samplePeriod)
|
||||
b.buffer[b.nextIndex] = s
|
||||
b.nextIndex++
|
||||
if b.nextIndex == len(b.buffer) {
|
||||
b.nextIndex = 0
|
||||
b.overflow = true
|
||||
}
|
||||
}
|
||||
|
||||
// len returns the number of spans in the bucket.
|
||||
func (b *bucket) len() int {
|
||||
if b.overflow {
|
||||
return len(b.buffer)
|
||||
}
|
||||
return b.nextIndex
|
||||
}
|
||||
|
||||
// spans returns the spans in this bucket.
|
||||
func (b *bucket) spans() []sdktrace.ReadOnlySpan {
|
||||
return append([]sdktrace.ReadOnlySpan(nil), b.buffer[0:b.len()]...)
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package zpages implements a collection of HTML pages that display
|
||||
// telemetry stats.
|
||||
package zpages // import "go.opentelemetry.io/contrib/zpages"
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Package internal provides non-public types for the zpages package.
|
||||
package internal // import "go.opentelemetry.io/contrib/zpages/internal"
|
||||
|
||||
import "embed"
|
||||
|
||||
// Templates embeds all the HTML templates used used to serve the tracez
|
||||
// endpoint
|
||||
//
|
||||
//go:embed templates/*
|
||||
var Templates embed.FS
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
</body>
|
||||
</html>
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en"><head>
|
||||
<meta charset="utf-8">
|
||||
<title>{{.Title}}</title>
|
||||
<link rel="shortcut icon" href="https://opentelemetry.io/favicons/favicon.ico"/>
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/material-design-lite/1.3.0/material.indigo-pink.min.css">
|
||||
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/material-design-lite/1.3.0/material.min.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<h1>{{.Title}}</h1>
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
<table style="border-spacing: 0">
|
||||
<tr>
|
||||
<td colspan=1 align=left><b>Span Name</b></td>
|
||||
<td> | </td><td colspan=1 align="center"><b>Running</b></td>
|
||||
<td> | </td>
|
||||
<td colspan=9 align="center"><b>Latency Samples</b></td>
|
||||
<td> | </td>
|
||||
<td colspan=1 align="center"><b>Error Samples</b></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan=1></td>
|
||||
<td> | </td>
|
||||
<td colspan=1></td>
|
||||
<td> | </td>
|
||||
{{range .LatencyBucketNames}}<th colspan=1 align="center"><b>[{{.}}]</b></th>{{end}}
|
||||
<td> | </td>
|
||||
<td colspan=1></td>
|
||||
</tr>
|
||||
{{$a := .TracesEndpoint}}
|
||||
{{$links := .Links}}
|
||||
{{range $rowindex, $row := .Rows}}
|
||||
{{- $name := .Name}}
|
||||
{{- if even $rowindex}}<tr style="background: #eee">{{else}}<tr>{{end -}}
|
||||
<td>{{.Name}}</td><td> | </td>
|
||||
{{- if $links -}}
|
||||
<td align="center"><a href="{{$a}}?zspanname={{$name}}&ztype=0">{{.Active}}</a></td>
|
||||
{{- else -}}
|
||||
<td>{{.Active}}</td>
|
||||
{{- end -}}
|
||||
<td> | </td>
|
||||
{{- if $links -}}
|
||||
{{range $index, $value := .Latency}}<td align="center"><a href="{{$a}}?zspanname={{$name}}&ztype=1&zlatencybucket={{$index}}">{{$value}}</a></td>{{end}}
|
||||
{{- else -}}
|
||||
{{range .Latency}}<td>{{.}}</td>{{end}}
|
||||
{{- end -}}
|
||||
<td> | </td>
|
||||
{{- if $links -}}
|
||||
<td align="center"><a href="{{$a}}?zspanname={{$name}}&ztype=2&zlatencybucket=0">{{.Errors}}</td>
|
||||
{{- else -}}
|
||||
<td>{{.Errors}}</td>
|
||||
{{- end -}}
|
||||
</tr>
|
||||
{{end}}</table>
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
<p><b>Span Name: {{.Name}} </b></p>
|
||||
<p>{{.Num}} Requests</p>
|
||||
<pre>
|
||||
When Elapsed (sec)
|
||||
----------------------------------------
|
||||
{{range .Rows}}{{printf "%26s" (index .Fields 0)}} {{printf "%12s" (index .Fields 1)}} {{index .Fields 2}}{{.|spanRow}}
|
||||
{{end}}</pre>
|
||||
<br>
|
||||
<p><b style="color:blue;">TraceId</b> means sampled request.
|
||||
<b style="color:black;">TraceId</b> means not sampled request.</p>
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Copyright 2017, OpenCensus Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package zpages // import "go.opentelemetry.io/contrib/zpages"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
var _ sdktrace.SpanProcessor = (*SpanProcessor)(nil)
|
||||
|
||||
// perMethodSummary is a summary of the spans stored for a single span name.
|
||||
type perMethodSummary struct {
|
||||
activeSpans int
|
||||
latencySpans []int
|
||||
errorSpans int
|
||||
}
|
||||
|
||||
// SpanProcessor is an sdktrace.SpanProcessor implementation that exposes zpages functionality for opentelemetry-go.
|
||||
//
|
||||
// It tracks all active spans, and stores samples of spans based on latency for non errored spans,
|
||||
// and samples for errored spans.
|
||||
type SpanProcessor struct {
|
||||
// Cannot keep track of the active Spans per name because the Span interface,
|
||||
// allows the name to be changed, and that will leak memory.
|
||||
activeSpansStore sync.Map
|
||||
spanSampleStores sync.Map
|
||||
}
|
||||
|
||||
// NewSpanProcessor returns a new SpanProcessor.
|
||||
func NewSpanProcessor() *SpanProcessor {
|
||||
return &SpanProcessor{}
|
||||
}
|
||||
|
||||
// OnStart adds span as active and reports it with zpages.
|
||||
func (ssm *SpanProcessor) OnStart(_ context.Context, span sdktrace.ReadWriteSpan) {
|
||||
sc := span.SpanContext()
|
||||
if sc.IsValid() {
|
||||
ssm.activeSpansStore.Store(spanKey(sc), span)
|
||||
}
|
||||
}
|
||||
|
||||
// OnEnd processes all spans and reports them with zpages.
|
||||
func (ssm *SpanProcessor) OnEnd(span sdktrace.ReadOnlySpan) {
|
||||
sc := span.SpanContext()
|
||||
if sc.IsValid() {
|
||||
ssm.activeSpansStore.Delete(spanKey(sc))
|
||||
}
|
||||
|
||||
name := span.Name()
|
||||
value, ok := ssm.spanSampleStores.Load(name)
|
||||
if !ok {
|
||||
value, _ = ssm.spanSampleStores.LoadOrStore(name, newSampleStore(defaultBucketCapacity, defaultBucketCapacity))
|
||||
}
|
||||
value.(*sampleStore).sampleSpan(span)
|
||||
}
|
||||
|
||||
// Shutdown does nothing.
|
||||
func (*SpanProcessor) Shutdown(context.Context) error {
|
||||
// Do nothing
|
||||
return nil
|
||||
}
|
||||
|
||||
// ForceFlush does nothing.
|
||||
func (*SpanProcessor) ForceFlush(context.Context) error {
|
||||
// Do nothing
|
||||
return nil
|
||||
}
|
||||
|
||||
// spanStoreForName returns the sampleStore for the given name.
|
||||
//
|
||||
// It returns nil if it doesn't exist.
|
||||
func (ssm *SpanProcessor) spanStoreForName(name string) *sampleStore {
|
||||
if value, ok := ssm.spanSampleStores.Load(name); ok {
|
||||
return value.(*sampleStore)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// spansPerMethod returns a summary of what spans are being stored for each span name.
|
||||
func (ssm *SpanProcessor) spansPerMethod() map[string]*perMethodSummary {
|
||||
out := make(map[string]*perMethodSummary)
|
||||
ssm.spanSampleStores.Range(func(name, s any) bool {
|
||||
out[name.(string)] = s.(*sampleStore).perMethodSummary()
|
||||
return true
|
||||
})
|
||||
ssm.activeSpansStore.Range(func(_, sp any) bool {
|
||||
span := sp.(sdktrace.ReadOnlySpan)
|
||||
if pms, ok := out[span.Name()]; ok {
|
||||
pms.activeSpans++
|
||||
return true
|
||||
}
|
||||
out[span.Name()] = &perMethodSummary{activeSpans: 1}
|
||||
return true
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// activeSpans returns the active spans for the given name.
|
||||
func (ssm *SpanProcessor) activeSpans(name string) []sdktrace.ReadOnlySpan {
|
||||
var out []sdktrace.ReadOnlySpan
|
||||
ssm.activeSpansStore.Range(func(_, sp any) bool {
|
||||
span := sp.(sdktrace.ReadOnlySpan)
|
||||
if span.Name() == name {
|
||||
out = append(out, span)
|
||||
}
|
||||
return true
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// errorSpans returns a sample of error spans.
|
||||
func (ssm *SpanProcessor) errorSpans(name string) []sdktrace.ReadOnlySpan {
|
||||
s := ssm.spanStoreForName(name)
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return s.errorSpans()
|
||||
}
|
||||
|
||||
// spansByLatency returns a sample of successful spans.
|
||||
//
|
||||
// minLatency is the minimum latency of spans to be returned.
|
||||
// maxDuration, if nonzero, is the maximum latency of spans to be returned.
|
||||
func (ssm *SpanProcessor) spansByLatency(name string, latencyBucketIndex int) []sdktrace.ReadOnlySpan {
|
||||
s := ssm.spanStoreForName(name)
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return s.spansByLatency(latencyBucketIndex)
|
||||
}
|
||||
|
||||
// sampleStore stores a sampled of spans for a particular span name.
|
||||
//
|
||||
// It contains sample of spans for error requests (status code is codes.Error);
|
||||
// and a sample of spans for successful requests, bucketed by latency.
|
||||
type sampleStore struct {
|
||||
sync.Mutex // protects everything below.
|
||||
latency []*bucket
|
||||
errors *bucket
|
||||
}
|
||||
|
||||
// newSampleStore creates a sampleStore.
|
||||
func newSampleStore(latencyBucketSize, errorBucketSize uint) *sampleStore {
|
||||
s := &sampleStore{
|
||||
latency: make([]*bucket, defaultBoundaries.numBuckets()),
|
||||
errors: newBucket(errorBucketSize),
|
||||
}
|
||||
for i := range s.latency {
|
||||
s.latency[i] = newBucket(latencyBucketSize)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func (ss *sampleStore) perMethodSummary() *perMethodSummary {
|
||||
ss.Lock()
|
||||
defer ss.Unlock()
|
||||
p := &perMethodSummary{}
|
||||
p.errorSpans = ss.errors.len()
|
||||
for _, b := range ss.latency {
|
||||
p.latencySpans = append(p.latencySpans, b.len())
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (ss *sampleStore) spansByLatency(latencyBucketIndex int) []sdktrace.ReadOnlySpan {
|
||||
ss.Lock()
|
||||
defer ss.Unlock()
|
||||
if latencyBucketIndex < 0 || latencyBucketIndex >= len(ss.latency) {
|
||||
return nil
|
||||
}
|
||||
return ss.latency[latencyBucketIndex].spans()
|
||||
}
|
||||
|
||||
func (ss *sampleStore) errorSpans() []sdktrace.ReadOnlySpan {
|
||||
ss.Lock()
|
||||
defer ss.Unlock()
|
||||
return ss.errors.spans()
|
||||
}
|
||||
|
||||
// sampleSpan removes adds to the corresponding latency or error bucket.
|
||||
func (ss *sampleStore) sampleSpan(span sdktrace.ReadOnlySpan) {
|
||||
code := span.Status().Code
|
||||
|
||||
ss.Lock()
|
||||
defer ss.Unlock()
|
||||
if code == codes.Error {
|
||||
ss.errors.add(span)
|
||||
return
|
||||
}
|
||||
|
||||
// In case of time skew or wrong time, sample as 0 latency.
|
||||
latency := max(span.EndTime().Sub(span.StartTime()), 0)
|
||||
ss.latency[defaultBoundaries.getBucketIndex(latency)].add(span)
|
||||
}
|
||||
|
||||
func spanKey(sc trace.SpanContext) [24]byte {
|
||||
var sk [24]byte
|
||||
tid := sc.TraceID()
|
||||
copy(sk[0:16], tid[:])
|
||||
sid := sc.SpanID()
|
||||
copy(sk[16:24], sid[:])
|
||||
return sk
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Copyright 2017, OpenCensus Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
package zpages // import "go.opentelemetry.io/contrib/zpages"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"log"
|
||||
|
||||
"go.opentelemetry.io/contrib/zpages/internal"
|
||||
)
|
||||
|
||||
var (
|
||||
templateFunctions = template.FuncMap{
|
||||
"even": even,
|
||||
"spanRow": spanRowFormatter,
|
||||
}
|
||||
headerTemplate = parseTemplate("header")
|
||||
summaryTableTemplate = parseTemplate("summary")
|
||||
tracesTableTemplate = parseTemplate("traces")
|
||||
footerTemplate = parseTemplate("footer")
|
||||
)
|
||||
|
||||
// headerData contains data for the header template.
|
||||
type headerData struct {
|
||||
Title string
|
||||
}
|
||||
|
||||
func parseTemplate(name string) *template.Template {
|
||||
f, err := internal.Templates.Open("templates/" + name + ".html")
|
||||
if err != nil {
|
||||
log.Panicf("%v: %v", name, err) //nolint:revive // Called during initialization.
|
||||
}
|
||||
defer func() {
|
||||
if err = f.Close(); err != nil {
|
||||
log.Panicf("%v: %v", name, err) //nolint:revive // Called during initialization.
|
||||
}
|
||||
}()
|
||||
text, err := io.ReadAll(f)
|
||||
if err != nil {
|
||||
log.Panicf("%v: %v", name, err) //nolint:revive // Called during initialization.
|
||||
}
|
||||
return template.Must(template.New(name).Funcs(templateFunctions).Parse(string(text)))
|
||||
}
|
||||
|
||||
func spanRowFormatter(r spanRow) template.HTML {
|
||||
if !r.IsValid() {
|
||||
return ""
|
||||
}
|
||||
col := "black"
|
||||
if r.IsSampled() {
|
||||
col = "blue"
|
||||
}
|
||||
|
||||
tpl := fmt.Sprintf(
|
||||
`trace_id: <b style="color:%s">%s</b> span_id: %s`,
|
||||
col,
|
||||
r.TraceID(),
|
||||
r.SpanID(),
|
||||
)
|
||||
if r.ParentSpanContext.IsValid() {
|
||||
tpl += fmt.Sprintf(` parent_span_id: %s`, r.ParentSpanContext.SpanID())
|
||||
}
|
||||
|
||||
//nolint:gosec // G203: None of the dynamic attributes (TraceID/SpanID) can
|
||||
// contain characters that need escaping so this lint issue is a false
|
||||
// positive.
|
||||
return template.HTML(tpl)
|
||||
}
|
||||
|
||||
func even(x int) bool {
|
||||
return x%2 == 0
|
||||
}
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Copyright 2017, OpenCensus Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package zpages // import "go.opentelemetry.io/contrib/zpages"
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
const (
|
||||
// spanNameQueryField is the header for span name.
|
||||
spanNameQueryField = "zspanname"
|
||||
// spanTypeQueryField is the header for type (running = 0, latency = 1, error = 2) to display.
|
||||
spanTypeQueryField = "ztype"
|
||||
// spanLatencyBucketQueryField is the header for latency based samples.
|
||||
// Default is [0, 8] representing the latency buckets, where 0 is the first one.
|
||||
spanLatencyBucketQueryField = "zlatencybucket"
|
||||
// maxTraceMessageLength is the maximum length of a message in tracez output.
|
||||
maxTraceMessageLength = 1024
|
||||
|
||||
maxRequestBodySize = 1 << 20 // 1MB
|
||||
)
|
||||
|
||||
type summaryTableData struct {
|
||||
Header []string
|
||||
LatencyBucketNames []string
|
||||
Links bool
|
||||
TracesEndpoint string
|
||||
Rows []summaryTableRowData
|
||||
}
|
||||
|
||||
type summaryTableRowData struct {
|
||||
Name string
|
||||
Active int
|
||||
Latency []int
|
||||
Errors int
|
||||
}
|
||||
|
||||
// traceTableData contains data for the trace data template.
|
||||
type traceTableData struct {
|
||||
Name string
|
||||
Num int
|
||||
Rows []spanRow
|
||||
}
|
||||
|
||||
var _ http.Handler = (*tracezHandler)(nil)
|
||||
|
||||
type tracezHandler struct {
|
||||
sp *SpanProcessor
|
||||
}
|
||||
|
||||
// NewTracezHandler returns an http.Handler that can be used to serve HTTP requests for trace zpages.
|
||||
func NewTracezHandler(sp *SpanProcessor) http.Handler {
|
||||
return &tracezHandler{sp: sp}
|
||||
}
|
||||
|
||||
// ServeHTTP implements the http.Handler and is capable of serving "tracez" HTTP requests.
|
||||
func (th *tracezHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodySize)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
spanName := r.Form.Get(spanNameQueryField)
|
||||
spanType, _ := strconv.Atoi(r.Form.Get(spanTypeQueryField))
|
||||
spanSubtype, _ := strconv.Atoi(r.Form.Get(spanLatencyBucketQueryField))
|
||||
|
||||
if err := headerTemplate.Execute(w, headerData{Title: "Trace Spans"}); err != nil {
|
||||
log.Printf("zpages: executing template: %v", err)
|
||||
}
|
||||
if err := summaryTableTemplate.Execute(w, th.getSummaryTableData()); err != nil {
|
||||
log.Printf("zpages: executing template: %v", err)
|
||||
}
|
||||
if spanName != "" {
|
||||
if err := tracesTableTemplate.Execute(w, th.getTraceTableData(spanName, spanType, spanSubtype)); err != nil {
|
||||
log.Printf("zpages: executing template: %v", err)
|
||||
}
|
||||
}
|
||||
if err := footerTemplate.Execute(w, nil); err != nil {
|
||||
log.Printf("zpages: executing template: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (th *tracezHandler) getTraceTableData(spanName string, spanType, latencyBucket int) traceTableData {
|
||||
var spans []sdktrace.ReadOnlySpan
|
||||
switch spanType {
|
||||
case 0: // active
|
||||
spans = th.sp.activeSpans(spanName)
|
||||
case 1: // latency
|
||||
spans = th.sp.spansByLatency(spanName, latencyBucket)
|
||||
case 2: // error
|
||||
spans = th.sp.errorSpans(spanName)
|
||||
}
|
||||
|
||||
data := traceTableData{
|
||||
Name: spanName,
|
||||
Num: len(spans),
|
||||
}
|
||||
for _, s := range spans {
|
||||
data.Rows = append(data.Rows, spanRows(s)...)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func (th *tracezHandler) getSummaryTableData() summaryTableData {
|
||||
data := summaryTableData{
|
||||
Links: true,
|
||||
TracesEndpoint: "tracez",
|
||||
}
|
||||
data.Header = []string{"Name", "active"}
|
||||
// An implicit 0 lower bound latency bucket is always present.
|
||||
latencyBuckets := append([]time.Duration{0}, defaultBoundaries.durations...)
|
||||
for _, l := range latencyBuckets {
|
||||
s := fmt.Sprintf(">%v", l)
|
||||
data.Header = append(data.Header, s)
|
||||
data.LatencyBucketNames = append(data.LatencyBucketNames, s)
|
||||
}
|
||||
data.Header = append(data.Header, "Errors")
|
||||
for name, s := range th.sp.spansPerMethod() {
|
||||
row := summaryTableRowData{Name: name, Active: s.activeSpans, Errors: s.errorSpans, Latency: s.latencySpans}
|
||||
data.Rows = append(data.Rows, row)
|
||||
}
|
||||
sort.Slice(data.Rows, func(i, j int) bool {
|
||||
return data.Rows[i].Name < data.Rows[j].Name
|
||||
})
|
||||
return data
|
||||
}
|
||||
|
||||
type spanRow struct {
|
||||
Fields [3]string
|
||||
trace.SpanContext
|
||||
ParentSpanContext trace.SpanContext
|
||||
}
|
||||
|
||||
type events []sdktrace.Event
|
||||
|
||||
func (e events) Len() int { return len(e) }
|
||||
func (e events) Less(i, j int) bool {
|
||||
return e[i].Time.Before(e[j].Time)
|
||||
}
|
||||
func (e events) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
|
||||
|
||||
type attributes []attribute.KeyValue
|
||||
|
||||
func (e attributes) Len() int { return len(e) }
|
||||
func (e attributes) Less(i, j int) bool {
|
||||
return string(e[i].Key) < string(e[j].Key)
|
||||
}
|
||||
func (e attributes) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
|
||||
|
||||
func spanRows(s sdktrace.ReadOnlySpan) []spanRow {
|
||||
start := s.StartTime()
|
||||
|
||||
lasty, lastm, lastd := start.Date()
|
||||
wholeTime := func(t time.Time) string {
|
||||
return t.Format("2006/01/02-15:04:05") + fmt.Sprintf(".%06d", t.Nanosecond()/1000)
|
||||
}
|
||||
formatTime := func(t time.Time) string {
|
||||
y, m, d := t.Date()
|
||||
if y == lasty && m == lastm && d == lastd {
|
||||
return t.Format(" 15:04:05") + fmt.Sprintf(".%06d", t.Nanosecond()/1000)
|
||||
}
|
||||
lasty, lastm, lastd = y, m, d
|
||||
return wholeTime(t)
|
||||
}
|
||||
|
||||
lastTime := start
|
||||
formatElapsed := func(t time.Time) string {
|
||||
d := t.Sub(lastTime)
|
||||
lastTime = t
|
||||
u := int64(d / 1000)
|
||||
// There are five cases for duration printing:
|
||||
// -1234567890s
|
||||
// -1234.123456
|
||||
// .123456
|
||||
// 12345.123456
|
||||
// 12345678901s
|
||||
switch {
|
||||
case u < -9999999999:
|
||||
return fmt.Sprintf("%11ds", u/1e6)
|
||||
case u < 0:
|
||||
sec := u / 1e6
|
||||
u -= sec * 1e6
|
||||
return fmt.Sprintf("%5d.%06d", sec, -u)
|
||||
case u < 1e6:
|
||||
return fmt.Sprintf(" .%6d", u)
|
||||
case u <= 99999999999:
|
||||
sec := u / 1e6
|
||||
u -= sec * 1e6
|
||||
return fmt.Sprintf("%5d.%06d", sec, u)
|
||||
default:
|
||||
return fmt.Sprintf("%11ds", u/1e6)
|
||||
}
|
||||
}
|
||||
|
||||
firstRow := spanRow{Fields: [3]string{wholeTime(start), "", ""}, SpanContext: s.SpanContext(), ParentSpanContext: s.Parent()}
|
||||
if s.EndTime().IsZero() {
|
||||
firstRow.Fields[1] = " "
|
||||
} else {
|
||||
firstRow.Fields[1] = formatElapsed(s.EndTime())
|
||||
lastTime = start
|
||||
}
|
||||
out := []spanRow{firstRow}
|
||||
|
||||
formatAttributes := func(a attributes) string {
|
||||
sort.Sort(a)
|
||||
var s []string
|
||||
for i := range a {
|
||||
s = append(s, fmt.Sprintf("%s=%v", a[i].Key, a[i].Value.Emit()))
|
||||
}
|
||||
return "Attributes:{" + strings.Join(s, ", ") + "}"
|
||||
}
|
||||
|
||||
msg := fmt.Sprintf("Status{Code=%s, description=%q}", s.Status().Code.String(), s.Status().Description)
|
||||
out = append(out, spanRow{Fields: [3]string{"", "", msg}})
|
||||
|
||||
if len(s.Attributes()) != 0 {
|
||||
out = append(out, spanRow{Fields: [3]string{"", "", formatAttributes(s.Attributes())}})
|
||||
}
|
||||
|
||||
es := events(s.Events())
|
||||
sort.Sort(es)
|
||||
for _, e := range es {
|
||||
msg := e.Name
|
||||
if len(e.Attributes) != 0 {
|
||||
msg = msg + " " + formatAttributes(e.Attributes)
|
||||
}
|
||||
row := spanRow{Fields: [3]string{
|
||||
formatTime(e.Time),
|
||||
formatElapsed(e.Time),
|
||||
msg,
|
||||
}}
|
||||
out = append(out, row)
|
||||
}
|
||||
for i := range out {
|
||||
if len(out[i].Fields[2]) > maxTraceMessageLength {
|
||||
out[i].Fields[2] = out[i].Fields[2][:maxTraceMessageLength]
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
// Copyright The OpenTelemetry Authors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package zpages // import "go.opentelemetry.io/contrib/zpages"
|
||||
|
||||
// Version is the current release version of the zpages span processor.
|
||||
const Version = "0.68.0"
|
||||
Reference in New Issue
Block a user