datasource.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'kbn',
  5. 'moment',
  6. 'app/core/utils/datemath',
  7. './directives',
  8. './queryCtrl',
  9. ],
  10. function (angular, _, kbn, dateMath) {
  11. 'use strict';
  12. var module = angular.module('grafana.services');
  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 sec = kbn.interval_to_seconds(interval);
  155. if (sec < 1) {
  156. sec = 1;
  157. }
  158. return sec * intervalFactor;
  159. };
  160. function transformMetricData(md, options) {
  161. var dps = [],
  162. metricLabel = null;
  163. metricLabel = createMetricLabel(md.metric, options);
  164. dps = _.map(md.values, function(value) {
  165. return [parseFloat(value[1]), value[0] * 1000];
  166. });
  167. return { target: metricLabel, datapoints: dps };
  168. }
  169. function createMetricLabel(labelData, options) {
  170. if (_.isUndefined(options) || _.isEmpty(options.legendFormat)) {
  171. return getOriginalMetricName(labelData);
  172. }
  173. var originalSettings = _.templateSettings;
  174. _.templateSettings = {
  175. interpolate: /\{\{(.+?)\}\}/g
  176. };
  177. var template = _.template(templateSrv.replace(options.legendFormat));
  178. var metricName;
  179. try {
  180. metricName = template(labelData);
  181. } catch (e) {
  182. metricName = '{}';
  183. }
  184. _.templateSettings = originalSettings;
  185. return metricName;
  186. }
  187. function getOriginalMetricName(labelData) {
  188. var metricName = labelData.__name__ || '';
  189. delete labelData.__name__;
  190. var labelPart = _.map(_.pairs(labelData), function(label) {
  191. return label[0] + '="' + label[1] + '"';
  192. }).join(',');
  193. return metricName + '{' + labelPart + '}';
  194. }
  195. function getPrometheusTime(date, roundUp) {
  196. if (_.isString(date)) {
  197. if (date === 'now') {
  198. return 'now()';
  199. }
  200. if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) {
  201. return date.replace('now', 'now()').replace('-', ' - ');
  202. }
  203. date = dateMath.parse(date, roundUp);
  204. }
  205. return (date.valueOf() / 1000).toFixed(0);
  206. }
  207. return PrometheusDatasource;
  208. });
  209. });