forked from timyates/mod-metrics
-
Notifications
You must be signed in to change notification settings - Fork 3
/
MetricsModule.java
333 lines (282 loc) · 11.6 KB
/
MetricsModule.java
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
/*
* Copyright 2012-2013 the original author or 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 org.swisspush.metrics;
import com.codahale.metrics.*;
import com.codahale.metrics.Timer.Context;
import com.codahale.metrics.jmx.JmxReporter;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class MetricsModule extends AbstractVerticle implements Handler<Message<JsonObject>> {
private MetricRegistry metrics ;
private String address ;
private Map<String,Context> timers ;
private ConcurrentMap<String,Integer> gauges ;
private JsonObject config;
private Logger logger = LoggerFactory.getLogger(MetricsModule.class);
@Override
public void start(Promise<Void> startPromise) {
logger.info("Starting MetricsModule");
config = config();
address = getOptionalStringConfig( "address", "org.swisspush.metrics" ) ;
metrics = new MetricRegistry() ;
timers = new HashMap<>() ;
gauges = new ConcurrentHashMap<>() ;
JmxReporter.forRegistry( metrics ).build().start() ;
logger.info("Register consumer for event bus address '"+address+"'");
vertx.eventBus().consumer( address, this ) ;
startPromise.complete();
}
private static Integer getOptionalInteger( JsonObject obj, String name, Integer def ) {
Integer result = obj.getInteger( name ) ;
return result == null ? def : result ;
}
public void handle( final Message<JsonObject> message ) {
if(message.body() == null){
sendError( message, "message body must be specified" ) ;
return;
}
final JsonObject body = message.body() ;
final String action = body.getString( "action" ) ;
final String name = body.getString( "name" ) ;
logger.debug("Handling message with action '"+action+"' and name '"+name+"'");
if( action == null ) {
sendError( message, "action must be specified" ) ;
return;
}
switch( action ) {
// set a gauge
case "set" :
setGauge(name, body, message);
break ;
// increment a counter
case "inc" :
incrementCounter(name, body, message);
break ;
// decrement a counter
case "dec" :
decrementCounter(name, body, message);
break ;
// Mark a meter
case "mark" :
markMeter(name, message);
break ;
// Update a histogram
case "update" :
updateHistogram(name, body, message);
break ;
// Start a timer
case "start" :
startTimer(name, message);
break ;
// Stop a timer
case "stop" :
stopTimer(name, message);
break ;
// Remove a metric if it exists
case "remove" :
removeMetric(name, message);
break ;
case "gauges" :
collectGauges(message);
break ;
case "counters" :
collectCounters(message);
break ;
case "histograms" :
collectHistograms(message);
break ;
case "meters" :
collectMeters(message);
break ;
case "timers" :
collectTimers(message);
break ;
default:
sendError( message, "Invalid action : " + action ) ;
}
}
private void setGauge(String name, JsonObject body, Message<JsonObject> message){
Integer n = body.getInteger( "n" ) ;
logger.debug("setting gauge with name '"+name+"' and value " + n);
gauges.put( name, n ) ;
if( metrics.getMetrics().get( name ) == null ) {
metrics.register( name, (Gauge<Integer>) () -> gauges.get( name )) ;
}
sendOK( message ) ;
}
private void incrementCounter(String name, JsonObject body, Message<JsonObject> message){
Integer value = getOptionalInteger( body, "n", 1 );
logger.debug("incrementing counter with name '"+name+"' by " + value);
metrics.counter( name ).inc( value ) ;
sendOK( message ) ;
}
private void decrementCounter(String name, JsonObject body, Message<JsonObject> message){
Integer value = getOptionalInteger( body, "n", 1 );
logger.debug("decrementing counter with name '"+name+"' by " + value);
metrics.counter( name ).dec( value ); ;
sendOK( message ) ;
}
private void markMeter(String name, Message<JsonObject> message){
metrics.meter( name ).mark() ;
logger.debug("marking meter with name '"+name+"'");
sendOK( message ) ;
}
private void updateHistogram(String name, JsonObject body, Message<JsonObject> message){
Integer value = body.getInteger("n");
logger.debug("updating histogram with name '"+name+"' and value " + value);
metrics.histogram( name ).update( value ) ;
sendOK( message ) ;
}
private void startTimer(String name, Message<JsonObject> message){
logger.debug("starting timer with name '"+name+"'");
timers.put( name, metrics.timer( name ).time() ) ;
sendOK( message ) ;
}
private void stopTimer(String name, Message<JsonObject> message){
logger.debug("stopping timer with name '"+name+"'");
Context c = timers.remove( name ) ;
if( c != null ) {
c.stop() ;
}
sendOK( message ) ;
}
private void removeMetric(String name, Message<JsonObject> message){
logger.debug("removing metric with name '"+name+"'");
metrics.remove( name ) ;
gauges.remove( name ) ;
sendOK( message ) ;
}
private void collectGauges(Message<JsonObject> message){
JsonObject reply = new JsonObject() ;
for( Entry<String,Gauge> entry : metrics.getGauges().entrySet() ) {
reply.put( entry.getKey(),
serialiseGauge( entry.getValue(), new JsonObject() ) ) ;
}
logger.debug("getting values for gauges. reply with " + reply.encode());
sendOK( message, reply ) ;
}
private void collectCounters(Message<JsonObject> message){
JsonObject reply = new JsonObject() ;
for( Entry<String,Counter> entry : metrics.getCounters().entrySet() ) {
reply.put( entry.getKey(),
serialiseCounting( entry.getValue(),
new JsonObject() ) ) ;
}
logger.debug("getting values for counters. reply with " + reply.encode());
sendOK( message, reply ) ;
}
private void collectHistograms(Message<JsonObject> message){
JsonObject reply = new JsonObject() ;
for( Entry<String,Histogram> entry : metrics.getHistograms().entrySet() ) {
reply.put( entry.getKey(),
serialiseSampling( entry.getValue(),
serialiseCounting( entry.getValue(),
new JsonObject() ) ) ) ;
}
logger.debug("getting values for histograms. reply with " + reply.encode());
sendOK( message, reply ) ;
}
private void collectMeters(Message<JsonObject> message){
JsonObject reply = new JsonObject() ;
for( Entry<String,Meter> entry : metrics.getMeters().entrySet() ) {
reply.put( entry.getKey(),
serialiseMetered( entry.getValue(),
new JsonObject() ) ) ;
}
logger.debug("getting values for meters. reply with " + reply.encode());
sendOK( message, reply ) ;
}
private void collectTimers(Message<JsonObject> message){
JsonObject reply = new JsonObject() ;
for( Entry<String,Timer> entry : metrics.getTimers().entrySet() ) {
reply.put( entry.getKey(),
serialiseSampling( entry.getValue(),
serialiseMetered( entry.getValue(),
new JsonObject() ) ) ) ;
}
logger.debug("getting values for timers. reply with " + reply.encode());
sendOK( message, reply ) ;
}
private JsonObject serialiseGauge( Gauge gauge, JsonObject ret ) {
ret.put( "value", (Integer)gauge.getValue() ) ;
return ret ;
}
private JsonObject serialiseCounting( Counting count, JsonObject ret ) {
ret.put( "count", count.getCount() ) ;
return ret ;
}
private JsonObject serialiseSampling( Sampling sample, JsonObject ret ) {
Snapshot snap = sample.getSnapshot() ;
ret.put( "min", snap.getMin() ) ;
ret.put( "max", snap.getMax() ) ;
ret.put( "median", snap.getMedian() ) ;
ret.put( "mean", snap.getMean() ) ;
ret.put( "stddev", snap.getStdDev() ) ;
ret.put( "size", snap.size() ) ;
ret.put( "75th", snap.get75thPercentile() ) ;
ret.put( "95th", snap.get95thPercentile() ) ;
ret.put( "98th", snap.get98thPercentile() ) ;
ret.put( "99th", snap.get99thPercentile() ) ;
ret.put( "999th", snap.get999thPercentile() ) ;
return ret ;
}
private JsonObject serialiseMetered( Metered meter, JsonObject ret ) {
ret.put( "1m", meter.getOneMinuteRate() ) ;
ret.put( "5m", meter.getFiveMinuteRate() ) ;
ret.put( "15m", meter.getFifteenMinuteRate() ) ;
ret.put( "count", meter.getCount() ) ;
ret.put( "mean", meter.getMeanRate() ) ;
return ret ;
}
private void sendError(Message<JsonObject> message, String error) {
sendError(message, error, null);
}
private void sendError(Message<JsonObject> message, String error, Exception e) {
logger.error(error, e);
JsonObject json = new JsonObject().put("status", "error").put("message", error);
message.reply(json);
}
private void sendOK(Message<JsonObject> message) {
sendOK(message, null);
}
private void sendOK(Message<JsonObject> message, JsonObject json) {
sendStatus("ok", message, json);
}
private void sendStatus(String status, Message<JsonObject> message, JsonObject json) {
if (json == null) {
json = new JsonObject();
}
json.put("status", status);
if(message.replyAddress() != null) {
logger.debug("replying message with status " + status);
}
message.reply(json);
}
private String getOptionalStringConfig(String fieldName, String defaultValue) {
String s = config.getString(fieldName);
return s == null ? defaultValue : s;
}
}