aboutsummaryrefslogtreecommitdiff
path: root/kamon-core/src/main/scala/kamon/metric/Registry.scala
blob: 3f549802edf201b9771278e0ef93984efadceb45 (plain) (blame)
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
package kamon
package metric

import java.time.Duration
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.atomic.AtomicReference

import com.typesafe.config.{Config, ConfigFactory}
import com.typesafe.scalalogging.Logger
import kamon.metric.instrument._
import kamon.util.MeasurementUnit

import scala.collection.concurrent.TrieMap
/*


Kamon.metrics.histogram("http.latency").withMeasurementUnit(Time.Microseconds)


Histogram.create("http.latency", Time.Milliseconds)



val histogram = Histogram.builder("http.latency")
  .tag("method", "get")
  .build()


val actorMetrics = MetricGroup("method" -> "get")


val actorMetrics = MetricGroup.builder()
  .tag("method", "get")
  .build()

actorMetrics.histogram(

Options for a Histogram:
  - MeasurementUnit
  - Dynamic Range

HistogramConfig.forLatency().inMicroseconds()

Kamon.metrics.histogram("http.latency").withoutTags()
Kamon.metrics.histogram("http.latency").withTag("method", "get")




Kamon.metrics.histogram("http.latency", Tag.of("color", "blue"), Tag.of("color", "blue"))

Kamon.histogram(named("http.latency").withTag("path", path))
Kamon.counter(named("http.latency").withTag("path", path))








val group = Kamon.metrics.group(tags = Map("path" -> "/my-system/user/test-actor"))
val processingTime = group.histogram("processing-time")



  def histogram(name: String): Histogram =
    histogram(name, MeasurementUnit.none)

  def histogram(name: String, unit: MeasurementUnit): Histogram =
    histogram(name, unit, Map.empty)

  def histogram(name: String, unit: MeasurementUnit, tags: Map[String, String]): Histogram =
    histogram(name, unit, tags, DynamicRange.Default)



 */

trait MetricLookup {

  def histogram(name: String): Histogram =
    histogram(name, MeasurementUnit.none)

  def histogram(name: String, unit: MeasurementUnit): Histogram =
    histogram(name, unit, Map.empty)

  def histogram(name: String, unit: MeasurementUnit, tags: Map[String, String]): Histogram =
    histogram(name, unit, tags, None)

  def histogram(name: String, unit: MeasurementUnit, tags: Map[String, String], dynamicRange: DynamicRange): Histogram =
    histogram(name, unit, tags, Some(dynamicRange))

  def histogram(name: String, unit: MeasurementUnit, tags: Map[String, String], dynamicRange: Option[DynamicRange]): Histogram

}

class Registry(initialConfig: Config) extends RegistrySnapshotGenerator {
  private val logger = Logger(classOf[Registry])
  private val metrics = TrieMap.empty[String, MetricEntry]
  private val instrumentFactory = new AtomicReference[InstrumentFactory]()
  reconfigure(initialConfig)

  def reconfigure(config: Config): Unit = synchronized {
    instrumentFactory.set(InstrumentFactory.fromConfig(config))
  }

  def histogram(name: String, unit: MeasurementUnit, tags: Map[String, String], dynamicRange: Option[DynamicRange]): Histogram =
    lookupInstrument(name, unit, tags, InstrumentType.Histogram, instrumentFactory.get().buildHistogram(dynamicRange))

  def counter(name: String, unit: MeasurementUnit, tags: Map[String, String]): Counter =
    lookupInstrument(name, unit, tags, InstrumentType.Counter, instrumentFactory.get().buildCounter)

  def gauge(name: String, unit: MeasurementUnit, tags: Map[String, String]): Gauge =
    lookupInstrument(name, unit, tags, InstrumentType.Gauge, instrumentFactory.get().buildGauge)

  def minMaxCounter(name: String, unit: MeasurementUnit, tags: Map[String, String], dynamicRange: Option[DynamicRange], sampleInterval: Option[Duration]): MinMaxCounter =
    lookupInstrument(name, unit, tags, InstrumentType.MinMaxCounter, instrumentFactory.get().buildMinMaxCounter(dynamicRange, sampleInterval))


  override def snapshot(): RegistrySnapshot = synchronized {
    var histograms = Seq.empty[DistributionSnapshot]
    var mmCounters = Seq.empty[DistributionSnapshot]
    var counters = Seq.empty[SingleValueSnapshot]
    var gauges = Seq.empty[SingleValueSnapshot]

    for {
      metricEntry <- metrics.values
      instrument  <- metricEntry.instruments.values
    } {
      metricEntry.instrumentType match {
        case InstrumentType.Histogram     => histograms = histograms :+ instrument.asInstanceOf[SnapshotableHistogram].snapshot()
        case InstrumentType.MinMaxCounter => mmCounters = mmCounters :+ instrument.asInstanceOf[SnapshotableMinMaxCounter].snapshot()
        case InstrumentType.Gauge         => gauges = gauges :+ instrument.asInstanceOf[SnapshotableGauge].snapshot()
        case InstrumentType.Counter       => counters = counters :+ instrument.asInstanceOf[SnapshotableCounter].snapshot()
      }
    }

    RegistrySnapshot(histograms, mmCounters, gauges, counters)
  }

  private def lookupInstrument[T](name: String, measurementUnit: MeasurementUnit, tags: Map[String, String],
      instrumentType: InstrumentType, builder: (String, Map[String, String], MeasurementUnit) => T): T = {

    val entry = metrics.atomicGetOrElseUpdate(name, MetricEntry(instrumentType, measurementUnit, TrieMap.empty))
    if(entry.instrumentType != instrumentType)
      sys.error(s"Tried to use metric [$name] as a [${instrumentType.name}] but it is already defined as [${entry.instrumentType.name}] ")

    if(entry.unit != measurementUnit)
      logger.warn("Ignoring attempt to use measurement unit [{}] on metric [name={}, tags={}], the metric uses [{}]",
        measurementUnit.magnitude.name, name, tags.prettyPrint(), entry.unit.magnitude.name)

    entry.instruments.getOrElseUpdate(tags, builder(name, tags, measurementUnit)).asInstanceOf[T]
  }

  private case class InstrumentType(name: String)
  private object InstrumentType {
    val Histogram     = InstrumentType("Histogram")
    val MinMaxCounter = InstrumentType("MinMaxCounter")
    val Counter       = InstrumentType("Counter")
    val Gauge         = InstrumentType("Gauge")
  }

  private case class MetricEntry(instrumentType: InstrumentType, unit: MeasurementUnit, instruments: TrieMap[Map[String, String], Any])
}



//
//
//trait RecorderRegistry {
//  def shouldTrack(entity: Entity): Boolean
//  def getRecorder(entity: Entity): EntityRecorder
//  def removeRecorder(entity: Entity): Boolean
//}
//
//class RecorderRegistryImpl(initialConfig: Config) extends RecorderRegistry {
//  private val scheduler = new ScheduledThreadPoolExecutor(1, numberedThreadFactory("kamon.metric.refresh-scheduler"))
//  private val instrumentFactory = new AtomicReference[InstrumentFactory]()
//  private val entityFilter = new AtomicReference[Filter]()
//  private val entities = TrieMap.empty[Entity, EntityRecorder with EntitySnapshotProducer]
//
//  reconfigure(initialConfig)
//
//
//  override def shouldTrack(entity: Entity): Boolean =
//    entityFilter.get().accept(entity)
//
//  override def getRecorder(entity: Entity): EntityRecorder =
//    entities.atomicGetOrElseUpdate(entity, new DefaultEntityRecorder(entity, instrumentFactory.get(), scheduler))
//
//  override def removeRecorder(entity: Entity): Boolean =
//    entities.remove(entity).nonEmpty
//
//  private[kamon] def reconfigure(config: Config): Unit = synchronized {
//    instrumentFactory.set(InstrumentFactory.fromConfig(config))
//    entityFilter.set(Filter.fromConfig(config))
//
//    val refreshSchedulerPoolSize = config.getInt("kamon.metric.refresh-scheduler-pool-size")
//    scheduler.setCorePoolSize(refreshSchedulerPoolSize)
//  }
//
//  //private[kamon] def diagnosticData
//}
//
//case class RecorderRegistryDiagnostic(entities: Seq[Entity])
//


object Test extends App {
  val registry = new Registry(ConfigFactory.load())

  println(registry.histogram("test-1", MeasurementUnit.none, Map.empty, Some(DynamicRange.Default)).dynamicRange)
  println(registry.histogram("test-2", MeasurementUnit.none, Map.empty, Option(DynamicRange.Fine)).dynamicRange)

  println(Kamon.histogram("my-test"))
}