-
Notifications
You must be signed in to change notification settings - Fork 74
/
AvailabilityHandler.java
469 lines (431 loc) · 22.6 KB
/
AvailabilityHandler.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
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
/*
* Copyright 2014-2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.hawkular.metrics.api.jaxrs.handler;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.hawkular.metrics.api.jaxrs.util.ApiUtils.badRequest;
import static org.hawkular.metrics.api.jaxrs.util.ApiUtils.noContent;
import static org.hawkular.metrics.api.jaxrs.util.ApiUtils.serverError;
import static org.hawkular.metrics.model.MetricType.AVAILABILITY;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.regex.PatternSyntaxException;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.hawkular.metrics.api.jaxrs.QueryRequest;
import org.hawkular.metrics.api.jaxrs.handler.observer.MetricCreatedObserver;
import org.hawkular.metrics.api.jaxrs.handler.observer.ResultSetObserver;
import org.hawkular.metrics.api.jaxrs.handler.template.IMetricsHandler;
import org.hawkular.metrics.api.jaxrs.handler.transformer.MinMaxTimestampTransformer;
import org.hawkular.metrics.api.jaxrs.util.ApiUtils;
import org.hawkular.metrics.core.service.Functions;
import org.hawkular.metrics.core.service.Order;
import org.hawkular.metrics.model.ApiError;
import org.hawkular.metrics.model.AvailabilityBucketPoint;
import org.hawkular.metrics.model.AvailabilityType;
import org.hawkular.metrics.model.Buckets;
import org.hawkular.metrics.model.DataPoint;
import org.hawkular.metrics.model.Metric;
import org.hawkular.metrics.model.MetricId;
import org.hawkular.metrics.model.MetricType;
import org.hawkular.metrics.model.param.BucketConfig;
import org.hawkular.metrics.model.param.Duration;
import org.hawkular.metrics.model.param.TagNames;
import org.hawkular.metrics.model.param.Tags;
import org.hawkular.metrics.model.param.TimeRange;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import rx.Observable;
/**
* @author Stefan Negrea
*
*/
@Path("/availability")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@Api(tags = "Availability")
@ApplicationScoped
public class AvailabilityHandler extends MetricsServiceHandler implements IMetricsHandler<AvailabilityType> {
@POST
@Path("/")
@ApiOperation(value = "Create availability metric.", notes = "Same notes as creating gauge metric apply.")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Metric created successfully"),
@ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class),
@ApiResponse(code = 409, message = "Availability metric with given id already exists",
response = ApiError.class),
@ApiResponse(code = 500, message = "Metric creation failed due to an unexpected error",
response = ApiError.class)
})
public void createMetric(
@Suspended final AsyncResponse asyncResponse,
@ApiParam(required = true) Metric<AvailabilityType> metric,
@ApiParam(value = "Overwrite previously created metric configuration if it exists. "
+ "Only data retention and tags are overwriten; existing data points are unnafected. Defaults to false.",
required = false) @DefaultValue("false") @QueryParam("overwrite") Boolean overwrite,
@Context UriInfo uriInfo
) {
if (metric.getType() != null
&& MetricType.UNDEFINED != metric.getType()
&& MetricType.AVAILABILITY != metric.getType()) {
asyncResponse.resume(badRequest(new ApiError("Metric type does not match " + MetricType
.AVAILABILITY.getText())));
}
URI location = uriInfo.getBaseUriBuilder().path("/availability/{id}").build(metric.getId());
metric = new Metric<>(
new MetricId<>(getTenant(), AVAILABILITY, metric.getMetricId().getName()), metric.getTags(),
metric.getDataRetention());
metricsService.createMetric(metric, overwrite).subscribe(new MetricCreatedObserver(asyncResponse, location));
}
@GET
@Path("/")
@ApiOperation(value = "Find tenant's metric definitions.",
notes = "Does not include any metric values. ",
response = Metric.class, responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved at least one metric definition."),
@ApiResponse(code = 204, message = "No metrics found."),
@ApiResponse(code = 400, message = "Invalid type parameter type.", response = ApiError.class),
@ApiResponse(code = 500, message = "Failed to retrieve metrics due to unexpected error.",
response = ApiError.class)
})
public void getMetrics(
@Suspended AsyncResponse asyncResponse,
@ApiParam(value = "List of tags filters", required = false) @QueryParam("tags") Tags tags) {
Observable<Metric<AvailabilityType>> metricObservable = (tags == null)
? metricsService.findMetrics(getTenant(), AVAILABILITY)
: metricsService.findMetricsWithFilters(getTenant(), AVAILABILITY, tags.getTags());
metricObservable
.compose(new MinMaxTimestampTransformer<>(metricsService))
.toList()
.map(ApiUtils::collectionToResponse)
.subscribe(asyncResponse::resume, t -> {
if (t instanceof PatternSyntaxException) {
asyncResponse.resume(badRequest(t));
} else {
asyncResponse.resume(serverError(t));
}
});
}
@GET
@Path("/{id}")
@ApiOperation(value = "Retrieve single metric definition.", response = Metric.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Metric's definition was successfully retrieved."),
@ApiResponse(code = 204, message = "Query was successful, but no metrics definition is set."),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric's definition.",
response = ApiError.class) })
public void getMetric(@Suspended final AsyncResponse asyncResponse, @PathParam("id") String id) {
metricsService.findMetric(new MetricId<>(getTenant(), AVAILABILITY, id))
.compose(new MinMaxTimestampTransformer<>(metricsService))
.map(metric -> Response.ok(metric).build())
.switchIfEmpty(Observable.just(noContent()))
.subscribe(asyncResponse::resume, t -> asyncResponse.resume(serverError(t)));
}
@GET
@Path("/tags/{tags}")
@ApiOperation(value = "Retrieve availability type's tag values", response = Map.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Tags successfully retrieved."),
@ApiResponse(code = 204, message = "No matching tags were found"),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching tags.",
response = ApiError.class)
})
public void getTags(@Suspended final AsyncResponse asyncResponse,
@ApiParam("Tag query") @PathParam("tags") Tags tags) {
metricsService.getTagValues(getTenant(), AVAILABILITY, tags.getTags())
.map(ApiUtils::mapToResponse)
.subscribe(asyncResponse::resume, t -> asyncResponse.resume(ApiUtils.serverError(t)));
}
@GET
@Path("/{id}/tags")
@ApiOperation(value = "Retrieve tags associated with the metric definition.", response = String.class,
responseContainer = "Map")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Metric's tags were successfully retrieved."),
@ApiResponse(code = 204, message = "Query was successful, but no metrics were found."),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric's tags.",
response = ApiError.class) })
public void getMetricTags(
@Suspended final AsyncResponse asyncResponse,
@PathParam("id") String id
) {
metricsService.getMetricTags(new MetricId<>(getTenant(), AVAILABILITY, id))
.map(ApiUtils::mapToResponse)
.subscribe(asyncResponse::resume, t -> asyncResponse.resume(ApiUtils.serverError(t)));
}
@PUT
@Path("/{id}/tags")
@ApiOperation(value = "Update tags associated with the metric definition.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Metric's tags were successfully updated."),
@ApiResponse(code = 500, message = "Unexpected error occurred while updating metric's tags.",
response = ApiError.class) })
public void updateMetricTags(
@Suspended final AsyncResponse asyncResponse,
@PathParam("id") String id,
@ApiParam(required = true) Map<String, String> tags
) {
Metric<AvailabilityType> metric = new Metric<>(new MetricId<>(getTenant(), AVAILABILITY, id));
metricsService.addTags(metric, tags).subscribe(new ResultSetObserver(asyncResponse));
}
@DELETE
@Path("/{id}/tags/{tags}")
@ApiOperation(value = "Delete tags associated with the metric definition.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Metric's tags were successfully deleted."),
@ApiResponse(code = 400, message = "Invalid tags", response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error occurred while trying to delete metric's tags.",
response = ApiError.class) })
public void deleteMetricTags(
@Suspended final AsyncResponse asyncResponse,
@PathParam("id") String id,
@ApiParam(value = "Tag names", allowableValues = "Comma-separated list of tag names")
@PathParam("tags") TagNames tags
) {
Metric<AvailabilityType> metric = new Metric<>(new MetricId<>(getTenant(), AVAILABILITY, id));
metricsService.deleteTags(metric, tags.getNames()).subscribe(new ResultSetObserver(asyncResponse));
}
@POST
@Path("/{id}/raw")
@ApiOperation(value = "Add data for a single availability metric.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Adding data succeeded."),
@ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data",
response = ApiError.class)
})
public void addMetricData(
@Suspended final AsyncResponse asyncResponse, @PathParam("id") String id,
@ApiParam(value = "List of availability datapoints", required = true) List<DataPoint<AvailabilityType>> data
) {
Observable<Metric<AvailabilityType>> metrics = Functions.dataPointToObservable(getTenant(), id, data,
AVAILABILITY);
Observable<Void> observable = metricsService.addDataPoints(AVAILABILITY, metrics);
observable.subscribe(new ResultSetObserver(asyncResponse));
}
@Deprecated
@POST
@Path("/{id}/data")
@ApiOperation(value = "Deprecated. Please use /raw endpoint.")
public void deprecatedAddAvailabilityForMetric(
@Suspended final AsyncResponse asyncResponse, @PathParam("id") String id,
@ApiParam(value = "List of availability datapoints", required = true)
List<DataPoint<AvailabilityType>> data) {
addMetricData(asyncResponse, id, data);
}
@POST
@Path("/raw")
@ApiOperation(value = "Add metric data for multiple availability metrics in a single call.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Adding data succeeded."),
@ApiResponse(code = 400, message = "Missing or invalid payload", response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error happened while storing the data",
response = ApiError.class)
})
public void addData(
@Suspended final AsyncResponse asyncResponse,
@ApiParam(value = "List of availability metrics", required = true)
@JsonDeserialize()
List<Metric<AvailabilityType>> availabilities
) {
Observable<Metric<AvailabilityType>> metrics = Functions.metricToObservable(getTenant(), availabilities,
AVAILABILITY);
Observable<Void> observable = metricsService.addDataPoints(AVAILABILITY, metrics);
observable.subscribe(new ResultSetObserver(asyncResponse));
}
@POST
@Path("/raw/query")
@ApiOperation(value = "Fetch raw data points for multiple metrics. This endpoint is experimental and may " +
"undergo non-backwards compatible changes in future releases.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully fetched metric data points."),
@ApiResponse(code = 204, message = "Query was successful, but no data was found."),
@ApiResponse(code = 400, message = "No metric ids are specified", response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching metric data.",
response = ApiError.class)
})
public void getData(
@Suspended AsyncResponse asyncResponse,
@ApiParam(required = true, value = "Query parameters that minimally must include a list of metric ids. " +
"The standard start, end, order, and limit query parameters are supported as well.")
QueryRequest query) {
findRawDataPointsForMetrics(asyncResponse, query, AVAILABILITY);
}
@Deprecated
@POST
@Path("/data")
@ApiOperation(value = "Deprecated. Please use /raw endpoint.")
public void deprecatedAddAvailabilityData(
@Suspended final AsyncResponse asyncResponse,
@ApiParam(value = "List of availability metrics", required = true)
@JsonDeserialize() List<Metric<AvailabilityType>> availabilities
) {
addData(asyncResponse, availabilities);
}
@Deprecated
@GET
@Path("/{id}/data")
@ApiOperation(value = "Deprecated. Please use /raw or /stats endpoints.", response = DataPoint.class,
responseContainer = "List")
public void deprecatedFindAvailabilityData(
@Suspended AsyncResponse asyncResponse,
@PathParam("id") String id,
@ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") String start,
@ApiParam(value = "Defaults to now") @QueryParam("end") String end,
@ApiParam(value = "Total number of buckets") @QueryParam("buckets") Integer bucketsCount,
@ApiParam(value = "Bucket duration") @QueryParam("bucketDuration") Duration bucketDuration,
@ApiParam(value = "Set to true to return only distinct, contiguous values")
@QueryParam("distinct") @DefaultValue("false") Boolean distinct,
@ApiParam(value = "Limit the number of data points returned") @QueryParam("limit") Integer limit,
@ApiParam(value = "Data point sort order, based on timestamp") @QueryParam("order") Order order
) {
if ((bucketsCount != null || bucketDuration != null) &&
(limit != null || order != null)) {
asyncResponse.resume(badRequest(new ApiError("Limit and order cannot be used with bucketed results")));
return;
}
TimeRange timeRange = new TimeRange(start, end);
if (!timeRange.isValid()) {
asyncResponse.resume(badRequest(new ApiError(timeRange.getProblem())));
return;
}
BucketConfig bucketConfig = new BucketConfig(bucketsCount, bucketDuration, timeRange);
if (!bucketConfig.isValid()) {
asyncResponse.resume(badRequest(new ApiError(bucketConfig.getProblem())));
return;
}
MetricId<AvailabilityType> metricId = new MetricId<>(getTenant(), AVAILABILITY, id);
Buckets buckets = bucketConfig.getBuckets();
if (buckets == null) {
if (limit == null) {
limit = 0;
}
if (order == null) {
order = Order.defaultValue(limit, start, end);
}
metricsService
.findAvailabilityData(metricId, timeRange.getStart(), timeRange.getEnd(), distinct, limit, order)
.toList()
.map(ApiUtils::collectionToResponse)
.subscribe(asyncResponse::resume, t -> asyncResponse.resume(serverError(t)));
} else {
metricsService.findAvailabilityStats(metricId, timeRange.getStart(), timeRange.getEnd(), buckets)
.map(ApiUtils::collectionToResponse)
.subscribe(asyncResponse::resume, t -> asyncResponse.resume(serverError(t)));
}
}
@GET
@Path("/{id}/raw")
@ApiOperation(value = "Retrieve availability data.", response = DataPoint.class, responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully fetched availability data."),
@ApiResponse(code = 204, message = "No availability data was found."),
@ApiResponse(code = 400, message = "buckets or bucketDuration parameter is invalid, or both are used.",
response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching availability data.",
response = ApiError.class)
})
public void getMetricData(
@Suspended AsyncResponse asyncResponse,
@PathParam("id") String id,
@ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") String start,
@ApiParam(value = "Defaults to now") @QueryParam("end") String end,
@ApiParam(value = "Set to true to return only distinct, contiguous values")
@QueryParam("distinct") @DefaultValue("false") Boolean distinct,
@ApiParam(value = "Limit the number of data points returned") @QueryParam("limit") Integer limit,
@ApiParam(value = "Data point sort order, based on timestamp") @QueryParam("order") Order order
) {
TimeRange timeRange = new TimeRange(start, end);
if (!timeRange.isValid()) {
asyncResponse.resume(badRequest(new ApiError(timeRange.getProblem())));
return;
}
MetricId<AvailabilityType> metricId = new MetricId<>(getTenant(), AVAILABILITY, id);
if (limit == null) {
limit = 0;
}
if (order == null) {
order = Order.defaultValue(limit, start, end);
}
metricsService
.findAvailabilityData(metricId, timeRange.getStart(), timeRange.getEnd(), distinct, limit, order)
.toList()
.map(ApiUtils::collectionToResponse)
.subscribe(asyncResponse::resume, t -> asyncResponse.resume(serverError(t)));
}
@GET
@Path("/{id}/stats")
@ApiOperation(value = "Retrieve availability data.", notes = "Based on buckets or bucketDuration query parameter" +
", the time range between start and end will be divided in buckets of equal duration, and " +
"availability statistics will be computed for each bucket.", response = AvailabilityBucketPoint.class,
responseContainer = "List")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully fetched availability data."),
@ApiResponse(code = 204, message = "No availability data was found."),
@ApiResponse(code = 400, message = "buckets or bucketDuration parameter is invalid, or both are used.",
response = ApiError.class),
@ApiResponse(code = 500, message = "Unexpected error occurred while fetching availability data.",
response = ApiError.class)
})
public void getMetricStats(
@Suspended AsyncResponse asyncResponse,
@PathParam("id") String id,
@ApiParam(value = "Defaults to now - 8 hours") @QueryParam("start") String start,
@ApiParam(value = "Defaults to now") @QueryParam("end") String end,
@ApiParam(value = "Total number of buckets") @QueryParam("buckets") Integer bucketsCount,
@ApiParam(value = "Bucket duration") @QueryParam("bucketDuration") Duration bucketDuration) {
TimeRange timeRange = new TimeRange(start, end);
if (!timeRange.isValid()) {
asyncResponse.resume(badRequest(new ApiError(timeRange.getProblem())));
return;
}
BucketConfig bucketConfig = new BucketConfig(bucketsCount, bucketDuration, timeRange);
if (!bucketConfig.isValid()) {
asyncResponse.resume(badRequest(new ApiError(bucketConfig.getProblem())));
return;
}
if (bucketConfig.isEmpty()) {
asyncResponse.resume(badRequest(new ApiError(
"Either the buckets or bucketDuration parameter must be used")));
return;
}
MetricId<AvailabilityType> metricId = new MetricId<>(getTenant(), AVAILABILITY, id);
Buckets buckets = bucketConfig.getBuckets();
metricsService.findAvailabilityStats(metricId, timeRange.getStart(), timeRange.getEnd(), buckets)
.map(ApiUtils::collectionToResponse)
.subscribe(asyncResponse::resume, t -> asyncResponse.resume(serverError(t)));
}
}