aboutsummaryrefslogtreecommitdiff
path: root/vendor/go.opencensus.io/trace/spanstore.go
blob: c442d990218a3a2df65cc93aeeb3b27866dbb7b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// 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 trace

import (
	"sync"
	"time"

	"go.opencensus.io/internal"
)

const (
	maxBucketSize     = 100000
	defaultBucketSize = 10
)

var (
	ssmu       sync.RWMutex // protects spanStores
	spanStores = make(map[string]*spanStore)
)

// This exists purely to avoid exposing internal methods used by z-Pages externally.
type internalOnly struct{}

func init() {
	//TODO(#412): remove
	internal.Trace = &internalOnly{}
}

// ReportActiveSpans returns the active spans for the given name.
func (i internalOnly) ReportActiveSpans(name string) []*SpanData {
	s := spanStoreForName(name)
	if s == nil {
		return nil
	}
	var out []*SpanData
	s.mu.Lock()
	defer s.mu.Unlock()
	for span := range s.active {
		out = append(out, span.makeSpanData())
	}
	return out
}

// ReportSpansByError returns a sample of error spans.
//
// If code is nonzero, only spans with that status code are returned.
func (i internalOnly) ReportSpansByError(name string, code int32) []*SpanData {
	s := spanStoreForName(name)
	if s == nil {
		return nil
	}
	var out []*SpanData
	s.mu.Lock()
	defer s.mu.Unlock()
	if code != 0 {
		if b, ok := s.errors[code]; ok {
			for _, sd := range b.buffer {
				if sd == nil {
					break
				}
				out = append(out, sd)
			}
		}
	} else {
		for _, b := range s.errors {
			for _, sd := range b.buffer {
				if sd == nil {
					break
				}
				out = append(out, sd)
			}
		}
	}
	return out
}

// ConfigureBucketSizes sets the number of spans to keep per latency and error
// bucket for different span names.
func (i internalOnly) ConfigureBucketSizes(bcs []internal.BucketConfiguration) {
	for _, bc := range bcs {
		latencyBucketSize := bc.MaxRequestsSucceeded
		if latencyBucketSize < 0 {
			latencyBucketSize = 0
		}
		if latencyBucketSize > maxBucketSize {
			latencyBucketSize = maxBucketSize
		}
		errorBucketSize := bc.MaxRequestsErrors
		if errorBucketSize < 0 {
			errorBucketSize = 0
		}
		if errorBucketSize > maxBucketSize {
			errorBucketSize = maxBucketSize
		}
		spanStoreSetSize(bc.Name, latencyBucketSize, errorBucketSize)
	}
}

// ReportSpansPerMethod returns a summary of what spans are being stored for each span name.
func (i internalOnly) ReportSpansPerMethod() map[string]internal.PerMethodSummary {
	out := make(map[string]internal.PerMethodSummary)
	ssmu.RLock()
	defer ssmu.RUnlock()
	for name, s := range spanStores {
		s.mu.Lock()
		p := internal.PerMethodSummary{
			Active: len(s.active),
		}
		for code, b := range s.errors {
			p.ErrorBuckets = append(p.ErrorBuckets, internal.ErrorBucketSummary{
				ErrorCode: code,
				Size:      b.size(),
			})
		}
		for i, b := range s.latency {
			min, max := latencyBucketBounds(i)
			p.LatencyBuckets = append(p.LatencyBuckets, internal.LatencyBucketSummary{
				MinLatency: min,
				MaxLatency: max,
				Size:       b.size(),
			})
		}
		s.mu.Unlock()
		out[name] = p
	}
	return out
}

// ReportSpansByLatency returns a sample of successful spans.
//
// minLatency is the minimum latency of spans to be returned.
// maxLatency, if nonzero, is the maximum latency of spans to be returned.
func (i internalOnly) ReportSpansByLatency(name string, minLatency, maxLatency time.Duration) []*SpanData {
	s := spanStoreForName(name)
	if s == nil {
		return nil
	}
	var out []*SpanData
	s.mu.Lock()
	defer s.mu.Unlock()
	for i, b := range s.latency {
		min, max := latencyBucketBounds(i)
		if i+1 != len(s.latency) && max <= minLatency {
			continue
		}
		if maxLatency != 0 && maxLatency < min {
			continue
		}
		for _, sd := range b.buffer {
			if sd == nil {
				break
			}
			if minLatency != 0 || maxLatency != 0 {
				d := sd.EndTime.Sub(sd.StartTime)
				if d < minLatency {
					continue
				}
				if maxLatency != 0 && d > maxLatency {
					continue
				}
			}
			out = append(out, sd)
		}
	}
	return out
}

// spanStore keeps track of spans stored for a particular span name.
//
// It contains all active spans; a sample of spans for failed requests,
// categorized by error code; and a sample of spans for successful requests,
// bucketed by latency.
type spanStore struct {
	mu                     sync.Mutex // protects everything below.
	active                 map[*Span]struct{}
	errors                 map[int32]*bucket
	latency                []bucket
	maxSpansPerErrorBucket int
}

// newSpanStore creates a span store.
func newSpanStore(name string, latencyBucketSize int, errorBucketSize int) *spanStore {
	s := &spanStore{
		active:                 make(map[*Span]struct{}),
		latency:                make([]bucket, len(defaultLatencies)+1),
		maxSpansPerErrorBucket: errorBucketSize,
	}
	for i := range s.latency {
		s.latency[i] = makeBucket(latencyBucketSize)
	}
	return s
}

// spanStoreForName returns the spanStore for the given name.
//
// It returns nil if it doesn't exist.
func spanStoreForName(name string) *spanStore {
	var s *spanStore
	ssmu.RLock()
	s, _ = spanStores[name]
	ssmu.RUnlock()
	return s
}

// spanStoreForNameCreateIfNew returns the spanStore for the given name.
//
// It creates it if it didn't exist.
func spanStoreForNameCreateIfNew(name string) *spanStore {
	ssmu.RLock()
	s, ok := spanStores[name]
	ssmu.RUnlock()
	if ok {
		return s
	}
	ssmu.Lock()
	defer ssmu.Unlock()
	s, ok = spanStores[name]
	if ok {
		return s
	}
	s = newSpanStore(name, defaultBucketSize, defaultBucketSize)
	spanStores[name] = s
	return s
}

// spanStoreSetSize resizes the spanStore for the given name.
//
// It creates it if it didn't exist.
func spanStoreSetSize(name string, latencyBucketSize int, errorBucketSize int) {
	ssmu.RLock()
	s, ok := spanStores[name]
	ssmu.RUnlock()
	if ok {
		s.resize(latencyBucketSize, errorBucketSize)
		return
	}
	ssmu.Lock()
	defer ssmu.Unlock()
	s, ok = spanStores[name]
	if ok {
		s.resize(latencyBucketSize, errorBucketSize)
		return
	}
	s = newSpanStore(name, latencyBucketSize, errorBucketSize)
	spanStores[name] = s
}

func (s *spanStore) resize(latencyBucketSize int, errorBucketSize int) {
	s.mu.Lock()
	for i := range s.latency {
		s.latency[i].resize(latencyBucketSize)
	}
	for _, b := range s.errors {
		b.resize(errorBucketSize)
	}
	s.maxSpansPerErrorBucket = errorBucketSize
	s.mu.Unlock()
}

// add adds a span to the active bucket of the spanStore.
func (s *spanStore) add(span *Span) {
	s.mu.Lock()
	s.active[span] = struct{}{}
	s.mu.Unlock()
}

// finished removes a span from the active set, and adds a corresponding
// SpanData to a latency or error bucket.
func (s *spanStore) finished(span *Span, sd *SpanData) {
	latency := sd.EndTime.Sub(sd.StartTime)
	if latency < 0 {
		latency = 0
	}
	code := sd.Status.Code

	s.mu.Lock()
	delete(s.active, span)
	if code == 0 {
		s.latency[latencyBucket(latency)].add(sd)
	} else {
		if s.errors == nil {
			s.errors = make(map[int32]*bucket)
		}
		if b := s.errors[code]; b != nil {
			b.add(sd)
		} else {
			b := makeBucket(s.maxSpansPerErrorBucket)
			s.errors[code] = &b
			b.add(sd)
		}
	}
	s.mu.Unlock()
}