datasource.js 8.5 KB

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