forked from grafana/kairosdb-datasource
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datasource.js
494 lines (421 loc) · 13.7 KB
/
datasource.js
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
define([
'angular',
'lodash',
'app/plugins/sdk',
'app/core/utils/datemath',
'app/core/utils/kbn',
'./query_ctrl'
],
function (angular, _, sdk, dateMath, kbn) {
'use strict';
var self;
function KairosDBDatasource(instanceSettings, $q, backendSrv, templateSrv) {
this.type = instanceSettings.type;
this.url = instanceSettings.url;
this.name = instanceSettings.name;
this.supportMetrics = true;
this.q = $q;
this.backendSrv = backendSrv;
this.templateSrv = templateSrv;
self = this;
}
// Called once per panel (graph)
KairosDBDatasource.prototype.query = function(options) {
var start = options.rangeRaw.from;
var end = options.rangeRaw.to;
var queries = _.compact(_.map(options.targets, _.partial(convertTargetToQuery, options)));
var plotParams = _.compact(_.map(options.targets, function(target) {
var alias = self.templateSrv.replace(target.alias);
if (typeof target.alias === 'undefined' || target.alias === "") {
alias = self.templateSrv.replace(target.metric);
}
if (!target.hide) {
return { alias: alias, exouter: target.exOuter };
}
else {
return null;
}
}));
var handleKairosDBQueryResponseAlias = _.partial(handleKairosDBQueryResponse, plotParams);
// No valid targets, return the empty result to save a round trip.
if (_.isEmpty(queries)) {
var d = this.q.defer();
d.resolve({ data: [] });
return d.promise;
}
return this.performTimeSeriesQuery(queries, start, end)
.then(handleKairosDBQueryResponseAlias, handleQueryError);
};
KairosDBDatasource.prototype.performTimeSeriesQuery = function(queries, start, end) {
var reqBody = {
metrics: queries,
cache_time: 0
};
convertToKairosTime(start, reqBody, 'start');
convertToKairosTime(end, reqBody, 'end');
var options = {
method: 'POST',
url: this.url + '/api/v1/datapoints/query',
data: reqBody
};
return this.backendSrv.datasourceRequest(options);
};
/**
* Gets the list of metrics
* @returns {*|Promise}
*/
KairosDBDatasource.prototype._performMetricSuggestQuery = function(metric) {
var options = {
url: this.url + '/api/v1/metricnames',
method: 'GET'
};
return this.backendSrv.datasourceRequest(options).then(function(response) {
if (!response.data) {
return this.q.when([]);
}
var metrics = [];
_.each(response.data.results, function(r) {
if (r.indexOf(metric) >= 0) {
metrics.push(r);
}
});
return metrics;
});
};
KairosDBDatasource.prototype._performMetricKeyLookup = function(metric) {
if(!metric) { return this.q.when([]); }
var options = {
method: 'POST',
url: this.url + '/api/v1/datapoints/query/tags',
data: {
metrics: [{ name: metric }],
cache_time: 0,
start_absolute: 0
}
};
return this.backendSrv.datasourceRequest(options).then(function(result) {
if (!result.data) {
return this.q.when([]);
}
var tagks = [];
_.each(result.data.queries[0].results[0].tags, function(tagv, tagk) {
if(tagks.indexOf(tagk) === -1) {
tagks.push(tagk);
}
});
return tagks;
});
};
KairosDBDatasource.prototype._performMetricKeyValueLookup = function(metric, key, otherTags) {
if(!metric || !key) {
return this.q.when([]);
}
var metricsOptions = { name: metric };
if (otherTags) {
var tags = {};
var kvps = otherTags.split(',');
kvps.forEach(function(pair) {
var kv = pair.split("=");
var key = kv[0] ? kv[0].trim() : "";
var value = kv[1] ? kv[1].trim() : "";
if (key && value) {
tags[key] = value;
}
});
metricsOptions["tags"] = tags;
}
var options = {
method: 'POST',
url: this.url + '/api/v1/datapoints/query/tags',
data: {
metrics: [metricsOptions],
cache_time: 0,
start_absolute: 0
}
};
return this.backendSrv.datasourceRequest(options).then(function(result) {
if (!result.data) {
return this.q.when([]);
}
return result.data.queries[0].results[0].tags[key];
});
};
KairosDBDatasource.prototype.performTagSuggestQuery = function(metric) {
var options = {
url: this.url + '/api/v1/datapoints/query/tags',
method: 'POST',
data: {
metrics: [{ name: metric }],
cache_time: 0,
start_absolute: 0
}
};
return ibacbackendSrv.datasourceRequest(options).then(function(response) {
if (!response.data) {
return [];
}
else {
return response.data.queries[0].results[0];
}
});
};
KairosDBDatasource.prototype.metricFindQuery = function(query) {
if (!query) { return this.q.when([]); }
var interpolated;
try {
interpolated = this.templateSrv.replace(query);
}
catch (err) {
return this.q.reject(err);
}
var responseTransform = function(result) {
return _.map(result, function(value) {
return {text: value};
});
};
var metrics_regex = /metrics\((.*)\)/;
var tag_names_regex = /tag_names\((.*)\)/;
var tag_values_regex = /tag_values\(([^,]*),\s*([^,]*)(,\s*\w+=.+)*\)/;
var metrics_query = interpolated.match(metrics_regex);
if (metrics_query) {
return this._performMetricSuggestQuery(metrics_query[1]).then(responseTransform);
}
var tag_names_query = interpolated.match(tag_names_regex);
if (tag_names_query) {
return this._performMetricKeyLookup(tag_names_query[1]).then(responseTransform);
}
var tag_values_query = interpolated.match(tag_values_regex);
if (tag_values_query) {
return this._performMetricKeyValueLookup(tag_values_query[1], tag_values_query[2], tag_values_query[3]).then(responseTransform);
}
return this.q.when([]);
};
/////////////////////////////////////////////////////////////////////////
/// Formatting methods
////////////////////////////////////////////////////////////////////////
/**
* Requires a verion of KairosDB with every CORS defects fixed
* @param results
* @returns {*}
*/
function handleQueryError(results) {
if (results.data.errors && !_.isEmpty(results.data.errors)) {
var errors = {
message: results.data.errors[0]
};
return self.q.reject(errors);
}
else {
return self.q.reject(results);
}
}
function handleKairosDBQueryResponse(plotParams, results) {
var output = [];
var index = 0;
_.each(results.data.queries, function(series) {
_.each(series.results, function(result) {
var target = plotParams[index].alias;
var details = " ( ";
_.each(result.group_by, function(element) {
if (element.name === "tag") {
_.each(element.group, function(value, key) {
details += key + "=" + value + " ";
});
}
else if (element.name === "value") {
details += 'value_group=' + element.group.group_number + " ";
}
else if (element.name === "time") {
details += 'time_group=' + element.group.group_number + " ";
}
});
details += ") ";
if (details !== " ( ) ") {
target += details;
}
var datapoints = [];
for (var i = 0; i < result.values.length; i++) {
var t = Math.floor(result.values[i][0]);
var v = result.values[i][1];
datapoints[i] = [v, t];
}
if (plotParams[index].exouter) {
datapoints = new PeakFilter(datapoints, 10);
}
output.push({ target: target, datapoints: datapoints });
});
index++;
});
return { data: _.flatten(output) };
}
function convertTargetToQuery(options, target) {
if (!target.metric || target.hide) {
return null;
}
var query = {
name: self.templateSrv.replace(target.metric)
};
query.aggregators = [];
if (target.horizontalAggregators) {
_.each(target.horizontalAggregators, function(chosenAggregator) {
var returnedAggregator = {
name:chosenAggregator.name
};
if (chosenAggregator.sampling_rate) {
returnedAggregator.sampling = self.convertToKairosInterval(chosenAggregator.sampling_rate);
returnedAggregator.align_sampling = true;
//returnedAggregator.align_start_time = true;
}
if (chosenAggregator.unit) {
returnedAggregator.unit = chosenAggregator.unit + 's';
}
if (chosenAggregator.factor && chosenAggregator.name === 'div') {
returnedAggregator.divisor = chosenAggregator.factor;
}
else if (chosenAggregator.factor && chosenAggregator.name === 'scale') {
returnedAggregator.factor = chosenAggregator.factor;
}
if (chosenAggregator.percentile) {
returnedAggregator.percentile = chosenAggregator.percentile;
}
query.aggregators.push(returnedAggregator);
});
}
if (_.isEmpty(query.aggregators)) {
delete query.aggregators;
}
if (target.tags) {
query.tags = angular.copy(target.tags);
_.forOwn(query.tags, function(value, key) {
query.tags[key] = _.map(value, function(tag) { return self.templateSrv.replace(tag); });
});
}
if (target.groupByTags || target.nonTagGroupBys) {
query.group_by = [];
if (target.groupByTags) {
query.group_by.push({
name: "tag",
tags: _.map(angular.copy(target.groupByTags), function(tag) { return self.templateSrv.replace(tag); })
});
}
if (target.nonTagGroupBys) {
_.each(target.nonTagGroupBys, function(rawGroupBy) {
var formattedGroupBy = angular.copy(rawGroupBy);
if (formattedGroupBy.name === 'time') {
formattedGroupBy.range_size = self.convertToKairosInterval(formattedGroupBy.range_size);
}
query.group_by.push(formattedGroupBy);
});
}
}
return query;
}
///////////////////////////////////////////////////////////////////////
/// Time conversion functions specifics to KairosDB
//////////////////////////////////////////////////////////////////////
KairosDBDatasource.prototype.convertToKairosInterval = function(intervalString) {
intervalString = self.templateSrv.replace(intervalString);
var interval_regex = /(\d+(?:\.\d+)?)([Mwdhmsy])/;
var interval_regex_ms = /(\d+(?:\.\d+)?)(ms)/;
var matches = intervalString.match(interval_regex_ms);
if (!matches) {
matches = intervalString.match(interval_regex);
}
if (!matches) {
throw new Error('Invalid interval string, expecting a number followed by one of "y M w d h m s ms"');
}
var value = matches[1];
var unit = matches[2];
if (value%1 !== 0) {
if (unit === 'ms') {
throw new Error('Invalid interval value, cannot be smaller than the millisecond');
}
value = Math.round(kbn.intervals_in_seconds[unit] * value * 1000);
unit = 'ms';
}
return {
value: value,
unit: convertToKairosDBTimeUnit(unit)
};
};
function convertToKairosTime(date, response_obj, start_stop_name) {
var name;
if (_.isString(date)) {
if (date === 'now') {
return;
}
else if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) {
date = date.substring(4);
name = start_stop_name + "_relative";
var re_date = /(\d+)\s*(\D+)/;
var result = re_date.exec(date);
if (result) {
var value = result[1];
var unit = result[2];
response_obj[name] = {
value: value,
unit: convertToKairosDBTimeUnit(unit)
};
return;
}
console.log("Unparseable date", date);
return;
}
date = dateMath.parse(date, start_stop_name === 'end');
}
name = start_stop_name + "_absolute";
response_obj[name] = date.valueOf();
}
function convertToKairosDBTimeUnit(unit) {
switch (unit) {
case 'ms':
return 'milliseconds';
case 's':
return 'seconds';
case 'm':
return 'minutes';
case 'h':
return 'hours';
case 'd':
return 'days';
case 'w':
return 'weeks';
case 'M':
return 'months';
case 'y':
return 'years';
default:
console.log("Unknown unit ", unit);
return '';
}
}
function PeakFilter(dataIn, limit) {
var datapoints = dataIn;
var arrLength = datapoints.length;
if (arrLength <= 3) {
return datapoints;
}
var LastIndx = arrLength - 1;
// Check first point
var prvDelta = Math.abs((datapoints[1][0] - datapoints[0][0]) / datapoints[0][0]);
var nxtDelta = Math.abs((datapoints[1][0] - datapoints[2][0]) / datapoints[2][0]);
if (prvDelta >= limit && nxtDelta < limit) {
datapoints[0][0] = datapoints[1][0];
}
// Check last point
prvDelta = Math.abs((datapoints[LastIndx - 1][0] - datapoints[LastIndx - 2][0]) / datapoints[LastIndx - 2][0]);
nxtDelta = Math.abs((datapoints[LastIndx - 1][0] - datapoints[LastIndx][0]) / datapoints[LastIndx][0]);
if (prvDelta >= limit && nxtDelta < limit) {
datapoints[LastIndx][0] = datapoints[LastIndx - 1][0];
}
for (var i = 1; i < arrLength - 1; i++) {
prvDelta = Math.abs((datapoints[i][0] - datapoints[i - 1][0]) / datapoints[i - 1][0]);
nxtDelta = Math.abs((datapoints[i][0] - datapoints[i + 1][0]) / datapoints[i + 1][0]);
if (prvDelta >= limit && nxtDelta >= limit) {
datapoints[i][0] = (datapoints[i - 1][0] + datapoints[i + 1][0]) / 2;
}
}
return datapoints;
}
return KairosDBDatasource;
});