Debian Codegraph @

zpages/spanprocessor.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Copyright 2017, OpenCensus Authors
5 //
6 // Licensed under the Apache License, Version 2.0 (the "License");
7 // you may not use this file except in compliance with the License.
8 // You may obtain a copy of the License at
9 //
10 // http://www.apache.org/licenses/LICENSE-2.0
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17
18 package zpages // import "go.opentelemetry.io/contrib/zpages"
19
20 import (
21 "context"
22 "sync"
23
24 "go.opentelemetry.io/otel/codes"
25 sdktrace "go.opentelemetry.io/otel/sdk/trace"
26 "go.opentelemetry.io/otel/trace"
27 )
28
29 var _ sdktrace.SpanProcessor = (*SpanProcessor)(nil)
30
31 // perMethodSummary is a summary of the spans stored for a single span name.
32 type perMethodSummary struct {
33 activeSpans int
34 latencySpans []int
35 errorSpans int
36 }
37
38 // SpanProcessor is an sdktrace.SpanProcessor implementation that exposes zpages functionality for opentelemetry-go.
39 //
40 // It tracks all active spans, and stores samples of spans based on latency for non errored spans,
41 // and samples for errored spans.
42 type SpanProcessor struct {
43 // Cannot keep track of the active Spans per name because the Span interface,
44 // allows the name to be changed, and that will leak memory.
45 activeSpansStore sync.Map
46 spanSampleStores sync.Map
47 }
48
49 // NewSpanProcessor returns a new SpanProcessor.
50 func NewSpanProcessor() *SpanProcessor {
51 return &SpanProcessor{}
52 }
53
54 // OnStart adds span as active and reports it with zpages.
55 func (ssm *SpanProcessor) OnStart(_ context.Context, span sdktrace.ReadWriteSpan) {
56 sc := span.SpanContext()
57 if sc.IsValid() {
58 ssm.activeSpansStore.Store(spanKey(sc), span)
59 }
60 }
61
62 // OnEnd processes all spans and reports them with zpages.
63 func (ssm *SpanProcessor) OnEnd(span sdktrace.ReadOnlySpan) {
64 sc := span.SpanContext()
65 if sc.IsValid() {
66 ssm.activeSpansStore.Delete(spanKey(sc))
67 }
68
69 name := span.Name()
70 value, ok := ssm.spanSampleStores.Load(name)
71 if !ok {
72 value, _ = ssm.spanSampleStores.LoadOrStore(name, newSampleStore(defaultBucketCapacity, defaultBucketCapacity))
73 }
74 value.(*sampleStore).sampleSpan(span)
75 }
76
77 // Shutdown does nothing.
78 func (*SpanProcessor) Shutdown(context.Context) error {
79 // Do nothing
80 return nil
81 }
82
83 // ForceFlush does nothing.
84 func (*SpanProcessor) ForceFlush(context.Context) error {
85 // Do nothing
86 return nil
87 }
88
89 // spanStoreForName returns the sampleStore for the given name.
90 //
91 // It returns nil if it doesn't exist.
92 func (ssm *SpanProcessor) spanStoreForName(name string) *sampleStore {
93 if value, ok := ssm.spanSampleStores.Load(name); ok {
94 return value.(*sampleStore)
95 }
96 return nil
97 }
98
99 // spansPerMethod returns a summary of what spans are being stored for each span name.
100 func (ssm *SpanProcessor) spansPerMethod() map[string]*perMethodSummary {
101 out := make(map[string]*perMethodSummary)
102 ssm.spanSampleStores.Range(func(name, s any) bool {
103 out[name.(string)] = s.(*sampleStore).perMethodSummary()
104 return true
105 })
106 ssm.activeSpansStore.Range(func(_, sp any) bool {
107 span := sp.(sdktrace.ReadOnlySpan)
108 if pms, ok := out[span.Name()]; ok {
109 pms.activeSpans++
110 return true
111 }
112 out[span.Name()] = &perMethodSummary{activeSpans: 1}
113 return true
114 })
115 return out
116 }
117
118 // activeSpans returns the active spans for the given name.
119 func (ssm *SpanProcessor) activeSpans(name string) []sdktrace.ReadOnlySpan {
120 var out []sdktrace.ReadOnlySpan
121 ssm.activeSpansStore.Range(func(_, sp any) bool {
122 span := sp.(sdktrace.ReadOnlySpan)
123 if span.Name() == name {
124 out = append(out, span)
125 }
126 return true
127 })
128 return out
129 }
130
131 // errorSpans returns a sample of error spans.
132 func (ssm *SpanProcessor) errorSpans(name string) []sdktrace.ReadOnlySpan {
133 s := ssm.spanStoreForName(name)
134 if s == nil {
135 return nil
136 }
137 return s.errorSpans()
138 }
139
140 // spansByLatency returns a sample of successful spans.
141 //
142 // minLatency is the minimum latency of spans to be returned.
143 // maxDuration, if nonzero, is the maximum latency of spans to be returned.
144 func (ssm *SpanProcessor) spansByLatency(name string, latencyBucketIndex int) []sdktrace.ReadOnlySpan {
145 s := ssm.spanStoreForName(name)
146 if s == nil {
147 return nil
148 }
149 return s.spansByLatency(latencyBucketIndex)
150 }
151
152 // sampleStore stores a sampled of spans for a particular span name.
153 //
154 // It contains sample of spans for error requests (status code is codes.Error);
155 // and a sample of spans for successful requests, bucketed by latency.
156 type sampleStore struct {
157 sync.Mutex // protects everything below.
158 latency []*bucket
159 errors *bucket
160 }
161
162 // newSampleStore creates a sampleStore.
163 func newSampleStore(latencyBucketSize, errorBucketSize uint) *sampleStore {
164 s := &sampleStore{
165 latency: make([]*bucket, defaultBoundaries.numBuckets()),
166 errors: newBucket(errorBucketSize),
167 }
168 for i := range s.latency {
169 s.latency[i] = newBucket(latencyBucketSize)
170 }
171 return s
172 }
173
174 func (ss *sampleStore) perMethodSummary() *perMethodSummary {
175 ss.Lock()
176 defer ss.Unlock()
177 p := &perMethodSummary{}
178 p.errorSpans = ss.errors.len()
179 for _, b := range ss.latency {
180 p.latencySpans = append(p.latencySpans, b.len())
181 }
182 return p
183 }
184
185 func (ss *sampleStore) spansByLatency(latencyBucketIndex int) []sdktrace.ReadOnlySpan {
186 ss.Lock()
187 defer ss.Unlock()
188 if latencyBucketIndex < 0 || latencyBucketIndex >= len(ss.latency) {
189 return nil
190 }
191 return ss.latency[latencyBucketIndex].spans()
192 }
193
194 func (ss *sampleStore) errorSpans() []sdktrace.ReadOnlySpan {
195 ss.Lock()
196 defer ss.Unlock()
197 return ss.errors.spans()
198 }
199
200 // sampleSpan removes adds to the corresponding latency or error bucket.
201 func (ss *sampleStore) sampleSpan(span sdktrace.ReadOnlySpan) {
202 code := span.Status().Code
203
204 ss.Lock()
205 defer ss.Unlock()
206 if code == codes.Error {
207 ss.errors.add(span)
208 return
209 }
210
211 // In case of time skew or wrong time, sample as 0 latency.
212 latency := max(span.EndTime().Sub(span.StartTime()), 0)
213 ss.latency[defaultBoundaries.getBucketIndex(latency)].add(span)
214 }
215
216 func spanKey(sc trace.SpanContext) [24]byte {
217 var sk [24]byte
218 tid := sc.TraceID()
219 copy(sk[0:16], tid[:])
220 sid := sc.SpanID()
221 copy(sk[16:24], sid[:])
222 return sk
223 }