datasource.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. var url;
  106. var metricsQuery = query.match(/^[a-zA-Z_:*][a-zA-Z0-9_:*]*/);
  107. var labelValuesQuery = query.match(/^label_values\((.+)\)/);
  108. if (labelValuesQuery) {
  109. // return label values
  110. url = '/api/v1/label/' + labelValuesQuery[1] + '/values';
  111. return this._request('GET', url).then(function(result) {
  112. return _.map(result.data.data, function(value) {
  113. return {text: value};
  114. });
  115. });
  116. } else if (metricsQuery != null && metricsQuery[0].indexOf('*') >= 0) {
  117. // if query has wildcard character, return metric name list
  118. url = '/api/v1/label/__name__/values';
  119. return this._request('GET', url)
  120. .then(function(result) {
  121. return _.chain(result.data.data)
  122. .filter(function(metricName) {
  123. var r = new RegExp(metricsQuery[0].replace(/\*/g, '.*'));
  124. return r.test(metricName);
  125. })
  126. .map(function(matchedMetricName) {
  127. return {
  128. text: matchedMetricName,
  129. expandable: true
  130. };
  131. })
  132. .value();
  133. });
  134. } else {
  135. // if query contains full metric name, return metric name and label list
  136. url = '/api/v1/query?query=' + encodeURIComponent(query);
  137. return this._request('GET', url)
  138. .then(function(result) {
  139. return _.map(result.data.result, function(metricData) {
  140. return {
  141. text: getOriginalMetricName(metricData.metric),
  142. expandable: true
  143. };
  144. });
  145. });
  146. }
  147. };
  148. PrometheusDatasource.prototype.testDatasource = function() {
  149. return this.metricFindQuery('*').then(function() {
  150. return { status: 'success', message: 'Data source is working', title: 'Success' };
  151. });
  152. };
  153. PrometheusDatasource.prototype.calculateInterval = function(interval, intervalFactor) {
  154. var m = interval.match(durationSplitRegexp);
  155. var dur = moment.duration(parseInt(m[1]), m[2]);
  156. var sec = dur.asSeconds();
  157. if (sec < 1) {
  158. sec = 1;
  159. }
  160. return Math.floor(sec * intervalFactor) + 's';
  161. };
  162. function transformMetricData(md, options) {
  163. var dps = [],
  164. metricLabel = null;
  165. metricLabel = createMetricLabel(md.metric, options);
  166. dps = _.map(md.values, function(value) {
  167. return [parseFloat(value[1]), value[0] * 1000];
  168. });
  169. return { target: metricLabel, datapoints: dps };
  170. }
  171. function createMetricLabel(labelData, options) {
  172. if (_.isUndefined(options) || _.isEmpty(options.legendFormat)) {
  173. return getOriginalMetricName(labelData);
  174. }
  175. var originalSettings = _.templateSettings;
  176. _.templateSettings = {
  177. interpolate: /\{\{(.+?)\}\}/g
  178. };
  179. var template = _.template(templateSrv.replace(options.legendFormat));
  180. var metricName;
  181. try {
  182. metricName = template(labelData);
  183. } catch (e) {
  184. metricName = '{}';
  185. }
  186. _.templateSettings = originalSettings;
  187. return metricName;
  188. }
  189. function getOriginalMetricName(labelData) {
  190. var metricName = labelData.__name__ || '';
  191. delete labelData.__name__;
  192. var labelPart = _.map(_.pairs(labelData), function(label) {
  193. return label[0] + '="' + label[1] + '"';
  194. }).join(',');
  195. return metricName + '{' + labelPart + '}';
  196. }
  197. function getPrometheusTime(date, roundUp) {
  198. if (_.isString(date)) {
  199. if (date === 'now') {
  200. return 'now()';
  201. }
  202. if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) {
  203. return date.replace('now', 'now()').replace('-', ' - ');
  204. }
  205. date = dateMath.parse(date, roundUp);
  206. }
  207. return (date.valueOf() / 1000).toFixed(0);
  208. }
  209. return PrometheusDatasource;
  210. });
  211. });