datasource.js 14 KB

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