datasource.js 14 KB

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