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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
|
// Copyright (c) 2021 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package tally
import (
"fmt"
"math"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/uber-go/tally/v4/internal/identity"
)
var (
capabilitiesNone = &capabilities{
reporting: false,
tagging: false,
}
capabilitiesReportingNoTagging = &capabilities{
reporting: true,
tagging: false,
}
capabilitiesReportingTagging = &capabilities{
reporting: true,
tagging: true,
}
)
type capabilities struct {
reporting bool
tagging bool
}
func (c *capabilities) Reporting() bool {
return c.reporting
}
func (c *capabilities) Tagging() bool {
return c.tagging
}
type counter struct {
prev int64
curr int64
cachedCount CachedCount
}
func newCounter(cachedCount CachedCount) *counter {
return &counter{cachedCount: cachedCount}
}
func (c *counter) Inc(v int64) {
atomic.AddInt64(&c.curr, v)
}
func (c *counter) value() int64 {
curr := atomic.LoadInt64(&c.curr)
prev := atomic.LoadInt64(&c.prev)
if prev == curr {
return 0
}
atomic.StoreInt64(&c.prev, curr)
return curr - prev
}
func (c *counter) report(name string, tags map[string]string, r StatsReporter) {
delta := c.value()
if delta == 0 {
return
}
r.ReportCounter(name, tags, delta)
}
func (c *counter) cachedReport() {
delta := c.value()
if delta == 0 {
return
}
c.cachedCount.ReportCount(delta)
}
func (c *counter) snapshot() int64 {
return atomic.LoadInt64(&c.curr) - atomic.LoadInt64(&c.prev)
}
type gauge struct {
updated uint64
curr uint64
cachedGauge CachedGauge
}
func newGauge(cachedGauge CachedGauge) *gauge {
return &gauge{cachedGauge: cachedGauge}
}
func (g *gauge) Update(v float64) {
atomic.StoreUint64(&g.curr, math.Float64bits(v))
atomic.StoreUint64(&g.updated, 1)
}
func (g *gauge) value() float64 {
return math.Float64frombits(atomic.LoadUint64(&g.curr))
}
func (g *gauge) report(name string, tags map[string]string, r StatsReporter) {
if atomic.SwapUint64(&g.updated, 0) == 1 {
r.ReportGauge(name, tags, g.value())
}
}
func (g *gauge) cachedReport() {
if atomic.SwapUint64(&g.updated, 0) == 1 {
g.cachedGauge.ReportGauge(g.value())
}
}
func (g *gauge) snapshot() float64 {
return math.Float64frombits(atomic.LoadUint64(&g.curr))
}
// NB(jra3): timers are a little special because they do no aggregate any data
// at the timer level. The reporter buffers may timer entries and periodically
// flushes.
type timer struct {
name string
tags map[string]string
reporter StatsReporter
cachedTimer CachedTimer
unreported timerValues
}
type timerValues struct {
sync.RWMutex
values []time.Duration
}
func newTimer(
name string,
tags map[string]string,
r StatsReporter,
cachedTimer CachedTimer,
) *timer {
t := &timer{
name: name,
tags: tags,
reporter: r,
cachedTimer: cachedTimer,
}
if r == nil {
t.reporter = &timerNoReporterSink{timer: t}
}
return t
}
func (t *timer) Record(interval time.Duration) {
if t.cachedTimer != nil {
t.cachedTimer.ReportTimer(interval)
} else {
t.reporter.ReportTimer(t.name, t.tags, interval)
}
}
func (t *timer) Start() Stopwatch {
return NewStopwatch(globalNow(), t)
}
func (t *timer) RecordStopwatch(stopwatchStart time.Time) {
d := globalNow().Sub(stopwatchStart)
t.Record(d)
}
func (t *timer) snapshot() []time.Duration {
t.unreported.RLock()
snap := make([]time.Duration, len(t.unreported.values))
copy(snap, t.unreported.values)
t.unreported.RUnlock()
return snap
}
type timerNoReporterSink struct {
sync.RWMutex
timer *timer
}
func (r *timerNoReporterSink) ReportCounter(
name string,
tags map[string]string,
value int64,
) {
}
func (r *timerNoReporterSink) ReportGauge(
name string,
tags map[string]string,
value float64,
) {
}
func (r *timerNoReporterSink) ReportTimer(
name string,
tags map[string]string,
interval time.Duration,
) {
r.timer.unreported.Lock()
r.timer.unreported.values = append(r.timer.unreported.values, interval)
r.timer.unreported.Unlock()
}
func (r *timerNoReporterSink) ReportHistogramValueSamples(
name string,
tags map[string]string,
buckets Buckets,
bucketLowerBound float64,
bucketUpperBound float64,
samples int64,
) {
}
func (r *timerNoReporterSink) ReportHistogramDurationSamples(
name string,
tags map[string]string,
buckets Buckets,
bucketLowerBound time.Duration,
bucketUpperBound time.Duration,
samples int64,
) {
}
func (r *timerNoReporterSink) Capabilities() Capabilities {
return capabilitiesReportingTagging
}
func (r *timerNoReporterSink) Flush() {
}
type sampleCounter struct {
counter *counter
cachedBucket CachedHistogramBucket
}
type histogram struct {
htype histogramType
name string
tags map[string]string
reporter StatsReporter
specification Buckets
buckets []histogramBucket
samples []sampleCounter
}
type histogramType int
const (
valueHistogramType histogramType = iota
durationHistogramType
)
func newHistogram(
htype histogramType,
name string,
tags map[string]string,
reporter StatsReporter,
storage bucketStorage,
cachedHistogram CachedHistogram,
) *histogram {
h := &histogram{
htype: htype,
name: name,
tags: tags,
reporter: reporter,
specification: storage.buckets,
buckets: storage.hbuckets,
samples: make([]sampleCounter, len(storage.hbuckets)),
}
for i := range h.samples {
h.samples[i].counter = newCounter(nil)
if cachedHistogram != nil {
switch htype {
case durationHistogramType:
h.samples[i].cachedBucket = cachedHistogram.DurationBucket(
durationLowerBound(storage.hbuckets, i),
storage.hbuckets[i].durationUpperBound,
)
case valueHistogramType:
h.samples[i].cachedBucket = cachedHistogram.ValueBucket(
valueLowerBound(storage.hbuckets, i),
storage.hbuckets[i].valueUpperBound,
)
}
}
}
return h
}
func (h *histogram) report(name string, tags map[string]string, r StatsReporter) {
for i := range h.buckets {
samples := h.samples[i].counter.value()
if samples == 0 {
continue
}
switch h.htype {
case valueHistogramType:
r.ReportHistogramValueSamples(
name,
tags,
h.specification,
valueLowerBound(h.buckets, i),
h.buckets[i].valueUpperBound,
samples,
)
case durationHistogramType:
r.ReportHistogramDurationSamples(
name,
tags,
h.specification,
durationLowerBound(h.buckets, i),
h.buckets[i].durationUpperBound,
samples,
)
}
}
}
func (h *histogram) cachedReport() {
for i := range h.buckets {
samples := h.samples[i].counter.value()
if samples == 0 {
continue
}
switch h.htype {
case valueHistogramType:
h.samples[i].cachedBucket.ReportSamples(samples)
case durationHistogramType:
h.samples[i].cachedBucket.ReportSamples(samples)
}
}
}
func (h *histogram) RecordValue(value float64) {
if h.htype != valueHistogramType {
return
}
// Find the highest inclusive of the bucket upper bound
// and emit directly to it. Since we use BucketPairs to derive
// buckets there will always be an inclusive bucket as
// we always have a math.MaxFloat64 bucket.
idx := sort.Search(len(h.buckets), func(i int) bool {
return h.buckets[i].valueUpperBound >= value
})
h.samples[idx].counter.Inc(1)
}
func (h *histogram) RecordDuration(value time.Duration) {
if h.htype != durationHistogramType {
return
}
// Find the highest inclusive of the bucket upper bound
// and emit directly to it. Since we use BucketPairs to derive
// buckets there will always be an inclusive bucket as
// we always have a math.MaxInt64 bucket.
idx := sort.Search(len(h.buckets), func(i int) bool {
return h.buckets[i].durationUpperBound >= value
})
h.samples[idx].counter.Inc(1)
}
func (h *histogram) Start() Stopwatch {
return NewStopwatch(globalNow(), h)
}
func (h *histogram) RecordStopwatch(stopwatchStart time.Time) {
d := globalNow().Sub(stopwatchStart)
h.RecordDuration(d)
}
func (h *histogram) snapshotValues() map[float64]int64 {
if h.htype != valueHistogramType {
return nil
}
vals := make(map[float64]int64, len(h.buckets))
for i := range h.buckets {
vals[h.buckets[i].valueUpperBound] = h.samples[i].counter.snapshot()
}
return vals
}
func (h *histogram) snapshotDurations() map[time.Duration]int64 {
if h.htype != durationHistogramType {
return nil
}
durations := make(map[time.Duration]int64, len(h.buckets))
for i := range h.buckets {
durations[h.buckets[i].durationUpperBound] = h.samples[i].counter.snapshot()
}
return durations
}
type histogramBucket struct {
valueUpperBound float64
durationUpperBound time.Duration
}
func durationLowerBound(buckets []histogramBucket, i int) time.Duration {
if i <= 0 {
return time.Duration(math.MinInt64)
}
return buckets[i-1].durationUpperBound
}
func valueLowerBound(buckets []histogramBucket, i int) float64 {
if i <= 0 {
return -math.MaxFloat64
}
return buckets[i-1].valueUpperBound
}
type bucketStorage struct {
buckets Buckets
hbuckets []histogramBucket
}
func newBucketStorage(
htype histogramType,
buckets Buckets,
) bucketStorage {
var (
pairs = BucketPairs(buckets)
storage = bucketStorage{
buckets: buckets,
hbuckets: make([]histogramBucket, 0, len(pairs)),
}
)
for _, pair := range pairs {
storage.hbuckets = append(storage.hbuckets, histogramBucket{
valueUpperBound: pair.UpperBoundValue(),
durationUpperBound: pair.UpperBoundDuration(),
})
}
return storage
}
type bucketCache struct {
mtx sync.RWMutex
cache map[uint64]bucketStorage
}
func newBucketCache() *bucketCache {
return &bucketCache{
cache: make(map[uint64]bucketStorage),
}
}
func (c *bucketCache) Get(
htype histogramType,
buckets Buckets,
) bucketStorage {
id := getBucketsIdentity(buckets)
c.mtx.RLock()
storage, ok := c.cache[id]
if !ok {
c.mtx.RUnlock()
c.mtx.Lock()
storage = newBucketStorage(htype, buckets)
c.cache[id] = storage
c.mtx.Unlock()
} else {
c.mtx.RUnlock()
if !bucketsEqual(buckets, storage.buckets) {
storage = newBucketStorage(htype, buckets)
}
}
return storage
}
// NullStatsReporter is an implementation of StatsReporter than simply does nothing.
var NullStatsReporter StatsReporter = nullStatsReporter{}
func (r nullStatsReporter) ReportCounter(name string, tags map[string]string, value int64) {
}
func (r nullStatsReporter) ReportGauge(name string, tags map[string]string, value float64) {
}
func (r nullStatsReporter) ReportTimer(name string, tags map[string]string, interval time.Duration) {
}
func (r nullStatsReporter) ReportHistogramValueSamples(
name string,
tags map[string]string,
buckets Buckets,
bucketLowerBound,
bucketUpperBound float64,
samples int64,
) {
}
func (r nullStatsReporter) ReportHistogramDurationSamples(
name string,
tags map[string]string,
buckets Buckets,
bucketLowerBound,
bucketUpperBound time.Duration,
samples int64,
) {
}
func (r nullStatsReporter) Capabilities() Capabilities {
return capabilitiesNone
}
func (r nullStatsReporter) Flush() {
}
type nullStatsReporter struct{}
func getBucketsIdentity(buckets Buckets) uint64 {
switch b := buckets.(type) {
case DurationBuckets:
return identity.Durations(b.AsDurations())
case ValueBuckets:
return identity.Float64s(b.AsValues())
default:
panic(fmt.Sprintf("unexpected bucket type: %T", b))
}
}
|