aboutsummaryrefslogtreecommitdiff
path: root/kamon-core
diff options
context:
space:
mode:
authorIvan Topolnjak <ivantopo@gmail.com>2017-12-13 00:48:14 +0100
committerIvan Topolnjak <ivantopo@gmail.com>2017-12-13 00:48:42 +0100
commitd9cd75db039b31eec8d7271b162ea822d1d4d5e3 (patch)
tree5c7319823da604af4093a7c1cc2a9df09b718832 /kamon-core
parentc10d93c4594b25b82fd2acc89fea18035ffcbc6f (diff)
downloadKamon-d9cd75db039b31eec8d7271b162ea822d1d4d5e3.tar.gz
Kamon-d9cd75db039b31eec8d7271b162ea822d1d4d5e3.tar.bz2
Kamon-d9cd75db039b31eec8d7271b162ea822d1d4d5e3.zip
add PeriodSnapshotAccumulator, successor of 0.6.x TickMetricSnapshotBuffer
Diffstat (limited to 'kamon-core')
-rw-r--r--kamon-core/src/main/scala/kamon/metric/Accumulator.scala141
1 files changed, 141 insertions, 0 deletions
diff --git a/kamon-core/src/main/scala/kamon/metric/Accumulator.scala b/kamon-core/src/main/scala/kamon/metric/Accumulator.scala
index 9f7c6d70..79713336 100644
--- a/kamon-core/src/main/scala/kamon/metric/Accumulator.scala
+++ b/kamon-core/src/main/scala/kamon/metric/Accumulator.scala
@@ -15,6 +15,13 @@
package kamon.metric
+import java.time.{Duration, Instant}
+
+import kamon.{Kamon, Tags}
+import kamon.metric.PeriodSnapshotAccumulator.{MetricDistributionKey, MetricValueKey}
+
+import scala.collection.mutable
+
class DistributionAccumulator(dynamicRange: DynamicRange) {
private val accumulatorHistogram = new HdrHistogram("metric-distribution-accumulator",
@@ -26,3 +33,137 @@ class DistributionAccumulator(dynamicRange: DynamicRange) {
def result(resetState: Boolean): Distribution =
accumulatorHistogram.snapshot(resetState).distribution
}
+
+/**
+ * Merges snapshots over the specified duration and produces a snapshot with all merged metrics provided to it within
+ * the period. This class is mutable, not thread safe and assumes that all snapshots passed to the `accumulate(...)`
+ * function are ordered in time.
+ *
+ * The typical use of this class would be when writing metric reporters that have to report data at a specific interval
+ * and wants to protect from users configuring a more frequent metrics tick interval. Example:
+ *
+ * {{{
+ * class Reporter extends MetricsReporter {
+ * val accumulator = new PeriodSnapshotAccumulator(Duration.ofSeconds(60), Duration.ofSeconds(1))
+ *
+ * def reportPeriodSnapshot(snapshot: PeriodSnapshot): Unit = {
+ * accumulator.add(snapshot).foreach(accumulatedSnapshot => {
+ * // Process your snapshot here, will only be called when the expected period has passed.
+ * }
+ * }
+ *
+ * ...
+ * }
+ * }}}
+ *
+ * The margin time is used to determine how close the current accumulated interval can to be to the expected interval
+ * and still get reported. In the example above a accumulated period of 59.6 seconds has a margin to 60 seconds of
+ * 0.4 seconds, thus, getting reported immediately instead of waiting for the next snapshot.
+ *
+ * A detail of what has been accumulated by calling the `.peek()` function.
+ *
+ * @param duration for how long to accumulate snapshots
+ * @param margin error margin for expected reporting period
+ */
+class PeriodSnapshotAccumulator(duration: Duration, margin: Duration) {
+ private val minimumDuration = duration.minus(margin)
+ private val counters = mutable.Map[MetricValueKey, Long]()
+ private val gauges = mutable.Map[MetricValueKey, Long]()
+ private val histograms = mutable.Map[MetricDistributionKey, DistributionAccumulator]()
+ private val rangeSamplers = mutable.Map[MetricDistributionKey, DistributionAccumulator]()
+
+ private var accumulatingFrom: Option[Instant] = None
+
+ def add(periodSnapshot: PeriodSnapshot): Option[PeriodSnapshot] = {
+ // short-circuit if there is no need to accumulate (e.g. when metrics tick-interval is the same as duration or the
+ // snapshots have a longer period than the duration).
+ if(isSameDurationAsTickInterval() || isWithinDurationMargin(periodSnapshot.from, periodSnapshot.to)) Some(periodSnapshot) else {
+ if (accumulatingFrom.isEmpty)
+ accumulatingFrom = Some(periodSnapshot.from)
+
+ periodSnapshot.metrics.counters.foreach(c => accumulateValue(counters, c))
+ periodSnapshot.metrics.gauges.foreach(g => replaceValue(gauges, g))
+ periodSnapshot.metrics.histograms.foreach(h => accumulateDistribution(histograms, h))
+ periodSnapshot.metrics.rangeSamplers.foreach(rs => accumulateDistribution(rangeSamplers, rs))
+
+ for(from <- accumulatingFrom if isWithinDurationMargin(from, periodSnapshot.to)) yield {
+ val accumulatedPeriodSnapshot = buildPeriodSnapshot(from, periodSnapshot.to, resetState = true)
+ accumulatingFrom = None
+ clearAccumulatedData()
+
+ accumulatedPeriodSnapshot
+ }
+ }
+ }
+
+ def peek(): PeriodSnapshot = {
+ val now = Kamon.clock().instant()
+ buildPeriodSnapshot(accumulatingFrom.getOrElse(now), now, resetState = false)
+ }
+
+ private def isWithinDurationMargin(from: Instant, to: Instant): Boolean = {
+ !Duration.between(from, to).minus(minimumDuration).isNegative
+ }
+
+ private def isSameDurationAsTickInterval(): Boolean = {
+ Kamon.config().getDuration("kamon.metric.tick-interval").equals(duration)
+ }
+
+ private def buildPeriodSnapshot(from: Instant, to: Instant, resetState: Boolean): PeriodSnapshot = {
+ val metrics = MetricsSnapshot(
+ histograms = histograms.map(createDistributionSnapshot(resetState)).toSeq,
+ rangeSamplers = rangeSamplers.map(createDistributionSnapshot(resetState)).toSeq,
+ gauges = gauges.map(createValueSnapshot(resetState)).toSeq,
+ counters = counters.map(createValueSnapshot(resetState)).toSeq
+ )
+
+ PeriodSnapshot(from, to, metrics)
+ }
+
+ private def accumulateValue(cache: mutable.Map[MetricValueKey, Long], metric: MetricValue): Unit = {
+ val key = MetricValueKey(metric.name, metric.tags, metric.unit)
+ cache.get(key).map(previousValue => {
+ cache.put(key, metric.value + previousValue)
+ }).orElse {
+ cache.put(key, metric.value)
+ }
+ }
+
+ private def replaceValue(cache: mutable.Map[MetricValueKey, Long], metric: MetricValue): Unit = {
+ val key = MetricValueKey(metric.name, metric.tags, metric.unit)
+ cache.put(key, metric.value)
+ }
+
+ private def createValueSnapshot(reset: Boolean)(pair: (MetricValueKey, Long)): MetricValue = {
+ val (key, value) = pair
+ MetricValue(key.name, key.tags, key.unit, value)
+ }
+
+ private def createDistributionSnapshot(resetState: Boolean)(pair: (MetricDistributionKey, DistributionAccumulator)): MetricDistribution = {
+ val (key, value) = pair
+ MetricDistribution(key.name, key.tags, key.unit, key.dynamicRange, value.result(resetState))
+ }
+
+ private def accumulateDistribution(cache: mutable.Map[MetricDistributionKey, DistributionAccumulator], metric: MetricDistribution): Unit = {
+ val key = MetricDistributionKey(metric.name, metric.tags, metric.unit, metric.dynamicRange)
+ cache.get(key).map(previousValue => {
+ previousValue.add(metric.distribution)
+ }).orElse {
+ val distributionAccumulator = new DistributionAccumulator(key.dynamicRange)
+ distributionAccumulator.add(metric.distribution)
+ cache.put(key, distributionAccumulator)
+ }
+ }
+
+ private def clearAccumulatedData(): Unit = {
+ histograms.clear()
+ rangeSamplers.clear()
+ counters.clear()
+ gauges.clear()
+ }
+}
+
+object PeriodSnapshotAccumulator {
+ case class MetricValueKey(name: String, tags: Tags, unit: MeasurementUnit)
+ case class MetricDistributionKey(name: String, tags: Tags, unit: MeasurementUnit, dynamicRange: DynamicRange)
+}