datasource.js 12 KB

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