datasource.js 12 KB

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