Initial QSfera import

This commit is contained in:
Курнат Андрей
2026-06-07 10:20:04 +03:00
commit 2315f25754
16485 changed files with 4826827 additions and 0 deletions
+231
View File
@@ -0,0 +1,231 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------------------
Copyright 2009 The Go Authors.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google LLC nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+50
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
@@ -0,0 +1,2 @@
</body>
</html>
@@ -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>
@@ -0,0 +1,43 @@
<table style="border-spacing: 0">
<tr>
<td colspan=1 align=left><b>Span Name</b></td>
<td>&nbsp;&nbsp;|&nbsp;&nbsp;</td><td colspan=1 align="center"><b>Running</b></td>
<td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>
<td colspan=9 align="center"><b>Latency Samples</b></td>
<td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>
<td colspan=1 align="center"><b>Error Samples</b></td>
</tr>
<tr>
<td colspan=1></td>
<td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>
<td colspan=1></td>
<td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>
{{range .LatencyBucketNames}}<th colspan=1 align="center"><b>[{{.}}]</b></th>{{end}}
<td>&nbsp;&nbsp;|&nbsp;&nbsp;</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>&nbsp;&nbsp;|&nbsp;&nbsp;</td>
{{- if $links -}}
<td align="center"><a href="{{$a}}?zspanname={{$name}}&ztype=0">{{.Active}}</a></td>
{{- else -}}
<td>{{.Active}}</td>
{{- end -}}
<td>&nbsp;&nbsp;|&nbsp;&nbsp;</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>&nbsp;&nbsp;|&nbsp;&nbsp;</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>
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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"