datasource.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'kbn',
  5. './queryCtrl',
  6. ],
  7. function (angular, _, kbn) {
  8. 'use strict';
  9. var module = angular.module('grafana.services');
  10. module.factory('KairosDBDatasource', function($q, $http, templateSrv) {
  11. function KairosDBDatasource(datasource) {
  12. this.type = datasource.type;
  13. this.editorSrc = 'plugins/datasources/kairosdb/kairosdb.editor.html';
  14. this.url = datasource.url;
  15. this.name = datasource.name;
  16. this.supportMetrics = true;
  17. }
  18. // Called once per panel (graph)
  19. KairosDBDatasource.prototype.query = function(options) {
  20. var start = options.range.from;
  21. var end = options.range.to;
  22. var queries = _.compact(_.map(options.targets, _.partial(convertTargetToQuery, options)));
  23. var plotParams = _.compact(_.map(options.targets, function(target) {
  24. var alias = target.alias;
  25. if (typeof target.alias === 'undefined' || target.alias === "") {
  26. alias = target.metric;
  27. }
  28. if (!target.hide) {
  29. return { alias: alias, exouter: target.exOuter };
  30. }
  31. else {
  32. return null;
  33. }
  34. }));
  35. var handleKairosDBQueryResponseAlias = _.partial(handleKairosDBQueryResponse, plotParams);
  36. // No valid targets, return the empty result to save a round trip.
  37. if (_.isEmpty(queries)) {
  38. var d = $q.defer();
  39. d.resolve({ data: [] });
  40. return d.promise;
  41. }
  42. return this.performTimeSeriesQuery(queries, start, end).then(handleKairosDBQueryResponseAlias, handleQueryError);
  43. };
  44. ///////////////////////////////////////////////////////////////////////
  45. /// Query methods
  46. ///////////////////////////////////////////////////////////////////////
  47. KairosDBDatasource.prototype.performTimeSeriesQuery = function(queries, start, end) {
  48. var reqBody = {
  49. metrics: queries,
  50. cache_time: 0
  51. };
  52. convertToKairosTime(start, reqBody, 'start');
  53. convertToKairosTime(end, reqBody, 'end');
  54. var options = {
  55. method: 'POST',
  56. url: this.url + '/api/v1/datapoints/query',
  57. data: reqBody
  58. };
  59. return $http(options);
  60. };
  61. /**
  62. * Gets the list of metrics
  63. * @returns {*|Promise}
  64. */
  65. KairosDBDatasource.prototype.performMetricSuggestQuery = function() {
  66. var options = {
  67. url : this.url + '/api/v1/metricnames',
  68. method : 'GET'
  69. };
  70. return $http(options).then(function(response) {
  71. if (!response.data) {
  72. return [];
  73. }
  74. return response.data.results;
  75. });
  76. };
  77. KairosDBDatasource.prototype.performListTagNames = function() {
  78. var options = {
  79. url : this.url + '/api/v1/tagnames',
  80. method : 'GET'
  81. };
  82. return $http(options).then(function(response) {
  83. if (!response.data) {
  84. return [];
  85. }
  86. return response.data.results;
  87. });
  88. };
  89. KairosDBDatasource.prototype.performListTagValues = function() {
  90. var options = {
  91. url : this.url + '/api/v1/tagvalues',
  92. method : 'GET'
  93. };
  94. return $http(options).then(function(response) {
  95. if (!response.data) {
  96. return [];
  97. }
  98. return response.data.results;
  99. });
  100. };
  101. KairosDBDatasource.prototype.performTagSuggestQuery = function(metricname) {
  102. var options = {
  103. url : this.url + '/api/v1/datapoints/query/tags',
  104. method : 'POST',
  105. data : {
  106. metrics : [{ name : metricname }],
  107. cache_time : 0,
  108. start_absolute: 0
  109. }
  110. };
  111. return $http(options).then(function(response) {
  112. if (!response.data) {
  113. return [];
  114. }
  115. else {
  116. return response.data.queries[0].results[0];
  117. }
  118. });
  119. };
  120. KairosDBDatasource.prototype.metricFindQuery = function(query) {
  121. function format(results, query) {
  122. return _.chain(results)
  123. .filter(function(result) {
  124. return result.indexOf(query) >= 0;
  125. })
  126. .map(function(result) {
  127. return {
  128. text: result,
  129. expandable: true
  130. };
  131. })
  132. .value();
  133. }
  134. var interpolated;
  135. try {
  136. interpolated = templateSrv.replace(query);
  137. }
  138. catch (err) {
  139. return $q.reject(err);
  140. }
  141. var metrics_regex = /metrics\((.*)\)/;
  142. var tag_names_regex = /tag_names\((.*)\)/;
  143. var tag_values_regex = /tag_values\((.*)\)/;
  144. var metrics_query = interpolated.match(metrics_regex);
  145. if (metrics_query) {
  146. return this.performMetricSuggestQuery().then(function(metrics) {
  147. return format(metrics, metrics_query[1]);
  148. });
  149. }
  150. var tag_names_query = interpolated.match(tag_names_regex);
  151. if (tag_names_query) {
  152. return this.performListTagNames().then(function(tag_names) {
  153. return format(tag_names, tag_names_query[1]);
  154. });
  155. }
  156. var tag_values_query = interpolated.match(tag_values_regex);
  157. if (tag_values_query) {
  158. return this.performListTagValues().then(function(tag_values) {
  159. return format(tag_values, tag_values_query[1]);
  160. });
  161. }
  162. };
  163. /////////////////////////////////////////////////////////////////////////
  164. /// Formatting methods
  165. ////////////////////////////////////////////////////////////////////////
  166. /**
  167. * Requires a verion of KairosDB with every CORS defects fixed
  168. * @param results
  169. * @returns {*}
  170. */
  171. function handleQueryError(results) {
  172. if (results.data.errors && !_.isEmpty(results.data.errors)) {
  173. var errors = {
  174. message: results.data.errors[0]
  175. };
  176. return $q.reject(errors);
  177. }
  178. else {
  179. return $q.reject(results);
  180. }
  181. }
  182. function handleKairosDBQueryResponse(plotParams, results) {
  183. var output = [];
  184. var index = 0;
  185. _.each(results.data.queries, function(series) {
  186. _.each(series.results, function(result) {
  187. var target = plotParams[index].alias;
  188. var details = " ( ";
  189. _.each(result.group_by, function(element) {
  190. if (element.name === "tag") {
  191. _.each(element.group, function(value, key) {
  192. details += key + "=" + value + " ";
  193. });
  194. }
  195. else if (element.name === "value") {
  196. details += 'value_group=' + element.group.group_number + " ";
  197. }
  198. else if (element.name === "time") {
  199. details += 'time_group=' + element.group.group_number + " ";
  200. }
  201. });
  202. details += ") ";
  203. if (details !== " ( ) ") {
  204. target += details;
  205. }
  206. var datapoints = [];
  207. for (var i = 0; i < result.values.length; i++) {
  208. var t = Math.floor(result.values[i][0]);
  209. var v = result.values[i][1];
  210. datapoints[i] = [v, t];
  211. }
  212. if (plotParams[index].exouter) {
  213. datapoints = new PeakFilter(datapoints, 10);
  214. }
  215. output.push({ target: target, datapoints: datapoints });
  216. });
  217. index++;
  218. });
  219. return { data: _.flatten(output) };
  220. }
  221. function convertTargetToQuery(options, target) {
  222. if (!target.metric || target.hide) {
  223. return null;
  224. }
  225. var query = {
  226. name: templateSrv.replace(target.metric)
  227. };
  228. query.aggregators = [];
  229. if (target.downsampling !== '(NONE)') {
  230. query.aggregators.push({
  231. name: target.downsampling,
  232. align_sampling: true,
  233. align_start_time: true,
  234. sampling: KairosDBDatasource.prototype.convertToKairosInterval(target.sampling || options.interval)
  235. });
  236. }
  237. if (target.horizontalAggregators) {
  238. _.each(target.horizontalAggregators, function(chosenAggregator) {
  239. var returnedAggregator = {
  240. name:chosenAggregator.name
  241. };
  242. if (chosenAggregator.sampling_rate) {
  243. returnedAggregator.sampling = KairosDBDatasource.prototype.convertToKairosInterval(chosenAggregator.sampling_rate);
  244. returnedAggregator.align_sampling = true;
  245. returnedAggregator.align_start_time =true;
  246. }
  247. if (chosenAggregator.unit) {
  248. returnedAggregator.unit = chosenAggregator.unit + 's';
  249. }
  250. if (chosenAggregator.factor && chosenAggregator.name === 'div') {
  251. returnedAggregator.divisor = chosenAggregator.factor;
  252. }
  253. else if (chosenAggregator.factor && chosenAggregator.name === 'scale') {
  254. returnedAggregator.factor = chosenAggregator.factor;
  255. }
  256. if (chosenAggregator.percentile) {
  257. returnedAggregator.percentile = chosenAggregator.percentile;
  258. }
  259. query.aggregators.push(returnedAggregator);
  260. });
  261. }
  262. if (_.isEmpty(query.aggregators)) {
  263. delete query.aggregators;
  264. }
  265. if (target.tags) {
  266. query.tags = angular.copy(target.tags);
  267. _.forOwn(query.tags, function(value, key) {
  268. query.tags[key] = _.map(value, function(tag) { return templateSrv.replace(tag); });
  269. });
  270. }
  271. if (target.groupByTags || target.nonTagGroupBys) {
  272. query.group_by = [];
  273. if (target.groupByTags) {
  274. query.group_by.push({
  275. name: "tag",
  276. tags: _.map(angular.copy(target.groupByTags), function(tag) { return templateSrv.replace(tag); })
  277. });
  278. }
  279. if (target.nonTagGroupBys) {
  280. _.each(target.nonTagGroupBys, function(rawGroupBy) {
  281. var formattedGroupBy = angular.copy(rawGroupBy);
  282. if (formattedGroupBy.name === 'time') {
  283. formattedGroupBy.range_size = KairosDBDatasource.prototype.convertToKairosInterval(formattedGroupBy.range_size);
  284. }
  285. query.group_by.push(formattedGroupBy);
  286. });
  287. }
  288. }
  289. return query;
  290. }
  291. ///////////////////////////////////////////////////////////////////////
  292. /// Time conversion functions specifics to KairosDB
  293. //////////////////////////////////////////////////////////////////////
  294. KairosDBDatasource.prototype.convertToKairosInterval = function(intervalString) {
  295. intervalString = templateSrv.replace(intervalString);
  296. var interval_regex = /(\d+(?:\.\d+)?)([Mwdhmsy])/;
  297. var interval_regex_ms = /(\d+(?:\.\d+)?)(ms)/;
  298. var matches = intervalString.match(interval_regex_ms);
  299. if (!matches) {
  300. matches = intervalString.match(interval_regex);
  301. }
  302. if (!matches) {
  303. throw new Error('Invalid interval string, expecting a number followed by one of "y M w d h m s ms"');
  304. }
  305. var value = matches[1];
  306. var unit = matches[2];
  307. if (value%1 !== 0) {
  308. if (unit === 'ms') {
  309. throw new Error('Invalid interval value, cannot be smaller than the millisecond');
  310. }
  311. value = Math.round(kbn.intervals_in_seconds[unit] * value * 1000);
  312. unit = 'ms';
  313. }
  314. return {
  315. value: value,
  316. unit: convertToKairosDBTimeUnit(unit)
  317. };
  318. };
  319. function convertToKairosTime(date, response_obj, start_stop_name) {
  320. var name;
  321. if (_.isString(date)) {
  322. if (date === 'now') {
  323. return;
  324. }
  325. else if (date.indexOf('now-') >= 0) {
  326. date = date.substring(4);
  327. name = start_stop_name + "_relative";
  328. var re_date = /(\d+)\s*(\D+)/;
  329. var result = re_date.exec(date);
  330. if (result) {
  331. var value = result[1];
  332. var unit = result[2];
  333. response_obj[name] = {
  334. value: value,
  335. unit: convertToKairosDBTimeUnit(unit)
  336. };
  337. return;
  338. }
  339. console.log("Unparseable date", date);
  340. return;
  341. }
  342. date = kbn.parseDate(date);
  343. }
  344. if (_.isDate(date)) {
  345. name = start_stop_name + "_absolute";
  346. response_obj[name] = date.getTime();
  347. return;
  348. }
  349. console.log("Date is neither string nor date");
  350. }
  351. function convertToKairosDBTimeUnit(unit) {
  352. switch (unit) {
  353. case 'ms':
  354. return 'milliseconds';
  355. case 's':
  356. return 'seconds';
  357. case 'm':
  358. return 'minutes';
  359. case 'h':
  360. return 'hours';
  361. case 'd':
  362. return 'days';
  363. case 'w':
  364. return 'weeks';
  365. case 'M':
  366. return 'months';
  367. case 'y':
  368. return 'years';
  369. default:
  370. console.log("Unknown unit ", unit);
  371. return '';
  372. }
  373. }
  374. function PeakFilter(dataIn, limit) {
  375. var datapoints = dataIn;
  376. var arrLength = datapoints.length;
  377. if (arrLength <= 3) {
  378. return datapoints;
  379. }
  380. var LastIndx = arrLength - 1;
  381. // Check first point
  382. var prvDelta = Math.abs((datapoints[1][0] - datapoints[0][0]) / datapoints[0][0]);
  383. var nxtDelta = Math.abs((datapoints[1][0] - datapoints[2][0]) / datapoints[2][0]);
  384. if (prvDelta >= limit && nxtDelta < limit) {
  385. datapoints[0][0] = datapoints[1][0];
  386. }
  387. // Check last point
  388. prvDelta = Math.abs((datapoints[LastIndx - 1][0] - datapoints[LastIndx - 2][0]) / datapoints[LastIndx - 2][0]);
  389. nxtDelta = Math.abs((datapoints[LastIndx - 1][0] - datapoints[LastIndx][0]) / datapoints[LastIndx][0]);
  390. if (prvDelta >= limit && nxtDelta < limit) {
  391. datapoints[LastIndx][0] = datapoints[LastIndx - 1][0];
  392. }
  393. for (var i = 1; i < arrLength - 1; i++) {
  394. prvDelta = Math.abs((datapoints[i][0] - datapoints[i - 1][0]) / datapoints[i - 1][0]);
  395. nxtDelta = Math.abs((datapoints[i][0] - datapoints[i + 1][0]) / datapoints[i + 1][0]);
  396. if (prvDelta >= limit && nxtDelta >= limit) {
  397. datapoints[i][0] = (datapoints[i - 1][0] + datapoints[i + 1][0]) / 2;
  398. }
  399. }
  400. return datapoints;
  401. }
  402. return KairosDBDatasource;
  403. });
  404. });