datasource.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'moment',
  5. 'app/core/utils/datemath',
  6. './directives',
  7. './queryCtrl',
  8. ],
  9. function (angular, _, moment, dateMath) {
  10. 'use strict';
  11. var module = angular.module('grafana.services');
  12. var durationSplitRegexp = /(\d+)(ms|s|m|h|d|w|M|y)/;
  13. module.factory('PrometheusDatasource', function($q, backendSrv, templateSrv) {
  14. function PrometheusDatasource(datasource) {
  15. this.type = 'prometheus';
  16. this.editorSrc = 'app/features/prometheus/partials/query.editor.html';
  17. this.name = datasource.name;
  18. this.supportMetrics = true;
  19. var url = datasource.url;
  20. if (url[url.length-1] === '/') {
  21. // remove trailing slash
  22. url = url.substr(0, url.length - 1);
  23. }
  24. this.url = url;
  25. this.basicAuth = datasource.basicAuth;
  26. this.lastErrors = {};
  27. }
  28. PrometheusDatasource.prototype._request = function(method, url) {
  29. var options = {
  30. url: this.url + url,
  31. method: method
  32. };
  33. if (this.basicAuth) {
  34. options.withCredentials = true;
  35. options.headers = {
  36. "Authorization": this.basicAuth
  37. };
  38. }
  39. return backendSrv.datasourceRequest(options);
  40. };
  41. // Called once per panel (graph)
  42. PrometheusDatasource.prototype.query = function(options) {
  43. var start = getPrometheusTime(options.range.from, false);
  44. var end = getPrometheusTime(options.range.to, true);
  45. var queries = [];
  46. _.each(options.targets, _.bind(function(target) {
  47. if (!target.expr || target.hide) {
  48. return;
  49. }
  50. var query = {};
  51. query.expr = templateSrv.replace(target.expr, options.scopedVars);
  52. var interval = target.interval || options.interval;
  53. var intervalFactor = target.intervalFactor || 1;
  54. query.step = this.calculateInterval(interval, intervalFactor);
  55. queries.push(query);
  56. }, this));
  57. // No valid targets, return the empty result to save a round trip.
  58. if (_.isEmpty(queries)) {
  59. var d = $q.defer();
  60. d.resolve({ data: [] });
  61. return d.promise;
  62. }
  63. var allQueryPromise = _.map(queries, _.bind(function(query) {
  64. return this.performTimeSeriesQuery(query, start, end);
  65. }, this));
  66. var self = this;
  67. return $q.all(allQueryPromise)
  68. .then(function(allResponse) {
  69. var result = [];
  70. _.each(allResponse, function(response, index) {
  71. if (response.status === 'error') {
  72. self.lastErrors.query = response.error;
  73. throw response.error;
  74. }
  75. delete self.lastErrors.query;
  76. _.each(response.data.data.result, function(metricData) {
  77. result.push(transformMetricData(metricData, options.targets[index]));
  78. });
  79. });
  80. return { data: result };
  81. });
  82. };
  83. PrometheusDatasource.prototype.performTimeSeriesQuery = function(query, start, end) {
  84. var url = '/api/v1/query_range?query=' + encodeURIComponent(query.expr) + '&start=' + start + '&end=' + end;
  85. var step = query.step;
  86. var range = Math.floor(end - start);
  87. // Prometheus drop query if range/step > 11000
  88. // calibrate step if it is too big
  89. if (step !== 0 && range / step > 11000) {
  90. step = Math.floor(range / 11000);
  91. }
  92. url += '&step=' + step;
  93. return this._request('GET', url);
  94. };
  95. PrometheusDatasource.prototype.performSuggestQuery = function(query) {
  96. var url = '/api/v1/label/__name__/values';
  97. return this._request('GET', url).then(function(result) {
  98. var suggestData = _.filter(result.data.data, function(metricName) {
  99. return metricName.indexOf(query) !== 1;
  100. });
  101. return suggestData;
  102. });
  103. };
  104. PrometheusDatasource.prototype.metricFindQuery = function(query) {
  105. if (!query) { return $q.when([]); }
  106. var interpolated;
  107. try {
  108. interpolated = templateSrv.replace(query);
  109. }
  110. catch (err) {
  111. return $q.reject(err);
  112. }
  113. var label_values_regex = /^label_values\(([^,]+)(?:,\s*(.+))?\)$/;
  114. var metric_names_regex = /^metrics\((.+)\)$/;
  115. var url;
  116. var label_values_query = interpolated.match(label_values_regex);
  117. if (label_values_query) {
  118. if (!label_values_query[2]) {
  119. // return label values globally
  120. url = '/api/v1/label/' + label_values_query[1] + '/values';
  121. return this._request('GET', url).then(function(result) {
  122. return _.map(result.data.data, function(value) {
  123. return {text: value};
  124. });
  125. });
  126. } else {
  127. var metric_query = 'count(' + label_values_query[1] + ') by (' +
  128. label_values_query[2] + ')';
  129. url = '/api/v1/query?query=' + encodeURIComponent(metric_query) +
  130. '&time=' + (moment().valueOf() / 1000);
  131. return this._request('GET', url)
  132. .then(function(result) {
  133. if (result.data.data.result.length === 0 ||
  134. _.keys(result.data.data.result[0].metric).length === 0) {
  135. return [];
  136. }
  137. return _.map(result.data.data.result, function(metricValue) {
  138. return {
  139. text: metricValue.metric[label_values_query[2]],
  140. expandable: true
  141. };
  142. });
  143. });
  144. }
  145. }
  146. var metric_names_query = interpolated.match(metric_names_regex);
  147. if (metric_names_query) {
  148. url = '/api/v1/label/__name__/values';
  149. return this._request('GET', url)
  150. .then(function(result) {
  151. return _.chain(result.data.data)
  152. .filter(function(metricName) {
  153. var r = new RegExp(metric_names_query[1]);
  154. return r.test(metricName);
  155. })
  156. .map(function(matchedMetricName) {
  157. return {
  158. text: matchedMetricName,
  159. expandable: true
  160. };
  161. })
  162. .value();
  163. });
  164. } else {
  165. // if query contains full metric name, return metric name and label list
  166. url = '/api/v1/query?query=' + encodeURIComponent(interpolated) +
  167. '&time=' + (moment().valueOf() / 1000);
  168. return this._request('GET', url)
  169. .then(function(result) {
  170. return _.map(result.data.data.result, function(metricData) {
  171. return {
  172. text: getOriginalMetricName(metricData.metric),
  173. expandable: true
  174. };
  175. });
  176. });
  177. }
  178. };
  179. PrometheusDatasource.prototype.testDatasource = function() {
  180. return this.metricFindQuery('*').then(function() {
  181. return { status: 'success', message: 'Data source is working', title: 'Success' };
  182. });
  183. };
  184. PrometheusDatasource.prototype.calculateInterval = function(interval, intervalFactor) {
  185. var m = interval.match(durationSplitRegexp);
  186. var dur = moment.duration(parseInt(m[1]), m[2]);
  187. var sec = dur.asSeconds();
  188. if (sec < 1) {
  189. sec = 1;
  190. }
  191. return Math.floor(sec * intervalFactor) + 's';
  192. };
  193. function transformMetricData(md, options) {
  194. var dps = [],
  195. metricLabel = null;
  196. metricLabel = createMetricLabel(md.metric, options);
  197. dps = _.map(md.values, function(value) {
  198. return [parseFloat(value[1]), value[0] * 1000];
  199. });
  200. return { target: metricLabel, datapoints: dps };
  201. }
  202. function createMetricLabel(labelData, options) {
  203. if (_.isUndefined(options) || _.isEmpty(options.legendFormat)) {
  204. return getOriginalMetricName(labelData);
  205. }
  206. var originalSettings = _.templateSettings;
  207. _.templateSettings = {
  208. interpolate: /\{\{(.+?)\}\}/g
  209. };
  210. var template = _.template(templateSrv.replace(options.legendFormat));
  211. var metricName;
  212. try {
  213. metricName = template(labelData);
  214. } catch (e) {
  215. metricName = '{}';
  216. }
  217. _.templateSettings = originalSettings;
  218. return metricName;
  219. }
  220. function getOriginalMetricName(labelData) {
  221. var metricName = labelData.__name__ || '';
  222. delete labelData.__name__;
  223. var labelPart = _.map(_.pairs(labelData), function(label) {
  224. return label[0] + '="' + label[1] + '"';
  225. }).join(',');
  226. return metricName + '{' + labelPart + '}';
  227. }
  228. function getPrometheusTime(date, roundUp) {
  229. if (_.isString(date)) {
  230. if (date === 'now') {
  231. return 'now()';
  232. }
  233. if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) {
  234. return date.replace('now', 'now()').replace('-', ' - ');
  235. }
  236. date = dateMath.parse(date, roundUp);
  237. }
  238. return (date.valueOf() / 1000).toFixed(0);
  239. }
  240. return PrometheusDatasource;
  241. });
  242. });