datasource.js 14 KB

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